# Sandbox for Proposed Challenges

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

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
• 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 needs more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended!

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".

Get the Sandbox Viewer to view the sandbox more easily!

## Leave ABACABA on the tape

Note that will be removed post sandboxing: This challenge is Brainfuck-specific, but I hope that its contents make the reason why sufficiently clear.

Write a brainfuck program which leaves the following sequence on the tape:

0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 ...


This sequence may be familiar to some as ABACABADABACABA... or A007814.

Assume an implementation of BF with an endless tape and arbitrarily large (but not arbitrarily small) integers.

You should link to a visualizer to prove that your program works as you say it does, but if this isn't fast enough to witness the first few (say 4) numbers in ABACABA you'll have to explain it yourself.

This is code-golf, so the shortest program operating within these rules wins. Have fun!

• Because a BF program would likely do destructive edits to the previous terms or add scratch data to the end while advancing the sequence, I'd propose a more rigorous definition: "Write a BF program where, given any prefix of the ABACABA sequence, running the program for some finite number of steps will give the pattern at the start of the tape." Nov 18 '21 at 1:32

# Light-Cycle KotH

• I'd recommend removing all bots that crash in the same turn. Basing it off of external factors like submission dates is a bit unfair. Sep 13 '21 at 17:04
• My justification for removing only 1 per turn is that it simplifies the logic of generating a leaderboard and removes some edge cases, otherwise things like 3-way ties for first place might be possible if all the bots crash at the same time. Sep 13 '21 at 20:51
• I feel like biasing the rules against newer submissions is fair. After all, new submissions inherently have the advantage that they're able to see the older submissions and can strategize around these existing submissions. Sep 13 '21 at 20:55
• The issue is that the oldest submissions functionally move first, meaning that being the first bot posted is a significant advantage. What about edits? If a bot is changed, does it drop to the bottom? I agree that removing all bots which crash is the right call. Sep 14 '21 at 18:36
• Hmm... I was going to disallow edits, so that anyone who wanted to update their bot must instead post it as a new bot. @Spitemaster Are edits typically allowed for KotH submission? Sep 14 '21 at 20:27
• Frequently; not always. But you've still got the problem of earlier entries effectively moving first. If you really want to do it this way, it doesn't make sense to have simultaneous movement (because it's not really simultaneous). Sep 14 '21 at 20:34
• Ok, that seems fair, I will update post to allow for simultaneous movement Sep 14 '21 at 20:49
• If I were you, I'd consider sizing the arena based on number of bots. Sep 14 '21 at 20:56
• That seems like a reasonable suggestion, what kind of scaling do you think would be good? I'm thinking maybe something like a square with side-length 2n+6, for n players. Sep 14 '21 at 21:02

# Randomly capitalize half of a string

• Will a string of length 0 ever be an input? Jun 15 '17 at 12:26
• @dzaima no, clarified by saying length will always be positive Jun 15 '17 at 13:57
• Change "positive" to "non-zero"? You can't have a negative-length string, last time I checked... Dec 1 '21 at 18:15

# Write a number in overflowed binary

• Maybe define a overflowed binary number a binary number where one or more of it's digits goes over 1? Dec 3 '21 at 17:21

# Solve an Inglenook Sidings Puzzle

Posted! After about 2 weeks in Sandbox

• @Bubbler specifically model railroading. The puzzle was made to create operational interest on small layouts, since it only needs 2 switches and 4 pieces of relatively short track Nov 25 '21 at 4:05
• So this challenge proposal has been in here for just about a week now; are there any flaws in this? I don't want to post this to the main site and get feedback that should've been caught in meta Dec 1 '21 at 16:11

# Simulate weathering

• I like this idea. I'd suggest extending the example for another iteration or two, and it wouldn't hurt to add other test cases. Just a thought (no strong opinion either way): you could remove the second input ($n$) and have the simulation run until the rock disappears, with the shape being printed at each iteration. Nov 4 '21 at 22:57
• @Dingus edited. removed the second input since outputing until the rock disappears makes more sense. Nov 5 '21 at 4:54
• First, I'd be more fluid with the I/O format - allow a bit matrix, char matrix, list of strings, etc. Also, a different idea that might warrant its own challenge: What if you just removed one rock at a time? Nov 5 '21 at 7:18

# Worst time complexity in under 100 bytes

Time complexity, typically represented in Big O notation, represents how long a program will typically take to run given some input(s), ignoring constants.

Your task is to do one of the following things, with the worst time complexity possible:

• Sort an array of integers
• Find duplicates in an array
• Find longest strictly increasing slice of an array of integers

All of the tasks involve taking one input, an array of items, in any reasonable format, and returning an array. If your language supports mutable array data types, this is an allowed output format. Assume all items in the arrays will be (not necessarily positive) integers.

If you choose sorting: You may choose to sort the array by minimum or maximum.

If you choose listing duplicates: You may include a duplicate item any number of times in the output; [1, 2, 2, 3, 4] could result in [2, 4], [2, 2, 4], or even [2, 4, 4, 4].

If you choose longest strictly increasing slice: Duplicate items do not count as increasing, so [1, 2, 2, 4] is not strictly increasing. The items do not have to increase by a steady amount; [-1, 4, 14, 16, 17] is strictly increasing.

Rules:

Your program must be 100 bytes or less. Your program should terminate in a finite amount of time. You can assume your program will never run out of memory, and it does not have to terminate before the heat death of the universe.

This is a . The winner will be based on the average time complexity, with slower being better, followed by the best case and then worst case for ties.

• Unfortunately, this answer broke all "irreducible" challenges. You can execute (almost) arbitrary code unrelated to the task without breaking the "irreducible" requirement. Apr 22 '21 at 0:16
• @Bubbler Hmm, and I don't think irreducible is a sensible requirement for this either. It definitely makes more sense with bytes than time, along with pristine. I'll have to think about some creative limitations. Maybe unique bytes only? Apr 22 '21 at 0:22
• Now this is somewhat too close to bignum computation challenge, since all the biggest numbers are actually a fast-growing function applied to some number. They can be trivially converted to take the length of the input, and then used in the algorithm in some way (or just discarded). Dec 16 '21 at 8:32
• How about this: Choose a decision problem, and write code that solves it, within 100 bytes (or use a partially ordered score instead of a byte limit). Answers are compared based on the minimal time complexity of the problem, not the implementation. So if someone solves an EXPTIME-hard problem, they beat whoever solves a problem in P. This solves the problem of people doing useless calculations, since it doesn't help them. Writing a sorting function that takes exponential time is not in any way better than just doing a sort in O(nlogn) time. Dec 16 '21 at 11:25
• @AnttiP That could be cool, but it sort of goes against what I was going for (ridiculously slow sorting algorithms). Maybe a separate challenge idea? Dec 16 '21 at 14:27

# Nth FizzBuzz Number

• Maybe allow any different 4 distinct inputs for Fizz, Buzz, FizzBuzz and Number? Dec 16 '21 at 11:48

# Light it up

• Maybe you can fill empty cells by some characters like . in your examples and testcases. Or it could be confusing: L.#. is falsy but L.# is truthy, but it is hard to see the difference.
– tsh
Nov 2 '21 at 1:53
• @tsh Ok, thanks! Nov 2 '21 at 2:02
• "some squares are walls, some are empty, and some are lights". Since there are testcases where only empty cell is there, will there be any testcases like ####?
– tsh
Nov 2 '21 at 5:23
• @tsh Yes, see the fourth truthy one. I'll be more explicit that some may not occur at all. Nov 2 '21 at 6:13

# Print □□Square□□ Numbers

Your task is to write a program or function that accepts an integer as input/argument and prints/returns all square numbers from 0 up to but not including n².

But the numbers should not just be perfect squares in the mathematical sense. They should be square in every sense. That is, the digits should

• • occupy a square space, 5 lines by 5 columns (including separating space)
• • form right angles at their joints
• • be formed entirely from □ and space characters

Actually, the digits must be shaped exactly like these:

   □ □□□□ □□□□ □  □ □□□□ □□□□ □□□□ □□□□ □□□□ □□□□
□    □    □ □  □ □    □       □ □  □ □  □ □  □
□ □□□□ □□□□ □□□□ □□□□ □□□□    □ □□□□ □□□□ □  □
□ □       □    □    □ □  □    □ □  □    □ □  □
□ □□□□ □□□□    □ □□□□ □□□□    □ □□□□ □□□□ □□□□


Note the single column of space between each digit. Spaces at the end of each line are optional. (The three empty columns of spaces on the left side of the digit 1 are not optional.)

Each square number shall be printed on exactly 5 lines using these digits, and between each of these numbers shall be a single line containing no non-whitespace characters. You may optionally include extra blank lines at the beginning or end of the output.

Standard loopholes etc. Shortest solution in bytes is the coolest of beans.

Example Output (given the input 5):

□□□□
□  □
□  □
□  □
□□□□

□
□
□
□
□

□  □
□  □
□□□□
□
□

□□□□
□  □
□□□□
□
□□□□

□ □□□□
□ □
□ □□□□
□ □  □
□ □□□□


(Note for sandbox: I know this is a good challenge because I had fun solving it myself. But I am worried there is another challenge I haven't seen that is too similar. Please let me know. I'll abandon it if so.)

• Can't find any dupes on this search so it is probably clear. Jan 7 at 4:45
• Closely related Jan 7 at 7:58
• @pxeger yeah that's probably similar enough not to post this Jan 7 at 17:37

## Remove consistently dependent smaller integers

• If lists can be empty I would add an example where one is empty, if they cannot I would make that explicit in the text. Otherwise this seems fine +1.
– Wheat Wizard Mod
Jan 6 at 14:20
• @WheatWizard i will explicitly specify. Thank you:) Jan 6 at 14:23

