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

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

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

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

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

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

-mesh spiral instead of concentric circles: 40 pts

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

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

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

-irregular outer outline: 20 pts

-2 or more easily observable reverses in spiral: 40

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

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

## Write a PHP Code Golfer code-challenge

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

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

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

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

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

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

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

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

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

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

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

# Create diagonal code

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

Specs:

• Your program must be at least 4 lines long;

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

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

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

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

• Internet access is forbidden;

• Most upvoted answer in 2 weeks wins.

Happy coding!

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

### Some bonuses for the code-challenge version:

+15 for any other hidden answer;
+5 for every hidden answer that runs and ends successfully, without any problem;
+15 for every hidden answer that is a polyglot;

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

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

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

# Create a Karnaugh-map calculator

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

Input:

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

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

Max 4 variables will be inputted

K-maps (a small explanation):

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

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

   cd
ab\   00 01 11 10
00
01
11
10


Note the grey-code counting scheme.

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

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


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

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

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

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

Output:

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

~ instead of ¬


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

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

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

Content:

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

### Scoring:

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

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

Example scoring:

### C: 21/32 = 65.625%

main(){printf("Hello World!");}

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

# Convert input to ASCII Semaphore

With monitor resolutions getting higher and font sizes getting lower, a good programmer has to make efforts to ensure that output is accessible to the visually impaired. This can be problematic when the only display is in text. Toward this end, your assignment (if you choose to accept it) is to write a program that converts text input into ASCII art flag semaphore.

## Input

1. Your program must accept any letter in the ASCII character set from A to Z (case insensitive) and spaces.
2. The program can accept input in any way that is convenient for the language it is written in (stdin, command line, file, etc.).

## Output

1. The program should output an ASCII art representation of the input string in flag semaphore. Follow this link to see the expected encoding.
2. Line feeds and carriage returns should be interpreted as spaces.
3. Numbers and other non-letters in the input may be ignored.
4. You may use whatever ASCII art representation of the semaphore sender you like, but it must contain a person holding two flags and have distinct arms, legs, head, and flags. It must be at least 10x10 characters.
5. Output may be either horizontal or vertical.

## Example

Input: Hello

Output:

           ###
###
#
_____########
|  |       ###
|__|      ####
# ###
#  ###
/   # #
/\   # #
/  \  # #
\  /  # #
\/  ## ##
/\
/  \
/\  /
#  \/
###  #
### #
# #
####
# ###
# ###
# ###
# ###
| # #
|__ #
|  |#
|__|#
## ##
/\
/  \
/\  /
#  \/
###  #
### #
# #
###
####
# ###
#  ###
#   ###
/    # #
/\    # #
/  \   # #
\  /   # #
\/   ## ##
/\
/  \
/\  /
#  \/
###  #
### #
# #
###
####
# ###
#  ###
#   ###
/    # #
/\    # #
/  \   # #
\  /   # #
\/   ## ##
/\
/  \
\  /\
\/  #
#  ###
# ###
# #
_____########
|  |       ###
|__|       ###
###
###
# #
# #
# #
# #
## ##


## Scoring

This is code golf. Shortest code wins.

• define "easily recognisable". Would a simple 3x3 compass (say, with a head if not covered) do? say:.o. -|. /|. ; or even: ... xx. x.. (read by lines, dots represent spaces) – John Dvorak Mar 6 '14 at 20:16
• @JanDvorak Good catch. Edited to include distinct items that must be present and a minimum size. I'm not exactly sure how to make that rule more clear. – Comintern Mar 6 '14 at 20:34
• Define "person holding two flags". Is what I drew a person? Is this a (lying, due to formatting issues) person: o--? Are three x's on a vertical line a person? – John Dvorak Mar 6 '14 at 20:43
• @JanDvorak Ack! had to many tabs open and forgot to save my edit. I think number 4 for output should cover that. – Comintern Mar 6 '14 at 20:47
• Define "distinct arms, legs, head, and flags." But I suggest allowing very small figures as well, otherwise this will turn into a kolmogorov-complexity-like question with very little of the code actually involving generating a pair of directions. – John Dvorak Mar 6 '14 at 20:51
• Very similar to this question. The ascii art is more complex here so perhaps it's not close enough to be called a duplicate... – Gareth Mar 6 '14 at 22:20
• I disagree with @JanDvorak: I think this would be better with a fixed output spec which must be followed exactly. That way people can golf their code rather than the output. – Peter Taylor Mar 6 '14 at 23:59
• Standard figures seem best to me as well. If you demonstrate a full "clock" of hand positions for the standard figure, then you can require those as output. That's easier to assess than free reign for variations. – Jonathan Van Matre Mar 7 '14 at 0:14

With its strange choice of 9 different characters (plus space and newline), the ASCII art version of the FreeBSD logo has always looked to me as if it might be nicely formatted, obfuscated code is some programming language. (Is it?)

 
s .....---.......--.   -/
+o   .--         /y:      +.
yo:.            :o      +-
y/               -/   -o/
.-                  ::/sy+:.
/                     --  /
:                          :
:                          :
/                          /
.-                        -.
--                      -.
:                  :
.--             --.
.---.....----.


Therefore I would like to challenge you to make it one: Either specify minimal changes to an existing programming language or minimal changes to this piece of ASCII art (making the artwork look different or significantly changing the character set used are definitely major changes), so that the logo, as source code generates meaningful output.

This should be a challenge, although I wouldn't mind some way of introducing hard scoring and run this as .

## King of the Hill Fighting

In this game, a player controls 5 bots that attack the other players 5 bots. Each bot has life points, and has to reduce the other playres lifepoints to zero. This post is program that tests the controllers. It is in literate haskell.

> import Data.Set as S
> import Data.Map as M


Here is the arena:

    D---G
/|   |\
B |   | J
/|\|   |/|\
A | E---H | L
\|/|   |\|/
C |   | K
\|   |/
F---I
20  12    4
16    8   0


Positions are denoted by letters

> data Positions = A | B | C | D | E | F | G | H | I | J | K | L deriving (Show, Read, Eq, Ord)


Each player is presented a map in which their side is the one with A. Here is code that will reflect it so each player sees their own view.

> pairFlip = (\(x, y)->[(x,y), (y,x)])
> reflect = M.fromList $[(A,L), (B,J), (D,G), (C, K), (E, H), (F, I)] >>= pairFlip  Lines denote connections. > connections=S.fromList$
>   [(A,B), (A,C), (B,D), (C, F), (E, D), (E, F), (D, G), (E, H), (F, I)]
>   >>= pairFlip
>   >>= (\(x,y)->[(x,y), (reflect ! x, reflect ! y)])
>
> connected x y=(x, y) S.member connections


The numbers below are the number of life points of generation that each bot.