# Expand a Rubik's Cube Commutator

• What do you mean by "expand" the commutator? Also, 3x3x3*, a 3x3 would be a rubik's square :) Jan 11 at 15:12
• @thejonymyster The common names for Rubik's cubes are by the size of a face since they're usually cubes, so we just call them "3x3" for a 3x3x3 cube, etc. Only in cuboids like the 3x3x4 cuboid actually have the 3rd dimension "Expanding" the commutator == Listing out all the moves performed in the commutator Jan 11 at 19:59
• ahh, that makes sense, for both parts. +1 Jan 11 at 20:03
• "Each part of the commutator can be a separate value" - I see this is to make IO more flexible than flat string to flat string, which is good, but I would go further and allow the moves themselves be separate values in each part, and allow a list of moves as the output in order to focus on the challenge itself. This would allow, for example, [["F'", "U2", "R"], ["D", "B2"]] -> ["F'", "U2", "R", "D", "B2", "R'", "U2", "F", "B2", "D'"]. Jan 11 at 23:07
• I couldn't resist and just gave it a go in Jelly and got a 15 byte solution (assuming IO is further relaxed as I suggested, which I believe you will do given your current relaxation). This is a good challenge IMO. Jan 11 at 23:20

# Is this hexagon symmetric?

TLDR: This is the hexagonal version of Is this square symmetrical?