> regen = M.fromList $> [ (A, 20), (B, 16), (C, 16), (D, 12), (E, 12), (F, 12) > , (G, 8), (H, 8), (I, 8), (J, 4), (K, 4), (L, 0)]  • Is there supposed to be a specification hidden in here somewhere? – Peter Taylor Mar 14 '14 at 16:30 • @Peter Taylor Just not done yet. – PyRulez Mar 14 '14 at 16:44 • You won't get lots of answers if it's limited to Haskell. – ugoren Mar 14 '14 at 17:57 • No no no, the above post is also a program for testing it. I will add in code that can take arbitrary programs and use them. – PyRulez Mar 14 '14 at 21:17 # Create the perfect CSS reset stylesheet Your job is to create a CSS reset stylesheet, That is, a stylesheet that you can apply to any HTML file, and the result will look the same in all webbrowsers. Because we all know that cross-browser interoperability is very important these days, and you want to make your website look pixel perfect everywhere. The rules: 1. You must be able to throw any valid HTML5 document at it and the result will look the same in the main browsers. For simplicity, you can assume that the HTML document does not contain any styles of its own or Javascript that changes anything. Just pure, static HTML that is valid HTML5. 2. The main browsers are Firefox >= 22, Chrome >= 28 and IE >= 10. 3. To avoid solutions like *{display:none} (which do indeed make all documents look the same in all browsers, yes) the result must be identical to the document without the stylesheet in one of the browsers. In other words, take your browser of choice and make the document look like that in the other browsers. The winner is the stylesheet that works the best, again, on any HTML file that is valid HTML5 and uses no other styles. I'm not looking at efficiency. If you come up with a 100K stylesheet or one that slows the site down considerably, that doesn't matter, as long as the end result looks good. That's the question so far. Now I have a bit of a problem with "any HTML5 document"; I know I could provide a test document that people can work with, but then you'll get answers that cater to only that particular test case, and that's not what I want. Not sure how to handle this. Ideas? Also, I want to include Safari as a main browsers, but as I don't have a Mac, I can't test the results on it. Not sure how to handle that. • – Peter Taylor Mar 14 '14 at 12:59 • @PeterTaylor That breaks rule #3. – Mr Lister Mar 14 '14 at 13:05 • The result must be identical to the document without the stylesheet in one of the browsers. I assume you have loaded a webpage without a stylesheet before? If you mean that it can have the main stylesheets, and we just need to create a modification stylesheet, you should specify that. – user10766 Mar 14 '14 at 16:17 • @hosch250 What I mean is that I want the document to retain its basic HTML-ness, so it shouldn't look like plain text. Take this fiddle for example; open it in all browsers, and then add CSS to it so that it looks like (your favourite browser) in all other browsers. If the name of such is "modification stylesheet" rather than "reset stylesheet", I apologise. – Mr Lister Mar 14 '14 at 19:32 • OK, I was thinking about how most HTML pages rely on CSS stylesheets to even be legible. If you took the CSS sheet off any webpage, it would not look the same; in fact, if the HTML wasn't laid out good using accessibility techniques, it wouldn't be legible. – user10766 Mar 14 '14 at 20:01 • Pixel perfect isn't going to happen because of issues around anti-aliasing: CSS doesn't let you do things like enable ClearType on Safari/OS X or disable it on IE/Win. So the best anyone can do is somehow obtain the default stylesheets for the listed browsers (e.g. iecss.com but updated) and then find a minimal diff. – Peter Taylor Mar 14 '14 at 20:09 • Guys, I'm not interested in solutions to the question right now. I want to know if the question is OK! Specifically if I can get away with not posting a testcase like the fiddle above. – Mr Lister Mar 14 '14 at 20:38 # music theory challenge Create a program that takes some input in the form of frequency, waveform, and duration that generates an audio stream based on the input. You can take input parameters however you choose, but if I input (translated to your method) 440Hz, sin(x), 3 seconds, your program should play or create a file for a sound 3 seconds long at 440 hertz on a sine wave. Also, any output should be musically correct as far as frequency is concerned. See http://www.phy.mtu.edu/~suits/notefreqs.html for example frequencies Since this is a popularity contest, the rest is up to you. I bid you Good programming! Oh, and any use of external functions or APIs is ok, as long as they weren't developed specifically for this contest. • If the program takes "input in the form of frequency, waveform and duration" then where do linear functions fit? What do you mean "output should be musically correct as far as frequency is concerned" given that the input is frequency? Is it supposed to correct the input: "You said 494Hz but you must mean 493.88Hz"? And simple synth has been done before in various guises: see music. To differentiate this and make it non-trivial you could perhaps specify a set of basic synth operations which need to be configurable (e.g. input specifies generators, envelopes, filters, mixers). – Peter Taylor Mar 14 '14 at 8:39 • On second thoughts, that would probably work better as a Code Review Code Challenge – Peter Taylor Mar 14 '14 at 9:23 • @PeterTaylor I didn't even know about Code Review Code Challenges <intrigued>. Linear isn't the right word...and I think that statement is redundant anyway, so I'll nix it. – David Wilkins Mar 14 '14 at 12:44 • Actually, I'm going to re-write this challenge...I don't know yet whether it'll be here of on CR – David Wilkins Mar 14 '14 at 13:07 ## Calculate pi using a unique method Your task is to calculate or approximate pi using the most interesting method you know. Well-known things such as using inverse trig functions (asin, acos, atan) or commonly used convergent series are considered uninteresting. You may calculate pi to any precision desired, but the more precision you can achieve, the better. • I couldn't find an exact duplicate of this, but I'd like to know if this overlaps too strongly with an existing question. – Kendall Frey Mar 14 '14 at 18:51 • If you rule out convergent series, what's left? – Peter Taylor Mar 14 '14 at 20:02 • @PeterTaylor If someone knows of a convergent series that isn't on Wikipedia, that would make a good answer. I know of an answer that does not use trigonometry or an approximation, but calculates the digits directly. – Kendall Frey Mar 14 '14 at 20:08 • Is it in mathworld.wolfram.com/PiFormulas.html ? I've got some ancient code which uses a spigot hypergeometric evaluator to compute pi as 3*F(1/2, 1, 1, 8/5 ; 3/5, 4/3, 5/3 | 2/27), but I would expect that to count as well-known. – Peter Taylor Mar 14 '14 at 20:11 • @PeterTaylor I'm familiar with it in layman's terms only, but I don't see it there. It could be related to some of them, but I don't see more than a small resemblance. It isn't original with me, BTW. – Kendall Frey Mar 14 '14 at 20:22 # I like trees ...so this is a challenge to make me a tree. Produce a program called tree which takes a single integer argument, N and draws a randomly-generated tree N levels deep, where level 0 is just the trunk. • Your program must produce visibly different results for at least N=0..5 • The tree ought to not be symmetrical in any axis. • The tree should be an image • Tree(5) should mostly fill dimensions of at least 200w*250h • I should be able to run your tree from a bash prompt, eg. '$ python tree.py 3'

I also accept ferns.

Optionally your tree may be 3d, iterate forever, be colourful, have leaves at level 5, or be lit according to the time of day. However, this is code-golf, so the smallest file wins.

Tags: code-golf

# Implement multi-line lambdas in Python.

Guido van Rossum said it couldn't be done, prove him wrong. Your solution should allow multi-line anonymous functions, like:

>>> f = multilinelamba("hour", """
...     if hour > 20 or hour < 6:
...         print "Good night"
...     else:
...         print "Hello world"
...     """)
>>> f(10)
... 'Hello world'


Your solution should be as close as possible to the behavior of real def or lambda. The actual syntax doesn't matter. E.g. you may choose to pass the code as a string as above, or you may find a way to avoid it. The implementation is also open, you may for example define a function, write a preprocessor, or edit the python source, but keep in mind that the solution should fit in the answer, so the last option probably won't work.

Your solution must allow arbitrary python code inside, except the following which is optional:

• recursive use of the multilinelambda "statement" inside of the multilinelambda
• calling the function recursively, i.e. using f inside the multilinelambda in the above function
• defining classes and
• importing modules (these two might be too hard)

You must also be able to use a multilinelambda as a parameter when calling a function.

You get bonus points:

• If your solution captures outside variables in a closure, like real def does
• For correct handling of exceptions in the multilinelambda. They should display similarly to when using def, and include line number relative to the file.
• For allowing default parameters
• For allowing *args and **kwargs
• If the solution admits any kind of consistent indentation. Two options must be considered:

• All lines have a common indentation (like in the example above) that can be stipped away.
• The first line of the body is given on the same line as the multilinelambda statement. In this case, all the remaining lines must be checked for consistency. It makes a difference whether the first line starts a block or not. Example:

multilinelambda("x", """print "Hello"
print "World" """)

multilinelambda("x, y", """if x > y:
print "case 1"
else:
print "case 2"
""")


In both cases, I may add or remove the same number of spaces to/from each of the lines following multilinelambda.

Any ideas for additional criteria? I personally don't really care much about picking a winner, this is more about tinkering and proving that it can be done. But in any way, more "unit tests" will only benefit the question.

Foreword: This might have been done before, but I couldn't find any such cases. I think the scoring is quite fair now, and the challenge quite clear, but any criticism is welcome. Only thing I am not sure of (besides maybe a similar question existing) is whether it is rewarding enough to add a single language or whether a 2 byte solution which just runs in two languages is going to win (is that possible?).

# The challenge

Write a single piece of code that will only output different deterministic integers depending on the language it has been interpreted as.

# Scoring

Length of the code divided by the multiplication of the score of every used language. Esoteric languages have score 2 and production languages have score 3. For example, if you have a code of length 120 which runs in whitespace and javascript this will give a score of 120/(2*3)=20.

# Rules

• Versions and forks: Different versions and forks may count as different languages, provided that the output is not determined by the version or similar constants in any way. In other words: <?=intval(phpversion())?> or 1<!--[if IE 8]>1<![endif]--> is not allowed.
• The outputted integer should be the constant and only dependent on the language it is run in.
• Only the most common compiler for a language should be used.
• The code should output nothing besides the integer.
• No two interpretations (languages) of the code may yield the same integer.
• In cases where there is any serious discussions of a language being esoteric, it will be counted as esoteric if no commercial company with at least 50 employees can be pointed to developing it's main product in the discussed language.

^ Blame the sandbox for that last crazy over specific rule

• Define "esoteric." Also, the last time is fairly opinion-based. And what about different versions of the same language? Or similar languages (i.e. C and C++)? – Doorknob Mar 22 '14 at 21:40
• Yes, a two-byte solution which runs in two languages is arguably possible. The arguments will come around things like what precisely you mean by "output ... [an] integer". Is additional non-numeric output (punctuation, ans - , or the like) permitted? If so, can the integer be part of an error message from the interpreter? Also expect arguments about whether languages are esoteric or production: it's clear-cut for C and Piet, but there are plenty of languages in much greyer territory. – Peter Taylor Mar 22 '14 at 23:30
• @Doorknob: Added a link and a rule regarding esoteric. Addressed the issue regarding forks and versions. – David Mulder Mar 23 '14 at 0:27
• @PeterTaylor: Great point regarding additional output! Would you have an example of a language you would consider to be gray? I added an additional note regarding the esoterism, but would like to have a 'gray' language to see whether the added rule would make a clear cut or still keep it gray. – David Mulder Mar 23 '14 at 0:29
• "Major/generally known" is highly opinion-based... – Doorknob Mar 23 '14 at 0:31
• @Doorknob: Although programmers do tend to think that anything a computer can not parse is opinion based, it is not hard to draw a line there knowing any of the social sciences, but fair enough, let me change that to a something even a programmer is able to comprehend. – David Mulder Mar 23 '14 at 0:38
• Okay, seriously, now you're just being ridiculous. The reason an objective specification is needed is because two people might disagree with the interpretation of the rule. – Doorknob Mar 23 '14 at 0:45
• The grey area I was thinking about is mainly functional languages. Common LISP, Haskell, OCAML, and F# all see some serious use; I'm not sure whether any of them meet your updated criterion. I can also report that a two-byte solution which runs in two languages is possible, but wouldn't win: I've found a three-byte solution which runs in three languages. – Peter Taylor Mar 23 '14 at 18:10
• J and K were designed as production languages, but I haven't seen anyone use them as such. What do they count in this chalenge? – John Dvorak Mar 24 '14 at 16:16
• "it will be counted as esoteric if no commercial company with at least 50 employees can be pointed to developing it's main product in the discussed language." - first off, I don't think this kind of data is readily available. Second, I doubt you'll find a company that still codes in Algol, Perl or Fortran. – John Dvorak Apr 4 '14 at 7:46

# Split string of powers of 2

I had this idea while playing 2048; Every single power of 2 is unique, even if it contains another power of 2 as a substring because there are none that consist entirely of powers of 2.

For example, the string "2048409632864" can be split into 2048, 4096, 32, 8, 64 easily enough, but it can also be split into 2, 0, 4, 8, 4, 0963, 2, 8, 6, 4 with a simple left-to-right algorithm, which is incorrect.

So, the challenge is to correctly split these numbers in the shortest byte count possible. Is this a good idea?

• But 128 can be split into 1 (20), 2 (21) and 8 (2**3) ... – r3mainer Mar 24 '14 at 15:13
• Related - and read the comments, because I think a lot of that discussion is relevant to this question. – Peter Taylor Mar 24 '14 at 15:53
• Does the program need to split the string into the smallest range possible? So if you get 2048, do you need go back and convert it into 2, 0, 4, 8? – user10766 Mar 24 '14 at 15:53
• also, that no word in a language can be decomposed does not imply that concatenations of words in that language are always unique. – John Dvorak Mar 24 '14 at 16:13

# A "counting" quine

and maybe . Hopefully codegolf.SE isn't tired of quines and quine-derivatives.

The aim of this golf is simple. Write a family of programs A and a single program B in your language, such that:

• Program A(N) produces the source code of A(N+1) when run, independent of file name, current date, contents of STDIN, or similar external variables.

• Program B, when given the source of A(N) as input, returns N. Input can be via STDIN, function argument, preinitialized single-character string variable, or language's equivalent.

Your score is the sum of the lengths of A(0) and B in bytes. Lowest score wins.

I called it a counting quine, because it is easiest to implement like a quine, except it also counts. The purpose of program B is to potentially allow for non-numeric changes between the programs in A, such as an increasing line of asterisks or something.

### Things to consider

Is this too similar to "Program that creates larger versions of itself (quine-variant)?"

Golfscript has a particularly powerful answer to the above question, that could be adapted to this challenge. It seems like it would beat even my best J, which itself is a curt 29 + 10 = 39 bytes. If this question is dissimilar enough to post, are we just going to bite the pillow and let these two duke it out? Is there some kind of restriction that might make this a little harder or more unique?

Alternatively, should this be a ? Maybe it would be more fun or interesting not to constrain cleverness by size requirements.

• Seems potentially even more suited for functional tarpits. I suspect zot might be a contender. But it's certainly the case that the better answers to the other question are trivially adapted, so it would seem to be a duplicate as written. One way of adapting it which might solve that problem is to require B = A(0), or even to generalise that a bit so that A(N) with no input / empty input outputs A(N+1) and with input of A(M) outputs M+N in decimal. – Peter Taylor Mar 28 '14 at 15:11
• You should give more importance to max(N) rather than code size. – user80551 Apr 3 '14 at 4:58
• @user80551 What for? That's not really an issue, even for the Golfscript solution, if you assume that time and space are not issues: theoretically N can reach to infinity. The same can be said of my J solution. However, it raises an interesting question: maybe this could be a [code-challenge], affected by the rate at which the program grows? Or maybe we take the max N, if all the programs in A have to be less than a certain filesize? Hmm... – algorithmshark Apr 3 '14 at 5:17