Given a hexagonal grid, decide if it is symmetric.

The shape of the grid is a regular hexagon. Each cell in the grid has two possible states.

Let's only consider reflections and rotations. Here are all the possible symmetries:

• Reflection symmetry, where the axis is the perpendicular bisector of an edge (there are 3 possible such axes):

Smaller examples in ASCII art:

   . . . .         . . * .         * . * .
. * . * .       * . * * .       . . . . *
* . . . . *     * * . . . .     . * . . . .
* * . . . * *   * * * * . * .   * . . . . . *
. . * * . .     . * * . * *     . . . . * .
. . * . .       . * * . .       * . . . .
* . . *         * * * .         . * . *

• Reflection symmetry, where the axis is a diagonal (there are 3 possible such axes):

Smaller examples in ASCII art:

   * . * *         . . * *         * * . *
* * . * .       . * . * .       . * . . .
. . . . . .     * . . . . .     * . . . . *
* . . . . . .   * * . . . * .   * * . * . * *
. . . . . .     . . . . * *     . . . . . .
* * . * .       . * * . .       . . . * *
* . * *         . * . .         * . . *

• 60° rotational symmetry:

A smaller example in ASCII art:

   * * . *
. * . * *
* . . . . .
* * . * . * *
. . . . . *
* * . * .
* . * *

• 120° rotational symmetry:

A smaller example in ASCII art:

   * . . .
. . * . *
* . . . . .
. . . . . . *
. * . . * .
. . . . .
* . * .

• 180° rotational symmetry:

A smaller example in ASCII art:

   . . . .
* . * . .
. . * * . .
* . . . . . *
. . * * . .
. . * . *
. . . .


### Input

A hexagonal grid, in any reasonable format. You may choose the two distinct values for the two states in the input.

Some example inputs (Taken from Bubbler's HexaGoL challenge):

• ASCII art:
  . . .
* . . *
* . * * *
* * * .
* . .

• List of rows:
[[0, 0, 0],
[1, 0, 0, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 0],
[1, 0, 0]]

• 2d array, skewed to the right (with zero padding):
[[0, 0, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 0, 0],
[1, 0, 0, 0, 0]]

• 2d array, skewed to the left (with zero padding):
[[0, 0, 0, 0, 0],
[1, 0, 0, 1, 0],
[1, 0, 1, 1, 1],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0]]

• Flatten array, with an integer that indicates the size:
3, [0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0]


### Output

A value representing whether the hexagonal grid is symmetric. You can choose to

• output truthy/falsy using your language's convention (swapping is allowed), or
• use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

This is , so the shortest code in bytes wins.

### Testcases

Here I use 2d arrays skewed to the left.

Truthy:

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


Falsy:

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


## Questions:

• Is it clear?
• What other input formats should I allow?
• Should I add testcases in other input formats?
• Should I use other characters in the ASCII art?
• To be honest, I'd say this is too close and is a duplicate. It's a bit more interesting, but I think the answers could be fairly easily adapted. Dec 15 '21 at 3:30
• @pxeger I'm considering changing it to hexagonal symmetries. Dec 15 '21 at 7:01
• I think you could make some smaller-sized examples, which might make them easier to digest (and then it would be easier to use ASCII art) Dec 28 '21 at 22:48

# Will the tower balance?

You are given as input a tower made of bars of unit height, and your task is to decide if the tower is stable. Here is an ascii art drawing of a tower:

 #
####
# ####
#####


For extra clarity here is the same tower but with the different bars in different characters:

 A
BBBB
C DDDD
EEEEE


The bars are rigid, but they are not connected to each other. Even though the bars are not connected, they stay still under the influence of gravity. Here however is a tower that is not stable:

      B
CCCCCCCC
D
EEE
FFFFFFFF


In this tower, under the influence of gravity, the top bar will fall to the right.

The following tower is metastable:

AA
B


The center of mass of the A-bar lies on top of the edge of the B-bar. In this kind of situation the tower is considered unstable, since even a small perturbation will cause it to fall eventually.

# Input/output format

The input format is an ascii drawing of the tower like so:

 ###
#
### #


In this picture there are 4 bars. It is guranteed that all bars are on top of another bar or on top of the ground and that every row has at least one bar. You can use a different printable ascii character instead of #. You can also take a 2d array instead of a string and use two distinct values for # and  . In that case please use simple values, that don't encode extra information (standard loopholes prohibited).

Output two distinct values for STABLE and UNSTABLE.

# Test cases

#


STABLE

###
#
##
#


UNSTABLE

  ###
###
###


UNSTABLE (metastable)

#
#     ######
####    ##
#      ##


STABLE

###
#
#####
#


STABLE

 #
#####
#


UNSTABLE

######  #
#  #   #
### #####
#   #
#####
#


STABLE

• The rules do not actually specify what makes a tower stable. The stable test cases use balancing methods not stated anywhere, and the rules themselves just seem to be more examples. As a non physicist, "use gravity" isn't enough information IMO. This is a cool idea though and +1 once that's fixed 2 days ago
• Just highlighting the bars on their own would be interesting IMO 2 days ago

## Is this continuous terrain? Part II

Caves and Cliffs edition

Part 1

Very related

You're given a piece of ASCII art representing a piece of land, like so:

   /‾\         _ __
__/ _/         \‾
_/  __/‾\     |
/   /     ‾\   |
\_/‾        \_/


But unlike in the previous challenge, the terrain is mountainous, with caves and cliffs, and can turn back on itself. Also, a new character is introduced, |, which can connect to any of its four corners.

Since an overline (‾) is not ASCII, you can use a ~ or - instead.

Your challenge is still to determine if it is connected by the lines of the characters. For example, the above can be traced like so:

To clarify the connections:

• _ can only connect on the bottom on either side
• ‾ (or ~ or -) can only connect on the top on either side
• / can only connect on the top right and bottom left
• \ can only connect on the top left and bottom right
• | can connect on all four corners, but not to anything that connects to more than one corner. | must have a single connection above itself and a single connection below.

That one's a bit confusing, so the following are legal:

|
\

|
\

_
|_

‾|
/


And the following aren't:

|
‾
_
|

||


It doesn't matter where the connections start and end as long as they're all connected. Note that one line's bottom is the next line's top, so stuff like this is allowed:

_
‾

\
\

_
/

\
‾


You can assume input will only contain those characters plus spaces and newlines, and will contain at least one non-space character per column.

Input can be taken as ASCII art, an array of rows, a character matrix, etc.

## Testcases

Separated by double newline.

Truthy:

\
\

\_
\ /\/\_
‾     \

/\
\/

\_
‾\

/‾\
__/   ‾\_
\_/‾\
\

/‾\         _ __
__/ _/         \‾
_/  __/‾\     |
/   /     ‾\   |
\_/‾        \_/

/‾\
\ /
/ \

____   _
___| | |
|  ___| |
| |___  |
|___  | |
___| | |
|_____| |

_
/ \  _
| |_|

_
|_\



Falsy:

/
\

//

‾‾
/  \

‾
_

\____/
/‾‾‾\

\_
/

| |
‾‾‾

|_|
| |


• i like it emanresu A! 11 hours ago

# Shrink ASCII art

• convert like ---, 3 to [---, 3]? Dec 26 '21 at 0:48

# Metagolf: Catlike Piet