(this isn't quite a duplicate of Water-Bucket problem because that question was ill-posed and apparently abandoned; it's also not a duplicate of 3 and 5 Litre Jug Puzzle because that one was just a single instance, and an instance of a different problem to boot)

# die-harder

THE PROBLEM

In commemoration of Leslie Lamport's Turing Award, let's borrow a problem from his TLA+ online hyperbook. There are two versions: "Die Hard" and "Die Harder." "Die Hard" is an instance of the general, "Die Harder" problem. "Die Hard" is the following:

Given an empty jug, jug[0], with capacity 3 gallons; and an empty jug, jug[1], with capacity 5 gallons, deliver exactly 4 gallons of water under the following rules; you may:

1. fill a jug completely, making its current amount equal to its capacity
2. spill a jug completely, making its current amount equal to zero
3. pour into a jug from another, either filling the destination, emptying the source, or both

One solution is to

1. fill jug 1 (amounts are 0, 5)
2. pour jug 1 into jug 0 (amounts are 3, 2)
3. spill jug 0 (amounts are 0, 2)
4. pour jug 1 into jug 0 (amounts are 2, 0)
5. fill jug 1 (amounts are 3, 4)
6. spill jug 0 (amounts are 0, 4)

I believe there are 3 more.

"Die Harder" is the following:

Given an ordered collection of n empty jugs with non-zero, not-necessarily unique capacities c[0], c[1], ..., c[n-1], deliver exactly k gallons of water, which may be spread out over multiple jugs, under the same rules as above.

THE CHALLENGE

Beat my reference Clojure code code for

A: performance, by choice of algorithm or by optimization or both (my algorithm becomes intolerably slow when the number of jugs > 3)

B: clarity (no obfuscators; we want to see your algorithm)

C: elegance

D: brevity

The above expresses the priority of the judging criteria: perf is more important that clarity, which is more important than elegance, which is more important than brevity.

Your code should behave as follows:

Given n, capacities in the form of a bracketed list like [3 5 7] and a target amount k, print t solutions in a form like the following in Clojure syntax, which is a solution for n = 2, capacities = [3 5], k = 4, and t = 2:

({:states
[{:amount 0, :capacity 3, :id 0} {:amount 4, :capacity 5, :id 1}],
:trace
[(fill-jug 0)        (fill-jug 1)       (spill-jug 0)
(pour-from 0 1)     (spill-jug 0)      (pour-from 0 1)
(fill-jug 1)        (pour-from 0 1)    (spill-jug 0) ] }
{:states
[{:amount 3, :capacity 3, :id 0} {:amount 1, :capacity 5, :id 1}],
:trace
[(fill-jug 0)       (pour-from 1 0)     (fill-jug 0)
(pour-from 1 0)    (spill-jug 1)       (pour-from 1 0)
(fill-jug 0) ] } )


Each of your t solutions must present the final states of the jugs and a sequence of moves, in order, that achieve the solution. Minor variations to the above format are ok.

Extra credit if your code produces optimal (shortest number of moves, fewest pours, etc.) solutions and you can prove so. You may present proofs in commentary with your code; acceptance of a proof is at our sole discretion, as is judgment of clarity and elegance.

Include instructions for running your code if it's non-obvious (as in, "how exactly do I run this bit of INTERCAL?").

OBSERVATIONS

If the gcd of the capacities does not divide the target amount, the problem has no solution. In your golf, you might check this (my reference code assumes it, instead).

Certain moves, while legal, are trivial, namely:

1. filling a full jug
2. spilling an empty jug
3. pouring from an empty jug
4. pouring into a full jug
5. repeating the last move, whatever it was

In your golf, you may either check for these trivial moves or not.

You might unit-test your code on inputs like the following:

capacities = [3 5 7],    k = any integer from 0 through 15
capacities = [3 5 7 11], k = any integer from 0 through 26


A REFERENCE SOLUTION

You can find a reference solution in Clojure here. It includes unit tests that demonstrate the program at work.

• What's the scoring system? What's the licence supposed to cover? How much flexibility is supposed to be implied by "in a form like the following in Clojure syntax"? – Peter Taylor Apr 30 '14 at 8:40
• Great questions. Will revise. – Reb.Cabin Apr 30 '14 at 12:47
• In your example Die Hard solution, I'm thinking you made a mistake in step 5 - wouldn't the amounts become 2, 5? – golfer9338 May 17 '14 at 12:06
• I've got two solutions for Die Hard showing -- in the first one, after the fifth step, namely (spill-jug 0), the 3-jug (jug 0) has 0 and the 5-jug (jug 1) has 2. In the second solution, after the fifth step, namely (spill-jug 1), the 3-jug (jug 0) has 1 and the 5-jug (jug 1) has 0. Not sure where you're seeing my error :) – Reb.Cabin May 18 '14 at 13:25