The goal of this is to write a catlike program, which would be executed (in a Unix environment, though you needn't stick to that) by the following:

yourprogram < file > output
piet output


where piet output writes the contents of file to stdout. That is, you're to generate a Piet program which prints the input to yourprogram.

One-liners

Straight line programs can be written in Piet... in straight lines. If you're willing to take a hit to your score, your output can take the form of a string of commands:

=  none (continue color block)
|  push
^  pop
-  subtract
*  multiply
/  divide
%  mod
~  not
>  greater
.  pointer
\  switch
:  duplicate
@  roll
$input number ? input character # output number ! output character  which is trivial to convert to a Piet program with the following (partially golfed) Python code: def P(s): h=v=0;l=len(s)+1;R="P3 %i 2 255 192 0 0 "%(l+2) C=[1,3,2,6,4,5];V=[0,192,192,255,0,255] for x in map("=|^+-*/%~>.,:@$?#!".find,s):
C=C[x//3:]+C[:x//3];V=V[x%3*2:]+V[:x%3*2]
for i in [1,2,4]:R+="%i "%V[(C[0]//i)%2]
return R+"255 "*4+"0 0 "+"255 "*l*3+"255 0 0 "*2


The dimension of said program is (n+3) x 2 if there are n characters in the string.

Scoring

Your code will be judged on the maximum dimension of the images that it outputs.

• Part 1: Take the maximum score taken over all ascii codes (that is, single-character inputs), discounting EOF.

• Part 2: Take the score for the input "Hello. My name is Inigo Montoya. You killed my father. Prepare to die."

Your score is the product of the scores in part 1 and part 2.

Punishment: Double your score if you write one-liners as above (that is, if you don't output an image).

Bonus: If your program is written in Piet, take the square root of your score above.

• It took me a while to understand the task as "Write a program taking INPUT which produces as output a piet program that takes no input but produces INPUT." I think it is a interesting and challenging, but it's reception will depend entirely on how many people are willing to learn/futz-around-in/deal-with piet. And I have no feel for how many that is. Jul 7 '11 at 3:12
• @dmckee; would it be better if I just used a reduced instruction set, and only ask for the instruction stream? I think this is still challenging with {push 1,duplicate,add,subtract,multiply,output}. Come to think of it, if I restrict to {push 1,duplicate,add,output}, there's a reduction to some awesome algorithms. Jul 7 '11 at 4:48
• I did this in piet some time ago: craigoclock.blogspot.com/2011/05/metaprogramming-in-piet.html May 21 '12 at 18:31
• 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.)
– user58826
Jun 9 '17 at 15:22

## Play Simple 2-Dimensional Minecraft

Recently I found this video of "HansLemurson" showing a computer that was built in minecraft, which runs minecraft. He is playing minecraft on a computer that was built in minecraft that is running on his computer. To be specific, it is a two dimensional version with an 8x8 grid of cells. There is gravity, block placement, and even jumping. It is worth noting that the computer is single purpose. The same person has built programmable computers, but making them single purpose allows the computer to be much smaller.

## Details

The minecraft world is an 8x8 grid (one horizontal and one vertical dimension). The grid is comprised of either Xs (representing blocks) or empty spaces. The player is an X that is blinking on and off about once every second.

There are two modes in the game, controlled by a toggle switch. The first mode is movement. This is controlled by a WASD-like button arrangement. If the player chooses to move left/right/down, the computer checks to see if the space immediately in that direction is empty. If so, then the player moves into that space.

If the player chooses to move up, then the computer checks that the block underneath the player is solid. If so, then the player moves upward two units. Notice that this can propel the player into a solid block. If this happens, the player is obscured by the solid block, but can still move to an empty block next to him. When the player is inside on a solid block, the game continues as if the block isn't there, although the block is still there once the player leaves it.

After each move, the player falls down one unit if there is empty space there. This simulates gravity. This is also why moving up moves up two units, so that the gravity makes a net movement of up one unit. Gravity does not cause the player to fall all of the way to the ground, just one unit.

The second mode is block placement. In this mode, the same exact WASD buttons are used. Instead of moving the player, they toggle the state of the block in that direction. If the player presses "left" and there is a block there, then the block is destroyed. If there is not a block there, then a block is placed. Again after this move, the player is again subject to gravity. The blocks are not subject to falling.

Toggling the toggle switch does not count as a move, and does not invoke gravity.

The game board is a torus, so all actions (movement, block creation) can wrap around the board. The board does not scroll with the player. The player moves, and the blocks stay in the same place.

## The challenge

You challenge is to write the shortest program that simulates this game. Your program should display and update the map correctly (with Xs as blocks, and with the blinking player). It should accept input from a button that toggles the state and four buttons for movement and actions. This is code golf.

There are imaginary bonus points for adding more features (block types, game size, etc) to your game.

## Suggestions?

• With more complicated challenges I find that it helps to do a reference implementation so that you have a very concrete idea of how much work is involved. Aside from that, I like it. Jun 3 '12 at 20:11
• Is the blink rate selected to fit with the ANSI escape sequence? Either way I would explicitly allow that, because it's the obvious way to do it on compatible terminals. Jun 5 '12 at 7:14
• The blink rate wasn't selected to be anything specific. I think that I will broaden the restriction. Maybe any blink rate between 3 blinks per second to 1 blink every 2 seconds. Jun 5 '12 at 20:21
• @programmer5000 No, for two main reasons: First, challenges can go extended periods of time in the sandbox before they are posted and/or adopted. In the past I've posted challenges after not touching them for 4 years. Second, deleting this answer will not reduce lag, as deleted answers are still present, simply not visible. Users with sufficient rep will see all 4040 answers in the sandbox, and you will too once you earn the "view deleted answers" privilege. Apr 13 '17 at 18:15

Overview:

Let's say you've decided to operate your computer using voice recognition software, but unfortunately you did a horrible job researching the various products out there and chose a package that does not recognize numbers as numerals, only words. (i.e. "one" (spoken) == "one" (typed), not "1".) Rather than spend more money to get another option, you decide to make do. Now you want to use the computer's calculator, but this poses a problem, since your machine doesn't know how to add "one plus one".

Objective:

Implement a basic calculator that will read in a string of the written-out equation, perform the correct calculations, then return the result in its text form. Your code should be as short as possible; this is code golf.

Rules/Constraints:

• Input/output will be using your preferred method (STDIN, ARGV, etc.).
• Your calculator must be able to handle input and output within the billions (non-inclusive) -1,000,000,000 < i < 1,000,000,000, but you may expand to more if you wish.
• Decimal values and/or parts must be accepted (0 < i < 1) up to 3 places/digits.
• When calculating answers, proper rounding must be used, so "three point one four one five nine two six" must be returned as "three point one four two".
• Basic calculator functions required:
• "Add"/"Plus"/"Sum"/"And" (+)
• "Subtract"/"Minus"/"Remove" (-)
• "Multiply"/"Times" (*)
• "Divide"/"Divided"/"Divide by"/"Divided by" (/)
• "Raise"/"Exponent"/"Power"/"To the power of" (^)
• "<Base>Root"/"<Base>Radical" (√)
• "Point"/"Decimal" (.)
• "Pi" (π)
• All strings in the list above must be accounted for in your code, capitalization does not matter.
• Numbers may be presented as their full value ("one thousand") or by digit (one zero zero zero).
• Negative numbers may be assigned using "Minus" or "Negative".
• The string "Minus" bust be accounted for as an operator and identifier. (see example)
• "And" is only acceptable as an operator, not as part of a named number.
• "one hundred and one"
• "one hundred one"
• "a" or the absence of a number does not equate to any number; all numbers will be explicitly accounted for in the program input.
• "a hundred" does not equate to "one hundred" and is not a valid input.
• No more than 2 terms will be used.
• "one plus one minus one" will not be implemented.
• If an invalid input is supplied, your function/program should handle the error and exit gracefully with an error description.

Example I/O:

• "one add one" --> "two"
• "five thousand thirty four subtract ten thousand six hundred" --> "negative five thousand five hundred sixty six"
• Alternatively: "five zero three four subtract one zero six zero zero"
• "three root twenty seven" --> "three"
• "ten minus minus ten" --> "twenty"
• Alternatively: "ten subtract negative ten"

## Sandbox Questions:

1. Is this too basic/complicated? (I'm assuming some languages will handle this much more simply than the method I have in my head...)
2. Does the title fit?
3. Are there any constraints that should be added/lifted?
4. Are any more examples needed for clarification?

• Not everyone says numbers the same way. Does the parser have to treat the following as equivalent? "negative one hundred five", "minus one hundred five", "negative one hundred and five", "minus one hundred and five", "negative a hundred five", "negative a hundred and five", ...? Jun 15 '12 at 15:12
• @PeterTaylor I had had a similar thought re: operators. ("plus" versus "add", etc.) I think it would be more interesting to account for all, but given the wide variety of possible inputs, it may generally be better to limit the options to a specifically defined set (which I have yet to define). Jun 15 '12 at 15:18
• @PeterTaylor I've added some of these details. Please let me know if there's anything unclear about them. Jun 15 '12 at 16:10
• I don't spot any ambiguities in the parser. There is still an ambiguity relating to decimals, though. What precision should be used? Also, I notice now that there's no winning condition. Is this intended to be code-golf? (Ugh - tons of strings which will have to be hard-coded in most languages. I expect Perl has a suitable parser already in CPAN, though...) Jun 19 '12 at 9:03
• @PeterTaylor I don't know where I went... I've updated the spec. re: decimal places and objective. Jun 29 '12 at 13:24
• @PeterTaylor metacpan.org/pod/Lingua::EN::Words2Nums Apr 27 '16 at 20:37

# 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

• 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. Oct 8 '12 at 16:23
• 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.)
– user58826
Jun 9 '17 at 15:30

## 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'.

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.

• 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. Jun 8 '13 at 14:33
• Yes, this is the case. In general however there is not a unique series of applications of the reduction rules for any given instance.
– Kaya
Jun 8 '13 at 16:21
• 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. Jun 10 '13 at 8:49
• 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? Jun 11 '13 at 8:32
• 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.
– Kaya
Jun 11 '13 at 14:04

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.

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

• 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>"? Oct 6 '13 at 17:22
• 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). Oct 6 '13 at 17:29
• 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. Oct 6 '13 at 17:33
• 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. Oct 6 '13 at 22:48
• Yes. Read the teapot question for guidance. Ultimately I decided that one was too big, but we did get into some pertinent details. Dec 1 '13 at 9:48
• 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.
– user58826
Jun 9 '17 at 15:32

# Count unique characters in text.

Given a string for input, output the unique non-whitespace characters in that string along with a count of their occurrences. The list should be sorted in ascending order of ASCII code.

Examples

Input:

Hello, World!


Output:

Character    Count
!            1
,            1
H            1
W            1
d            1
e            1
l            3
o            2
r            1


Input:

The quick brown fox jumps over the lazy dog.


Output:

Character    Count
.            1
T            1
a            1
b            1
c            1
d            1
e            3
f            1
g            1
h            2
i            1
j            1
k            1
l            1
m            1
n            1
o            4
p            1
q            1
r            1
s            1
t            1
u            1
v            1
w            1
x            1
y            1
z            1


The actual formatting (headers, spacing, etc) of the on-screen output is up to you. The only conditions are that it must be sorted in ascending order by ASCII code, and it must be easy to tell what represents a character from the string and what represents a count of a given character. (For example, given a string of 99999999, the output should be explicit so that it is not confused as saying I have 9 8s.)

Ultimate challenge (taken from here):

JKqdJg+oJgiowgyIJgkS+gyxJdeS+gyxJ4yoJdybJdioJdqIJ4kS+KwFJ4QS+gzYJg+ow4vIJ4yxvd+IJgy=+dv=JdQx+gzbJrzx24zYJgkxJ4qLJKQxJ4yxJKqx+KqdJKqdJg+oJgiowgyIJgkS+gyxJdeo24yxJm+xJdybJdioJdqIJKi=J4wF+dvS+gzYJg+ow4zYJ4yxvdy=J4i=+Kv=JdQo+KqxJrzdJKzYJgkxJ4qLJgkxJ4yxJKvSJ4qbJKqdJg+oJgiowgyIJgkdJgyxJdeo24yxJm+xJdybJd+oJd+S+dz=J4wF+dvS+g+SJg+ow4vIJ4yxJ4voJgy=+dv=+dzdJgqxJrzdJKzYJgkS+dweJKQxJ4yxJKvSJ4qbJKq=24yYJgiowgyIJgkdJgzdJryo24yxJm+d24zxJd+oJdqIJ4kS+KwFJ4QS+gzYJ4y=2gzYJ4yxJ4voJgy=+dv=+dzdJgqxJrzx24zYJgkS+dweJKQxJ4fK+dQSJ4qbJKq=24yYJgiowgyIJgkS+gzdJryS+gyxJ4yoJdybJd+oJd+S+dz=J4wF+dvS+gzYJ4y=2gvIJ4yxJ4voJgy=+dv=JdQo+KqxJrzx24zY+dzS+dweJKQxJ4yxJKqx+KqbJKq=24vbJdyowgyIJgkdJgzdJryS+gyxJm+d24zxJdioJd+S+dz=J4wF+dvS+gzYJg+ow4vIJ4yxJ4voJgy=+Kv=JdQx+gzbJrzx24zYJgkS+dweJgkxJ4yxJKvSJ4qdJKq=24yYJgiowgyIJgkdJgzdJryS+gyxJ4yoJdybJd+oJdqIJKi=J4wF+dvS+gzYJg+ow4vIJ4yxJ4v=J4i=+Kv=+dzdJgqxJrzx24zYJgkS+dweJgkxJ4fKJ4qx+KqdJKqdJg+SJdyowg+oJgkS+gyxJdeS+gyxJ4yoJdybJd+oJdqIJ4kS+KwFJ4QS+g+SJ4y=2gzYJ4yxJ4v=J4i=+Kv=JdQo+KqxJrzx24zY+dzS+dweJKQxJ4yxJKvSJ4qbJKqdJg+oJgiowg+oJgkS+gzdJryo24yxJ4yoJdybJdioJdqIJ4kS+KwFJ4QS+g+SJg+ow4vIJ4yxvd+IJgy=+dv=JdQo+KqxJrzdJKzY+dzxJ4qLJKQxJ4yxJKqx+KqdJKq=24vbJdyowg+oJgkS+gzdJryo24yxJ4yoJdybJdioJd+S+dz=J4wFJ4QS+gzYJg+ow4zYJ4yxvd+IJgy=+Kv=+dzdJgqxJrzdJKzYJgkxJ4qLJgkxJ4yxJKvSJ4qbJKq=24vbJdyowgyIJgkdJgyxJdeo24yxJm+xJdybJd+oJdqIJKi=J4wF+dvS+g+SJ4y=2gvIJ4yxvd+IJgy=+dv=+dzdJKzbJrzdJKzY+dzS+dweJgkxJ4yxJKvSJ4qbJKq=24yYJgiowg+oJgkS+gyxJdeo24yxJ4yoJKzxJd+oJdqIJKi=J4wF+dvS+gzYJg+ow4vIJ4yxJ4v=J4i=+dv=+dzdJgqxJrzx24zYJgkxJ4qLJKQxJ4fKJ4qx+KqdJKqdJg+oJgiowgyIJgkS+gzdJryS+gyxJm+d24zxJd+oJdqIJKi=J4wFJ4QS+gzYJ4y=2gzYJ4yxvdy=J4i=+Kv=+dzdJKzbJrzx24zY+dzxJ4qLJKQxJ4yxJKqx+KqdJKqdJg+SJdyowg+oJgkdJgzdJryo24yxJm+d24zxJd+5


• This isn't really an interesting problem. The shortest answer is almost certainly going to be fewer than 10 characters. Dec 11 '13 at 12:19
• @PeterTaylor While I mostly agree with your comment - already the header line may contain more than 10 characters. Dec 12 '13 at 6:15
• "The quick brown fox jumps over the lazy dog." contains "e" three times. Dec 12 '13 at 6:16
• @Howard Thanks. I must be blind - it took me about five times of reading your comment to find it. Also, do remember that the header is optional to a certain degree - you just need to make sure the output is unambiguous as to which items are characters from the string, and which are character counts.
– Iszi
Dec 12 '13 at 7:02
• My brain instantly went into bash mode. wc and uniq practically solve half of this, but not in any particularly short manner.
– Rob
Dec 17 '13 at 20:31

## 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.

• 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%

• 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!

• "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. Feb 28 '14 at 5:54
• 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? Feb 28 '14 at 12:02
• @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. Feb 28 '14 at 12:11
• @JanDvorak, (part of) the point of that example is that there are two AUG substrings. Feb 28 '14 at 12:30
• 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. Feb 28 '14 at 13:58
• Also, I've muddied the waters with RNA encoding and DNA encoding, (U vs T), which we can chalk up to a late night. Feb 28 '14 at 14:00
• 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. Feb 28 '14 at 17:20
• " 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? Mar 1 '14 at 9:25
• 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). Mar 1 '14 at 9:29
• 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) Mar 1 '14 at 9:34
• 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. Mar 1 '14 at 9:38
• 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. Mar 1 '14 at 9:45
• 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). Mar 1 '14 at 14:29
• 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. Mar 1 '14 at 14:33
• Perhaps a code-challenge where people earn x points for each complexity implemented?
– user10766
Mar 2 '14 at 5:52