I have not put substantial effort into this sandbox post. Since I am unsure(and it's probably not) whether this kind of question is a good fit for this site or not. If somebody reputable mentions that the idea has merit, I'll tune this sandbox up, and try to get it in shape for posting.

Obviously the biggest problem is how do you test the code? And that's the part I'm stuck on. If anyone can think of a way to overcome this please let me know! Anyway, here it is:

Write a program that posts itself as an answer

Your program must establish an http connection to codegolf.stackexchange.com, login, and post an answer to this question.

The answer must be in the form of:

"

## [Language]

Code


"

Rules: Cannot read source file, or any resource which is identical to your source file in any way.

Tags: popularity contest, quine

• Imagine what would happen if people try to test each answer! – Peter Taylor May 6 '14 at 22:04

## Create an Andy Warhol portrait

Andy Warhol was one of the main figures of the Pop Art. One of his most famous works was a Marylin Monroe picture in nine frames changing the colors, saturation and others aspects of a original pic.

The challenge here is to create a program that takes any photo and emulates the Warhol painting with some caveats:

1. Final image should be compossed of 9 different frames.
2. Final image will be compossed from 3 rows and 3 columns.
3. Final image should be sized 3 times width and 3 times height of the original image.
4. The program should output just one image.
5. The image that the program outputs must be an emulation of Warhol works.
6. You cannot use any built in function that doest by itself the Warholization of the picture neither load or use any external image other than the original. You can use your language methods for changing color, hue, saturation..
7. Program should be deterministic: Any given photo should output the same image every time.

The program should read the image in JPG, BPM or PNG (at your convenience) and output the image in the same format.

The program will be tested with these images:

This is a so the most upvoted answers will win. Nobody restrains you from adding more warholized pictures for winning more votes from the judges.

• Where do you draw the line for a "built-in function that does the Warholization"? Are functions allowed that can adjust the hue of a pixel/an image? Or the saturation? Or the contrast? Neither of those is a function "to do Warholization", but of course they would probably take care of a large chunk of the work. – Martin Ender May 9 '14 at 8:04
• @m.buettner I would say you can use a set of functions that perform the task. If your language have functions to change hue, color, saturation you use them. You cannot use any function that does by itself the warholization (eg some external library or graphic editing program script calling a program built in action...) – Averroes May 9 '14 at 8:16
• Alright, thanks for clarifying (maybe add that to the question, that you really mean only functions that literally do the Warholization themselves). – Martin Ender May 9 '14 at 8:18
• @m.buettner Nice. I will add it to the specs. Thanks. – Averroes May 9 '14 at 8:20
• This seems to be close to a duplicate of Minature faking. It replaces the blur with repetition, but that aside they both seem to just be about simple transformations in HSV space. – Peter Taylor May 9 '14 at 11:48

# Brute Force Decryption

Write an function B() in any language of your choice that takes an encrypted string as input and brute forces though solutions then infers the key used. Your program should then output the decrypted string and the key.

The encrypted string is one that is in English, is a valid sentence and has been encrypted by shifting the ASCII number by the key.

## The Rules

• This is code golf, smallest program wins.
• You can’t use any external dictionaries.

## Encryption

To help you along I’ve written this program, which shows you how the string is encrypted:

def encrypt(string, key):
encrypted = str()
for Char in string:
encrypted += (chr(ord(Char) + key))
return encrypted

def decrypt(string, key):
decrypted = str()
for Char in string:
decrypted += (chr(ord(Char) - key))
return decrypted


Use Like:

>>> encrypt("secret", 5)
'xjhwjy'
>>> decrypt("xjhwjy", 5)
'secret'


I've put potential issues in bold.

We need some XHTML pages to test this on. I suggest http://www.w3.org/People/mimasa/test/schemas/xhtml1-sample.xml#headings.heading

# XHTML Compression Challenge (revision 5)

Design an algorithm to compress XHTML code as efficiently as possible. You must provide programs that do compression and decompression, and a detailed explanation. Input before compression and decompressed output should be identical and both valid XHTML.

The exact specification of XHTML we will be using is XHTML 1.0 Transitional as defined by W3C. This is to make the code easier to deal with - parameter values are always in quotes, there is a distinction between single and container tags, and all tags are properly nested.

This would be a , so the winner is whoever gets the best compression ratio on <some test code>. Obviously the algorithm should work on any HTML!

The sort of thing that I mean is

• not including the html tag in the compressed format (as you always know where it is)
• compressing h1, h2 and so on to 1, 2, etc.
• compress title to t

The test code (could be an actual webpage) (where do we get the test code) would contain a variety of HTML tags, in "natural abundances" (you won't suddenly have millions of kbd tags, say, but you would have lots of p or br).

The decompressed code and the original MUST be identical!

Or should we allow minute differences like interchanging <acronym> with <abbr>, or <strike> with <s>?

• Transforming <s>test</s> to <del>test</del> is not compression, so I think that the title is misleading. Your example is not good because we can see it as only replacing tags by other tags. – A.L Apr 15 '14 at 17:41
• @n.1 That's not what I mean, I mean that if we compress strikethrough as s, then <s>, <strike> and <del> can all compress to s. So the compression algorithm can make no distinction between the three, and then it can decompress s as any one of the three. – user16402 Apr 15 '14 at 17:51
• I'm sorry but I still don't see what are you waiting for. Please add an example of compressed text to see how to calculate the score. And what tags can be translated, what about <i> to <em>, etc.? The rules have to be strict so the users will know what tags can be translated to other tags. And this question lacks a input that will be processed by the users to compare the compression ratio. – A.L Apr 15 '14 at 17:58
• @n.1 maybe we can scrap the tag translation thing entirely? It does lack a standard test text to find compression ratio, I was hoping someone would find one. – user16402 Apr 15 '14 at 17:59
• @n.1 So, we scrap turning tags into other tags. But we should allow translating between <br /> and <br>, because they are EXACTLY the same. Or should we? (It would be annoying if we didn't.) – user16402 Apr 15 '14 at 18:01
• Do you want to judge purely on the compression ratio, regardless of the size of the submitted program? Would you be interested in having a bonus for a shorter program? For example, lowest total score wins, with score made up of compressed size/original size + log2(number of characters in program). I don't think this is needed - just wondering. – trichoplax Apr 16 '14 at 0:14
• @githubphagocyte I was thinking about that... but probably not. Maybe this time we judge purely on compression ratio, then we do a code-golf for the shortest implementation of the winning algorithm. – user16402 Apr 16 '14 at 7:03
• Yes separating the two does sound better. Good thinking. – trichoplax Apr 16 '14 at 9:47
• This looks to me suspiciously like "Write a wrapper about bzip2". Given that you're asking us to compress a format which has many equivalent ways of writing the same thing (lots of optional whitespace, optional ordering of attributes, flexibility in the quoting characters used, etc.) it would make a more interesting question to require that the decompressed file be semantically equivalent to the input. It makes testing it harder, but it allows for a lot more ingenuity. – Peter Taylor Apr 16 '14 at 10:09
• As a separate matter, if you're asking us to compress XHTML by using our knowledge of its structure, you should be more specific about which structure we can assume. XHTML has at least 6 versions, and arguably more: which of them must be supported? – Peter Taylor Apr 16 '14 at 10:12
• @PeterTaylor That might be a problem, I tried the validator.w3.org, even the Google homepage (supposedly respectable) gets 23 errors... – user16402 Apr 16 '14 at 12:29
• @PeterTaylor XHTML 1.0 Transitional? I personally find XHTML 1.0 Strict a bit annoying... – user16402 Apr 18 '14 at 13:09
• I don't really care which you pick: just that you make it clear in the question. – Peter Taylor Apr 18 '14 at 15:23
• can anyone suggest a test text? – user16402 May 14 '14 at 18:40

Preface

Kyle is in kindergarten. He can tie his shoes and count by twos and write in almost every programming language existent! But he can't seem to remember the days of the week. They always get mixed up in his mind.

So, his problem is that needs to know what day of the week it is tomorrow. He decides to write a program for himself.

But, his source code is stored in a very stingy cloud service. They charge \$1.99 per character! So, he decided to it all...

Challenge

So, Kyle has hired you for a whopping 15 reputation! Your challenge is, given the name of a day of the week (thursday, for example), you output the name of the next day (friday). The code with the least characters wins.

• The input and output can be in any reasonable method you like (STDIN/STDOUT, command-line, read from a file, anything).

• You are free to use any built-in function you like. As long as they don't do all the work for you (that's no fun).

• The input and output should be in lowercase. Kyle hasn't learned about capital letters yet.

• In case you don't know, the weekdays are: monday, tuesday, wednesday, thursday, friday, saturday, sunday. And they loop around. :-)

Good luck, and may the best code win!

Tags:

Commentary

I have seen a lot of weekday-related posts here on codegolf.SE, but I am pretty sure that this one will present a unique challenge.

I don't know if the "Preface" is too goofy. Please comment with your input and I will act accordingly with popular opinion.

• does "give me the string representation of n.1.2000 in the format 'full week name'" count as "all the work"? Because the rest is easy. – John Dvorak May 12 '14 at 15:29
• Also you forgot Sunday. – Martin Ender May 12 '14 at 15:32
• I'm not sure about presenting a unique challenge. This can be done in GolfScript with literally 5 chars plus a lookup table. The only interesting part is compressing the lookup table. – Peter Taylor May 15 '14 at 12:01
• It could be done in bash using time and adding a day, then specifying output format. – Shade May 16 '14 at 17:18
• @m.buettner : Duh on me. I guess maybe the problem isn't complex/long enough. Probably won't go live. – Robbie Wxyz May 16 '14 at 23:09

GCD Game for better algorithm

Given A,B print the number of pairs (a,b) such that GCD(a,b)=1 and 1<=a<=A and 1<=b<=B.

Input:

First line contains T, the number of testcases. Each testcase consists of two space separated integers denoting A and B.

Output:

The Number of pairs which have GCD=1

Constraints:

• 1 <= T <= 10
• 1 <= A <= 105
• 1 <= B <= 105

Sample Input

1
3 2


Sample Output

5


Explanation

There are five pairs of relatively prime numbers (where the first <= 3 and the second <= 2):

1,1
1,2
2,1
3,1
3,2

Time Limit 5 sec(s)

Memory Limit 256 MB

Source Limit 1024 KB

Use smart ways Bruteforce won't work.

• Okay, this is a start! So what's the objective winning criterion? Execution time of the program? In that case,on which benchmark and on which machine? Or code size? – Martin Ender May 27 '14 at 18:46
• If there are multiple testcases (T>1), should there be multiple numbers outputted? – Ypnypn May 27 '14 at 18:51
• Out of curiosity, are you just looking for an answer, or are you trying to make a competition out of it? I ask because the general feel of the spec makes me feel this was copied/pasted here from an exercise/task/homework, not intended as a competition. I ask because if you're just trying to figure out how to do it, another SE site might be a better choice for this. If it is a competetion, you should add winning criteria as m.buettner noted. – Geobits May 27 '14 at 18:52
• @Ypnypn if there is multiple test cases multiple outputs will be there – user3680169 May 27 '14 at 18:57
• @m.buettner Wining criteria is the most optimised code(optimised algorithm) which executes fastest – user3680169 May 27 '14 at 19:06
• @user3680169 as it stand that is not objective. do you want to judge that by actual execution time or by asymptotic complexity of the algorithm? in the former case, how is execution time measured, in the latter case, what about ties? – Martin Ender May 27 '14 at 19:16
• @m.buettner asymptotic complexity of the algorithm – user3680169 May 27 '14 at 19:18
• @user3680169 how are ties broken? It's not unlikely that two or more answers will have the same complexity. – Martin Ender May 27 '14 at 19:45
• The question should reference OEIS A135646. It should also clarify the output format in the case that there's more than one test case. Also beware that questions involving primality tend to get tricky enough to analyse for asymptotic performance that some people will either not answer because they can't analyse their own program, will answer without the analysis and expect you to do it for them, or will give an unnecessarily loose complexity bound. – Peter Taylor May 28 '14 at 17:07

# Factorize any number using a set of predetermined random numbers

For instance:

With the randomly generated set [1,2,3,5,8], factorizing 10 would give the result [2,5] as in 2*5=10.

• If a number can not be factorized using the provided set, indicate so. Using the same set, factorizing 13 would show an error or an empty list.

• Generated sets should contain less than 64 numbers.

# Bonuses

The score is given by floor (code length * (1 - 0,1 * # of bonuses))

• If a number can not be factorized, try to fix it using addition. In the previous example, factorizing 13 could give [2,5] and [3] as in 2*5+3=13.

• If a number can not be factorized, try to fix it using subtraction. In the previous example, factorizing 14 could give [3,5] and [1] as in 3*5-1=14.

• When generating a set, filter out primes and powers of 2.

• If posted like this, I would vote to close as not clear what you're asking. At the very least you need to specify what the input and output are. Then either ditch the bonuses or make them clearer: what exactly does "fix it using addition" mean? E.g. with [2,3] 17 do we get 2*2*3+2+3? – Peter Taylor Jun 10 '14 at 15:48
• Test comment, ignore. math – gxtaillon Jul 22 '14 at 0:05

# Find the a Strong Prime

What's a String Prime? Wikipedia:

In cryptography, a prime number p is strong if the following conditions are satisfied.[1]

• p is sufficiently large to be useful in cryptography; typically this requires p to be too large for plausible computational resources to enable a cryptanalyst to factorise products of p multiplied by other strong primes.
• p-1 has large prime factors. That is, p = a_1 q_1 + 1 for some integer a_1 and large prime q_1.
• q_1-1 has large prime factors. That is, q_1 = a_2 q_2 + 1 for some integer a_2 and large prime q_2.
• p+1 has large prime factors. That is, p = a_3 q_3 - 1 for some integer a_3 and large prime q_3.

## Input

Your program must receive a number of bits 16 <= x <= 60. This can be a method definition, command line argument, or stdin.

## Output

Print and/or return a strong prime of exactly the given bit length.

## Other rules:

• All variables in the below conditions refer to the wikipedia variables.
• Do not worry about condition 1 from wikipedia.
• For the rest of these rules, the notation |x| means the number of bits in x.
• |q_2| >= 0.4 |p|.
• You may not use any external tools. Other input data or precalculation counts against the length of your program even if it's in a different file or command line.
• You are allowed (and even encouraged) to use the algorithms in this paper (thanks @PeterTaylor!) but it is not a requirement.
• Three things. 1. 10 minutes is probably not enough for even good implementations of basic sieves. Are you expecting people to implement sophisticated sieves, or did you intend to allow probabilistic primality testing? 2. Why the "no more than 3 bits" constraints? There are plenty of definitions going around, but from cursory reading it seems that most of them would consider |q_2| >= 0.4 |p| to be sufficient. 3. Have you done a reference implementation to test that strong primes by your definition are sufficiently frequent for the time constraint to be feasible? – Peter Taylor Jun 17 '14 at 16:15
• In my above comment, || should be taken to mean length in bits rather than absolute value. – Peter Taylor Jun 17 '14 at 19:29
• @PeterTaylor how's that? – durron597 Jun 17 '14 at 20:13
• Is "other external tools" meant to include IsPrime functions? – Peter Taylor Jun 17 '14 at 20:38
• @PeterTaylor yes. but maybe that's not a good rule in this case? – durron597 Jun 17 '14 at 20:46
• Probably needs some input from Mathematica users, or you risk creating a restriction which they can waltz straight past. – Peter Taylor Jun 17 '14 at 21:10
• According to the OEIS, Miller-Rabin can be relied on to give accurate results for numbers up to at least 2^61 when tested with the first 9 prime numbers (i.e., a(9)>2^61). If the limit for p is extended to 2^64, then the first 12 primes will have to be tested. This shouldn't take long. – r3mainer Jun 18 '14 at 14:40

# Code Looking For 0x6C, 0x6F, 0x76, and 0x65 In All the Wrong Places

Write the shortest code that finds all instances of love" on the system. For this challenge love shall be defined as the bytes 0x6C, 0x6F, 0x76, and 0x65 in sequential order. It should look for love within files, in memory, and in file names. The code should run on Ubuntu to be tested. Assume you have whatever access you need to perform these operations.

Winning Criteria

The code will be run under a Ubuntu 12.04 instance that is hosted on a dual boot Windows 8.1 machine. There will be 1 file on each of the hard drives named love. The grub loader has a configuration called love. A program will be running in the background. If you find all the instances and have the shortest code. You will win. The contest will close XX/XX/YYYY.

• What's the winning criterion? How do you even test that submissions actually do find every single occurrence of his byte sequence? – Martin Ender Jun 2 '14 at 9:01
• Will this question be open in a browser, and hence held in memory, when you run the programs? Will the rival programs all be present on your machine while they are being run? I guess at least some of them will contain love... – trichoplax Jun 4 '14 at 21:02
• What does it mean to "find" it? Does a memory/file/offset location need to be output for each one? – Geobits Jun 4 '14 at 21:45
• That's a really good call out. I will have to think a little. – ojblass Jun 4 '14 at 21:52

# Saving Eve

## Background

In the year 1946 the organisation Illuminati launched their first intelligence collecting satellite - called Eve - into orbit around the earth. Onboard it contains a highly sophisticated set of sensors capable of eavesdropping on every telephone call in the world. All suspicious calls are recorded along with all ascertainable information about the caller and receiver. Eve then relays everything to Illuminati's office in Venice.

However, recently the growing amount of radio communication in space and on earth has started to interfere with Eve's downlink and uplink to and from the Venice office, which has resulted in spurious intermixing of the recordings of suspicious calls with the local weather report.

...we are to drop the bomb ... ...sunny and 28 degrees! In fair Verona... ...shoot them down...

Seeing as this interferes with Illuminati's ability to control all governments of the world, the error correction encoding firmware of Eve must be upgraded.

## Objective

You have been hired to write the new firmware for Eve. You have realised that the only sufficiently robust and efficient encoding is to use the extended binary Golay code, which encodes 12-bits into 24-bits of data. Luckily Eve was built in the 40's, before the 8-bit byte convention, so all the data that Eve processes is already in 12-bit chunks.

So you have to write a function or a program that takes one 12-bit chunk (as an integer) and outputs or returns a 24-bit chunk (again as an integer) according to the extended binary Golay code.

And you have to write a decoding function or program that takes one 24-bit chunk (again as a an integer) and outputs the decoded 12-bits, with a 16th bit set (2^15) if any correctable errors were detected, and a 20th bit set (2^19) if any uncorrectable errors were detected.

But since the uplink to Eve is unstable you must write the functions or programs in the least amount of characters possible, so that it takes a minimal amount of time to upload.

## Winning criteria

The least amount of characters in the source code of the encoding and decoding functions or programs.

## Note

The exact details of the output of the encoding is not that important, as long as the solution can correct any error up to 3 bits and detect any error up to 7 bits.

• Could do with a link to a good description of the code. – Peter Taylor Jul 3 '14 at 21:07

# Meta Code-golf code-golf

Golfing code can be slightly annoying[citation needed]. There are some things that can be automatically be applied to every golfing problem (e. g. remove all newlines). So what do you do? Automate it!

Your task is to write a program that will golf another program. Naturally, your program must be also be golfed, otherwise this wouldn't be a question, would it?

The following rules apply to your program:

• All the code must be in one file, except for that of the program your program is golfing.
• You may assume that the code of the program to be golfed is contained in a string. That string will not be counted towards your score.
• The output of the golfed program must be identical to that of the original program.
• Your program need only golf programs in it's own language. For example, a Python code-golfer-bot-thing need only successfully golf Python code, it can break all the Java code it wants.

Sandbox note: I'm not sure how to score this. The length of the golfer should be factored in, as should the difference between an ungolfed and golfed program. I'm thinking something like (ungolfed - golfed) / chars in answer, but this would require a way of finding the average number of characters removed. This suggests something of a , with random programs being chosen and passed to the bots to be golfed, but I would probably have to limit that to Python because that's to only language for which I have a bunch of random programs lying around on my box. However, I have no idea how to implement this and I don't want to spend a while looking through 100+ programs looking for sensitive information (passwords, email addresses, names). Anyway, in this case, score would probably be (average ungolfed - golfed) / chars in answer. Any thoughts? Side note to the sandbox note: sorry for the convoluted state of the note. I was basically just vomiting all my thoughts onto the page as they came to me.

• There's an entire tag for that. Are you sure your challenge adds anything new to this? – Martin Ender Jul 8 '14 at 7:42
• Essentially this idea has been proposed twice on the sandbox, and neither time has it prospered. It's very hard to write a good spec for it. I suggest that you look through the old sandboxes for the previous versions and read their comment threads. – Peter Taylor Jul 8 '14 at 8:20

# Reve's puzzle

When the pilgrims were stopping at a wayside tavern, a number of cheeses of varying sizes caught his alert eye; and calling for four stools, he told the company that he would show them a puzzle of his own that would keep them amused during their rest. He then placed n cheeses of graduating sizes on one of the end stools, the smallest cheese being at the top (and no cheese resting on a smaller one.) 'This is the riddle', quoth he, 'that I did once set before my fellow townsmen at Baldeswell, that is in Norfolk, and, by Saint Joce, there was no man among them that could rede it aright. And yet it is withal fully easy, for all that I do desire is that, by the moving of one cheese at a time from one stool unto another, ye shall remove all the cheeses to the stool at the other end without ever putting any cheese on one that is smaller than itself. To him that will perform this feat in the least moves that be possible will I give a draught of the best that our good host can provide.'

Write a function called reve that takes five arguments — the number of cheeses n >= 0 and labels for four stools (the source, two intermediaries, and the destination) — and outputs the minimum set of moves necessary to solve Reve's puzzle.

For example, the original puzzle is posed with n = 8, 10, and 21 cheeses, so running reve 8 "A" "B" "C" "D" should return the following 33 moves:

[("A","C"),("A","B"),("A","D"),("B","D"),("A","B"),("D","A"),("D","B"),("A","B"),("C","B"),("A","C"),("A","D"),("C","D"),("A","C"),("D","A"),("D","C"),("A","C"),("A","D"),("C","D"),("C","A"),("D","A"),("C","D"),("A","C"),("A","D"),("C","D"),("B","A"),("B","D"),("B","C"),("D","C"),("B","D"),("C","B"),("C","D"),("B","D"),("A","D")]


reve 10 "A" "B" "C" "D" (49 moves)

[("A","D"),("A","B"),("A","C"),("B","C"),("D","C"),("A","B"),("A","D"),("B","D"),("A","B"),("D","A"),("D","B"),("A","B"),("C","A"),("C","D"),("C","B"),("D","B"),("A","B"),("A","C"),("A","D"),("C","D"),("A","C"),("D","A"),("D","C"),("A","C"),("A","D"),("C","D"),("C","A"),("D","A"),("C","D"),("A","C"),("A","D"),("C","D"),("B","C"),("B","D"),("B","A"),("D","A"),("C","A"),("B","D"),("B","C"),("D","C"),("B","D"),("C","B"),("C","D"),("B","D"),("A","B"),("A","C"),("A","D"),("C","D"),("B","D")]


reve 21 "A" "B" "C" "D" (321 moves)

[("A","C"),("A","D"),("A","B"),("D","B"),("C","B"),("A","D"),("A","C"),("D","C"),("A","D"),("C","A"),("C","D"),("A","D"),("B","A"),("B","C"),("B","D"),("C","D"),("A","D"),("A","B"),("A","C"),("B","C"),("A","B"),("C","A"),("C","B"),("A","B"),("A","C"),("B","C"),("B","A"),("C","A"),("B","C"),("A","B"),("A","C"),("B","C"),("D","B"),("D","C"),("D","A"),("C","A"),("B","A"),("D","C"),("D","B"),("C","B"),("D","C"),("B","D"),("B","C"),("D","C"),("A","D"),("A","B"),("A","C"),("B","C"),("D","C"),("A","B"),("A","D"),("B","D"),("A","B"),("D","A"),("D","B"),("A","B"),("A","D"),("B","D"),("B","A"),("D","A"),("B","D"),("A","B"),("A","D"),("B","D"),("A","B"),("D","A"),("D","B"),("A","B"),("D","A"),("B","D"),("B","A"),("D","A"),("D","B"),("A","B"),("A","D"),("B","D"),("A","B"),("D","A"),("D","B"),("A","B"),("C","B"),("C","A"),("C","D"),("A","D"),("B","D"),("C","A"),("C","B"),("A","B"),("C","A"),("B","C"),("B","A"),("C","A"),("D","C"),("D","B"),("D","A"),("B","A"),("C","A"),("C","D"),("C","B"),("D","B"),("C","D"),("B","C"),("B","D"),("C","D"),("C","B"),("D","B"),("D","C"),("B","C"),("D","B"),("C","D"),("C","B"),("D","B"),("A","D"),("A","B"),("A","C"),("B","C"),("D","C"),("A","B"),("A","D"),("B","D"),("A","B"),("D","A"),("D","B"),("A","B"),("C","A"),("C","D"),("C","B"),("D","B"),("A","B"),("A","C"),("A","D"),("C","D"),("A","C"),("D","A"),("D","C"),("A","C"),("A","D"),("C","D"),("C","A"),("D","A"),("C","D"),("A","C"),("A","D"),("C","D"),("A","C"),("D","A"),("D","C"),("A","C"),("D","A"),("C","D"),("C","A"),("D","A"),("D","C"),("A","C"),("A","D"),("C","D"),("A","C"),("D","A"),("D","C"),("A","C"),("A","D"),("C","D"),("C","A"),("D","A"),("C","D"),("A","C"),("A","D"),("C","D"),("C","A"),("D","A"),("D","C"),("A","C"),("D","A"),("C","D"),("C","A"),("D","A"),("C","D"),("A","C"),("A","D"),("C","D"),("A","C"),("D","A"),("D","C"),("A","C"),("A","D"),("C","D"),("C","A"),("D","A"),("C","D"),("A","C"),("A","D"),("C","D"),("B","A"),("B","C"),("B","D"),("C","D"),("A","D"),("B","C"),("B","A"),("C","A"),("B","C"),("A","B"),("A","C"),("B","C"),("D","B"),("D","A"),("D","C"),("A","C"),("B","C"),("B","D"),("B","A"),("D","A"),("B","D"),("A","B"),("A","D"),("B","D"),("B","A"),("D","A"),("D","B"),("A","B"),("D","A"),("B","D"),("B","A"),("D","A"),("C","D"),("C","A"),("C","B"),("A","B"),("D","B"),("C","A"),("C","D"),("A","D"),("C","A"),("D","C"),("D","A"),("C","A"),("B","C"),("B","D"),("B","A"),("D","A"),("C","A"),("B","D"),("B","C"),("D","C"),("B","D"),("C","B"),("C","D"),("B","D"),("B","C"),("D","C"),("D","B"),("C","B"),("D","C"),("B","D"),("B","C"),("D","C"),("B","D"),("C","B"),("C","D"),("B","D"),("C","B"),("D","C"),("D","B"),("C","B"),("C","D"),("B","D"),("B","C"),("D","C"),("B","D"),("C","B"),("C","D"),("B","D"),("A","D"),("A","B"),("A","C"),("B","C"),("D","C"),("A","B"),("A","D"),("B","D"),("A","B"),("D","A"),("D","B"),("A","B"),("C","A"),("C","D"),("C","B"),("D","B"),("A","B"),("A","C"),("A","D"),("C","D"),("A","C"),("D","A"),("D","C"),("A","C"),("A","D"),("C","D"),("C","A"),("D","A"),("C","D"),("A","C"),("A","D"),("C","D"),("B","C"),("B","D"),("B","A"),("D","A"),("C","A"),("B","D"),("B","C"),("D","C"),("B","D"),("C","B"),("C","D"),("B","D"),("A","B"),("A","C"),("A","D"),("C","D"),("B","D")]


An up vote for all successful attempts. Shortest solution by character count wins. Sorry, no beer. Although if you're ever in the Boston area, it's on me.

### Questions

• Is this a suitable question for code golf?
• Is it clear what I'm asking? Do I need to be more specific about input/output, etc.?
• Any other suggestions?
• Is this a duplicate of Tower of Hanoi Solver? – Rainbolt Jul 9 '14 at 0:56
• @Rusher The only difference between this and the Tower of Hanoi is that this uses 4 stacks instead of 3. I'm not sure that's enough different, though it would defeat most Tower of Hanoi solutions, which are typically recursive, while this seems more brute-force. – isaacg Jul 9 '14 at 4:54
• The input/output spec is certainly unclear. You ask for a function, and then give examples of program invocation. The other thing which isn't clear is whether you want "pure" code golf (ignoring realistic feasibility assumptions) or whether you want a program which can actually execute for 21 discs with only e.g. 2GB of RAM, explicitly using disk as a backing store. – Peter Taylor Jul 9 '14 at 10:02
• I think the T(4,n) case of Tower of Hanoi is sufficiently different from T(3,n) and is the subject of many interesting papers. This does not require brute force. Frame-Stewart will solve this recursively, though it is still an open question whether the algorithm is optimal for all values of n and k in T(n,k). There are several papers that have popped on arXiv in the last few years that argue Frame-Stewart is optimal for T(4,k). – O-I Jul 9 '14 at 13:57
• @PeterTaylor I agree the input/output is unclear. Any suggestions on improving this? I wrote my solver in Haskell, hence the term 'function' and the lack of commas/parentheses for invocation. I'm fairly certain this is feasible — my function works and it will spit out reve 100 "A" "B" "C" "D" with little fuss (172033 moves). Perhaps I have made some mistake in my implementation? I can post the code if you would like to test. Regardless, I think this is a really interesting problem. Yes, it is 'just' Tower of Hanoi with 4 pegs, but a solution — let alone an optimal one — isn't obvious. – O-I Jul 9 '14 at 14:08
• It's an interesting problem, yes, but mainly because it's not clear that Frame-Stewart is optimal. The well-known 3-tower implementation is a special case of Frame-Stewart, and a fully general implementation isn't much more interesting. If we can assume optimality of Frame-Stewart, then I would vote to close as duplicate of the 3-tower question. If we can't, issues of performance (or of its irrelevance) need addressing. – Peter Taylor Jul 9 '14 at 14:25
• Understood. I guess it should be closed then. – O-I Jul 9 '14 at 15:00

# Type me out.

Your task (related to this question) is to translate any text (in a file, or simply input) into the input of a telephone keypad.

and provide a keypress score.

As the keypad has a limited set of keys you have to 'encode' your non-alphanumerics with their ASCii hexadecimal encoding; e.g. to type ~ (which is hexidecimal ASCII land is 7e) you press the hash key once, the 7 key (once to get a seven) and then 3 three times to cycle through the digits 3, 'd', and finally 'e'. This gives the code #7e which corresponds to ~ (for a total number of key presses of 5). Spaces and capitals have to be accessed via hex code (so MY_CONST (#4d #59 #53def #43 #4f #4e #53 #54 - 27 presses) costs you less than my_const (6m 9wxy #53def 2bc 6mno 6mn 7pqrs 8t - 29), but more than myconst (6m 9wxy 2bc 6mno 6mn 7pqrs 8t - 23)).

For instance If your code had print() that would cost 15 for the print (7p 7pqr 4ghi 6mn 8t) plus 6 for the () (#28 #29)

To be clear with just the input print() the output is:

7p 7pqr 4ghi 6mn 8t #28 #29
21


(Note however the hex codes for c f i r s v y z are shorter (correspondingly #63 #66 #69 #72 #73 #76 #79 #7a) than long hand key presses. It's perfectly allowed to score print() as 19:

7p #72 #69 6mn 8t #28 #29
19


)

This is Code Golf, so feed your code into the finished program - shortest answer (in keypresses) wins.

• Migrated from previous sandbox – Pureferret Jul 16 '14 at 7:33
• So we enter 'print()' as our input and the output is the second code block? and our answer needs to be processed by the program we wrote, and the shorted processed answer wins? 2 questions: 1) is ~ 3 or 5 characters? because we need to press 3 three times. 2) is our score the bytelength or the keypress score? – Nzall Jul 17 '14 at 11:09
• @NateKerkhofs 1) it's 5 2) it's key presses. – Pureferret Jul 17 '14 at 11:11