## 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

• 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. Mar 6 '14 at 23:28
• 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". Mar 6 '14 at 23:57
• 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. Mar 7 '14 at 0:04
• 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.)
– user58826
Jun 9 '17 at 16:09

# 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;
}

• Can the program assume that the @@ lines contain the correct line numbers? Mar 6 '14 at 17:52
• A good explanation of the patch file format is needed. If not too long, include it in the question. Else, provide a link. Mar 6 '14 at 17:53
• You forgot the obvious "no external tools" disclaimer. You don't want the patch \$1 answer. Mar 6 '14 at 17:55
• @ugoren thanks for the comments, I added some further clarifications. Mar 6 '14 at 18:38
• Does "The patch file will be valid (it will not lie about line numbers)" also mean that it will apply cleanly? Mar 6 '14 at 19:24
• @PeterTaylor yes, updated question. Mar 6 '14 at 19:51
• "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. Mar 7 '14 at 0:01
• 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.
– user58826
Jun 9 '17 at 16:10

# 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:

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:

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}

• 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). Feb 20 '14 at 8:30
• 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. Feb 20 '14 at 11:51
• 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. Feb 20 '14 at 11:57
• 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. Feb 20 '14 at 12:43
• @ugoren, 0 is easily obtained. Feb 20 '14 at 12:57
• @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. Feb 20 '14 at 15:12
• @PeterTaylor: I agree it is quite long, and will consider revisions to it. Feb 20 '14 at 21:43
• @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? Feb 20 '14 at 21:48
• @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. Feb 20 '14 at 21:49
• @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. Feb 20 '14 at 21:51
• 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. Feb 20 '14 at 21:59
• 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. Mar 12 '14 at 8:47
• 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. Mar 12 '14 at 9:03
• 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. Mar 12 '14 at 20:17
• 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. Mar 12 '14 at 21:23

## Amino Acids Matcher

In genetics, a codon is a set of three nucleotides, the most basic form of nucleic acids. A codon "codes" (no pun intended, that's the actual term used) for a specific amino acid. Given a string of DNA, it is converted into RNA form by taking the opposite complementary pair.

DNA    RNA
A      U (T changes to U)
T      A
C      G
G      C


You will be given a String of unknown length that contains multiple codons. You must convert them to RNA form and print out the amino acid for each. See here for a chart: http://en.wikipedia.org/wiki/RNA_codon_table#RNA_codon_table

## Sample Input

TACTCGGATACT

Is split into

TAC, TCG, GAT, ACT

We now change each letter to its reciprocal

AUG, AGC, CUA, UGA

And print out the amino acids

Methionine, Serine, Leucine, Stop

This would probably be

I know that this is most likely not sufficiently explained and might be too complicated. Additional, tell me if there is any incorrect information above.

• So basically this is a challenge to compress a lookup table. You should probably specify that the string will be a multiple of three characters (or specify what to do otherwise); and it would seem sensible to inline the lookup table so that a) the question doesn't rely on the external page remaining intact; b) you save everyone who wants to answer the question the hassle of calculating it. Mar 17 '14 at 12:42
• Thanks for the feedback. I'll update accordingly later today. Mar 17 '14 at 15:48