# What is the Sandbox?

This "Sandbox" is a place where Code Golf users can get feedback on prospective challenges they wish to post to the main page. This is useful because writing a clear and fully specified challenge on the first try can be difficult. There is a much better chance of your challenge being well received if you post it in the Sandbox first.

To post to the Sandbox, scroll to the bottom of this page or click on the "Add Proposal" link below, and click "Answer This Question". Click "OK" when it asks if you really want to add another answer. Write your challenge just as you would when actually posting it. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it. When you think your challenge is ready for the public, go ahead and post it, replace the post here with a link to the challenge and delete it.

See the Sandbox FAQ for more information on how to use the Sandbox.

## Get the Sandbox Viewer to view the sandbox more easily

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

## 2925 Answers

Math golf

This challenge is about writing code that outputs the smallest formula possible for a sequence of position integers.

Input

I will choose 10 from the following test sequences of positive integers. However, please do not hardcode these into your answers. If I suspect this has happened, I reserve the right to change the test sequences without notice.

Your code should accept standard in with one list of comma separated sequences per line.

1, 2, 7

12, 9, 7, 5

40, 25, 16, 10, 7

2240, 1225, 679, 373, 213, 149, 141, 133

8064, 3969, 1969, 974, 494, 254, 164, 134, 119

118272, 53361, 24196, 10958, 5027, 2399, 1271, 863, 746, 695, 668, 665

1, 4, 36, 400, 4900

96, 1280, 17920, 258048, 3784704, 56229888, 843448320

72, 800, 9800, 127008, 1707552, 23557248, 331273800

40, 224, 1064, 3808, 21280, 59200, 322600

2240, 832, 240, 72, 20, 6, 3

53760, 17152, 4480, 1248, 384, 104, 44, 22, 11

329472, 86656, 20800, 5536, 1536, 440, 124, 44, 19, 8, 4

32800768, 6856704, 1536000, 394752, 103936, 27136, 7936, 2080, 656, 264, 132, 66, 33

206389248, 33216512, 7029760, 1743360, 448000, 112640, 30144, 8288, 2096, 688, 284, 102, 46, 18, 9

20956446720, 2527756288, 510181376, 122363904, 30720000, 7643136, 1972224, 508416, 136192, 35456, 10816, 3296, 1360, 632, 292, 146, 73

Output

A math formula per input line which maps an index n starting at 1 to the relevant value.

A formula can be made up as follows. It can consist of the sequence variable n, integer constants, *, /, -, +, !, (, ), ^ or (m,k). These are to be interpreted in their normal mathematical sense with (m,k) to be read as binomial(m,k). The formula has to be well formed with, for example, parentheses matching and the order of precedence of operators will be the usual mathematical ordering.

A special rule applies to the factorial function ! which requires parentheses if the ^ or ! operators are to be applied to the result of the factorial. I.e. it is (n!)^2 and not n!^2. Note that the !! is never allowed. Unary - also requires brackets if any further operator is applied to the result on the left hand side or if the result is to be raised to a power. For example it is n*(-1) and not n*-1.

Score

I will test your code on a number of sequences of integers that I make.

The score is the sum of the number of characters in all your outputs.

Example output

For the sequence that starts 96, 1280 above, the output 4^(n+1)*(2*(n+1))!/((n+1)!)^2 gives a score of 29.

• It's an interesting idea, but it sounds brutally hard in the absence of gimmicks. There is, generally speaking, no systematic or efficient procedure for turning a sequence of numbers into a formula. – COTO Nov 21 '14 at 1:22
• There's always the polynomial of degree length-1... which is the only realistic option if you write something longer than 10 characters. One could try to golf the polynomial a bit but anyway it wouldn't be a great challenge. – feersum Nov 21 '14 at 2:19
• @feersum and COTO , The challenge is interesting, I hope, if many of the test cases come from sequences which do have short formulae. You are right that if the sequences are genuinely chosen at random it is perhaps not so interesting. – user9206 Nov 21 '14 at 15:22

# Generalized Array Indexing

Most programming languages provide an array datatype (which might be called a list or a vector) that supports indexing. Given an array and a nonnegative integer, we can fetch the element of the array at that position: [a,b,c][0] = a. Some languages, like Python, support a more general indexing system, where passing a negative index counts the position from the end: [a,b,c][-1] = c. But why stop there?

In this challenge, your task is to provide another generalization of this operation. In other words, you must provide a function that takes in an array and a number, and returns something, up to the following restrictions:

1. If a nonnegative integer is passed to the function, it must return the element of the array at that position. In other words, it must be an extension of the array indexing operation.
2. It must support more indices than just nonnegative integers, like negative integers, fractions, complex numbers, or even strings. In other words, it must be a proper extension.

If necessary, you may restrict the types of elements your arrays may contain, so you may choose to only handle arrays of, say, floating-point numbers, or other arrays. This is a popularity contest, so the answer with the most upvotes wins.

• I'm sure people would come up with some fun ideas, but I believe this is currently a bit too broad as it stands (the telltale sign being a "something" in italics in your spec). – Martin Ender Nov 25 '14 at 17:37
• That was my fear too. I don't know whether this can be turned into a good challenge without changing the idea completely, but I'll leave it here for now. – Zgarb Nov 27 '14 at 16:43

# Play Chopsticks

Disclaimer: Please fix the question and the scoring if they are not satisfactory. I am probably not qualified to run and score entries because I am not entirely familiar with the logistics of running two programs against one another, and, as such, I will not be posting this question to the main page myself. So, if anyone wants to take this off my hands, feel free. I just really like this idea and want to see it happen.

Chopsticks Wikipedia article

Your challenge is to write a program that, given the current position of the game as input (how many fingers on each hand), outputs the next move it chose to take.

## Rules of the game

(Normal rules, no variations)

1. When a hand's finger-count becomes >= 5, it's finger-count becomes 0.
2. Splitting/transferring is allowed. You CAN bring a dead hand back by transferring some fingers from your other hand.
3. However, splitting/transferring is not allowed if the move only results in you having swapped your hands. (eg. no prolonging the game by "doing nothing")
4. A player loses if both their hands are dead.

## Input

You will receive as input the number of fingers on each of your and your opponents hands.

Input will be given in the following format:

#_on_your_LH #_on_your_RH #_on_opponent_LH #_on_opponent_RH


Examples:

1 1 1 1


or

4 0 3 2


## Output

Your program will output your move base on the input.

Key:

First number:
0 (your LH)
1 (your RH)
2 (transfer from your LH to your RH)
3 (transfer from your RH to your LH)

Second number:
If first number was 0 or 1:
0 (opponent's LH)
1 (opponent's RH)
If first number was 2 or 3:
1-3 (# of fingers to transfer)


Examples:

0 0 (tap opponent's RH with your LH)
0 1 (tap opponent's LH with your LH)
1 0 (tap opponent's RH with your RH)
1 1 (tap opponent's LH with your RH)
2 1 (transfer 1 finger from your LH to your RH)
3 2 (transfer 2 fingers from your RH to your LH)


## Scoring

Each entry will be made to play a game against every other entry.
If a game does not end after 100 rounds (?), it will be declared a tie.

Two points will be awarded for every win and one point will be awarded for every tie.
Entry with the most points is the king of the chopstick-hill.

• This sounds so familiar, I feel like it has been posted before, either on main or in the sandbox (or maybe it was just discussed in chat), but the game has so many names that it's hard to find right now. (Looks like it was the sandbox and died off right away: chat.stackexchange.com/transcript/message/17654246#17654246) – Martin Ender Nov 29 '14 at 23:01
• @MartinBüttner I still think that this should be done. Perhaps it could be made more interesting by allowing the programs to see the whole game, not just on a turn-by-turn basis, and they then could adapt to their opponents. Though I believe that would require networking / competing on a server, of which I know little. Well, in any case, like I said, I just thought this was a good idea and wanted to see it happen, though I don't feel up to taking the responsibility to do it myself. If this dies off too... oh well. – kukac67 Nov 29 '14 at 23:23
• I'm not sure if I remembered right, but I thought Chopsticks was a solved game for the second player? – Sp3000 Nov 30 '14 at 3:27
• @Sp3000 Dang it. I think you're right. I wonder if any of the variations to the game change it enough for it to require more strategy and not be a solved game. – kukac67 Nov 30 '14 at 20:12

# N-gon Naming

## Challenge

Given the word name of a polygon n, you must output the number of sides polygon n.

## Examples

Input:  triangle
Output: 3

Input:  dodecagon
Output: 12

Input:  megagon
Output: 1000000

Input:  hexahexagon
Output: 66


## Winning

The shortest code wins.

The list of shape names can be found here with instructions on how shape names are constructed. Use the alkane naming system.

• In case you aren't aware, there's a pretty simple formula to find these numbers. – Geobits Nov 13 '14 at 19:58
• @Geobits This is more parsing of the shape name – Beta Decay Nov 13 '14 at 19:59
• For some reason I thought that part was a dupe, but it turns out I can't find anything except going the other way (3->tri). – Geobits Nov 13 '14 at 20:02
• You'll probably need to define an upper limit, like this question did – FryAmTheEggman Nov 13 '14 at 20:46
• If the challenge is really about parsing the shape name, then just have that be the question. – xnor Nov 14 '14 at 10:12
• It might be a good idea to point out if we need to support Tetracontadigon, as well as 42-gon. – FryAmTheEggman Nov 19 '14 at 15:30
• The rules on that new link are confusing. What is a hexahectogon? 6100? 600? – FryAmTheEggman Nov 20 '14 at 19:13
• Can we really trust a site that says Is there actually a name for a 27 sided pentagon? Yes there is.? – feersum Nov 20 '14 at 21:56
• @feersum Yeah... I was hoping to find a long list of every shape from 3 to n... That's the best I could do ATM – Beta Decay Nov 21 '14 at 7:03
• en.wikipedia.org/wiki/Polygon has a better list with more rules than the site you linked. Anyway, both sites offer various alternative names and you should specify which are required, and the maximum number of sides to be supported. It is very, very unclear how a polygon with more than 1999 sides should be named. – Level River St Nov 30 '14 at 12:40
• @steveverrill A polygon with more than 1999 sides -> circle ;) – FryAmTheEggman Dec 1 '14 at 17:34

# Help Bob the Builder survive the communists, and fast!

The communists have taken over the world and you are the last remaining tower builder. In order to surive you must show that you are able to build towers and fast!

## The challenge

Bob is given a set of building blocks b, and a number n of towers to build. Since we are in communist land the towers should have as equal of an height as possible. The catch is that you are only given 180 seconds to build the towers. The goal is to minimize the std of the tower height. In addition you have to build towers at three different sites. Which means three different sets of building blocks and three different set of towers.

## Input & Output

blocks = [1,2,3,4,5,6,7,8,9]
towers = 3


The ouput should be on the form

7 6 2
8 5 4
1 9 5

std = 0


Here the towers are built vertically. The std is calculated as follows

std = sqrt[(mean - tower1)^2 + (mean - tower2)^2 + ...]


where tower1 represents the height of that tower and mean is the average of the heights.

mean = (tower1 + tower2 + ... + towern)/towers


# Example 2

Input

blocks = [1,2,3,4,5,6,7,8,9]
towers = 2


Output

5 3 2 4 1
9 6 7 9 0

std = 0.7071


Since mean = (23+22)/2 = 22.5 and std = [(22.5-23)^2+(22-23)^2]^(1/2) = [1/4+1/4]^(1/2) = (1/2)^1/2.

These two are examples of optimal outputs. Since the problem is NP hard an optimal solution within a reasonable time is impossible.

# Scoring

The blocks for the three building sizes are given below. The sum of these three tests judge your performance. Lowest score wins. Eg

 score = 100*std(1) + 50*std(2) + std(3)


Where std stands for the standard deviation obtained at building site n. Do not try to cheat and make a code that runs longer than 300 seconds. The KGB (Eg me) performs regurarly controls.

# Question for meta

1) Is the problem clear enough? Eg use the three vectors and distribute them equally

2) Is the scoring now fair? Must have a run time beneath 3 minutes, lowest score wins.

Building site 1: 2 towers

Building site 2: 3 towers

Building site 3: 23 towers

• How is this different to your previous question? – Peter Taylor Dec 14 '14 at 17:48
• In previous question the number of elements in each tower were fixed, here only the number of towers are fixed. There is now a logical time constraint as well as a fair score system. Plus slightly more creative vectors. Is that enough? – N3buchadnezzar Dec 14 '14 at 18:07

# Quine is love, quine is life (well, almost)

Yes, another Life challenge. Inspired by this.

# Challenge

Write a program (the generator) that, when given a representation of a Game of Life board on STDIN (or in a file if you like), outputs a program which contains a string representation of a Game of Life board in its source code.

The representation will be in the following format:

 h w x1 y1 x2 y2 x3 y3 . . . xw yh


where:

• h = height of the grid
• w = width of the grid
• xi yi = coordinates of a live cell

When run, the new program should output its own source code - with a catch: the string in the output must represent the generation following the one previously encoded. (We shall call this program the replicator.)

# Other stuff

• All live cells will be provided as input, so all other cells may be assumed to be dead.

• 0,0 is at the bottom left.

• Both programs (the generator and the replicator) need not be in the same language.

• There may be a width-one border around the string representation for a -10% bonus in score.

# Scoring

Your score on a particular input will be defined as the length of the generator plus the average length of the first 100 generations of the replicator.

Your final score will be the average of your scores on all the test cases. The lowest score wins!

# Question

Should we impose a format for the string representation, like maybe

* * * * * * * * * * * * * * * * * * *
*                                   *
*                                   *
*                 *                 *
*               *                   *
*               * * *               *
*                                   *
*                                   *
*                                   *
* * * * * * * * * * * * * * * * * * *


or should we let the GolfScripters and CJammers of PPCG use their unprintable black magic? :D

• Just to check, the scoring formula is generator_length + sum(replicator_lengths)/100? The bolding is a tad misleading: it seems to imply that the division is performed also on the generator length (which would be very odd). – FryAmTheEggman Dec 22 '14 at 3:33
• That is indeed what I meant, but you're right; it is a bit odd. Fixing. – Soham Chowdhury Dec 22 '14 at 4:27
• The scoring formula is generator_length + sum(lengths of first 100 replicators)/100. – Soham Chowdhury Dec 22 '14 at 4:30
• This looks like a less interesting version of this Life quine question. If you do decide to allow flexibility in the representation, you'll need to be careful to avoiding being too close a duplicate. Other than that, I don't understand what h and w are (is there an unspoken assumption of boundary conditions?) nor what you mean about 0,0 being the bottom left (since the output doesn't care which directions the axes run) or about having a border around the string representation. – Peter Taylor Dec 24 '14 at 11:06

## Query the icosahedral graph

You've been sent back in time to 1973 to change history by remaking a clone of Hunt the Wumpus. You need to code a network of rooms in the game that forms an icosahedral graph, whose vertices correspond to the 12 vertices of the icosahedron connected by edges, unlike the dodecahedral graph used in the original game. Each room connects to five others.

Your goal is to write a program or function that takes the ID numbers of two of the twelve rooms, and returns one value if the rooms are adjacent, and a different value if not. Due to space constraints, you code needs to use as few bytes as possible.

You can choose what ID's to label the 12 rooms, but due to hardware constraints, they must be numbers from 0 to 255. Specifying the ID's doesn't count for the code length.

Input

Two distinct ID numbers from 0 to 255 out of 20 of your choice. You can't restrict which order two numbers appear in.

Output

A consistent value for pairs of numbers that correspond to adjacent rooms in your ID scheme, and a different consistent value for non-adjacent pairs.

Your code may not use any built-ins that represent the dodecahdral graph or related structures.

• I haven't actually given much thought to how to do this and how hard or easy this easy. Looking for feedback on this half-baked idea. – xnor Jan 3 '15 at 18:24
• Well, Hunt the Wumpus has been done. Not sure how much more room for variation this subchallenge gives other than ripping out the relevant parts from the answers of the previous challenge. – Martin Ender Jan 3 '15 at 18:37
• @MartinBüttner Fair point, I'll switch to a different graph. – xnor Jan 3 '15 at 18:48
• I'm not sure at the moment which graph the question is trying to talk about, but IIRC both dodecahedron and icosahedron have been done. In fact, you did a dodecahedron graph structure question already. – Peter Taylor Jan 3 '15 at 19:12
• @PeterTaylor I guess I'm not conveying my idea well. The core idea is to make a two-input function whose truth table is isomorphic to some specific graph, with you getting to choose the input labels and the isomorphism. So, it's a question of how to represent the required graph as much as how to code it. For example, if I asked to make a 16-vertex hypercube graph, you could label vertices by the four-bits numbers 0 to 16 the natural way, and check for an edge by whether the xor of the two labels is a power of 2. – xnor Jan 3 '15 at 23:21
• I understood that. How do you feel about switching to the Petersen graph? It's comparable in size and complexity, but it's definitely not treading on the toes of the previous questions. – Peter Taylor Jan 4 '15 at 9:16
• @PeterTaylor The Petersen graph happens to have a compact and elegant solution that's surely optimal. Got any other graphs to suggest? – xnor Jan 5 '15 at 3:16
• Fair point. How about the McGee graph? It's not vertex-transitive, so I think that probably forces a different approach to the group representational approach which was used on the earlier questions. Other interesting options might be the Pappus graph and the Coxeter graph, but they have more symmetry. – Peter Taylor Jan 5 '15 at 20:01

# Reverse Polish Notation-ing!

Your challenge is simply to write a function which converts a given arithmetical expression into it's Reverse Polish Notation form.

## Input

Your function will be passed in an arithmetical expression, as a string, which may contain any of +-*/^() or a space. For example:

1+1 34 * 7^6 3 * (78 + 7)

## Output

Your function should return the Reverse Polish Notation form of the input with a space between each number. The above inputs would output:

1 1 + 7 6 ^ 34 * 78 7 + 3 *

## Scoring:

This is so shortest code wins. Bonuses are as follows:

• -15 for supporting brackets in the input (as in: ())
• -5 for supporting exponents (as in: ^)
• -10 for supporting floating point (decimal) numbers (formatted with a dot: 12.56)

You should support, at minimum, +, -, * and / operations.

Good luck!

To the sandbox:

• Should I give more examples or is 3 enough?
• Do you think the deductions are a fair amount off? Too much? Too little?
• Am I missing something really obvious? (I usually am!)
• I would call the inputs arithmetical expressions instead of sums, since there can be other operations than addition. – Zgarb Jan 3 '15 at 19:55
• Thanks, I couldn't think of a better word! Edited :) – JamJar00 Jan 3 '15 at 19:57
• Looks like it's a duplicate. – Martin Ender Jan 3 '15 at 20:24
• Gah! Thanks, Nevermind then :( – JamJar00 Jan 3 '15 at 20:25

Print the Twelve Days of Christmas with twelve programming languages

Use twelve programming or scripting languages to write twelve programs, embedded within each other, to print the lyrics for Twelve Days of Christmas.

Each program will write the next program to file, compile if needed, and execute it. The parent processes will not exit until the last has executed. When they exit, they will print the final verse, program by program. You may only have one file to start with. You may also, optionally, have a text file with each line of the song in it.

You must specifiy any dependencies needed to run the programs. For example, if you need a compiler, such as GCC, or PHP or the Java compiler/Java, put them in a list of dependencies.

For example:

<?php
echo "On the first day of Christmas, my true love gave to me:\nA partridge in a pear tree!\n";
$code = <<<EOD public static void main(String [ ] args) { String nextCode = new String; System.out.println("On the second day of Christmas, my true love sent to me:"); System.out.print("Two Turtle Doves\nand a Partridge in a Pear Tree\n"); nextCode = "(Next code to be written is in here)"; PrintWriter writer = new PrintWriter("thirdDay.c", "UTF-8"); /* * and write the next program, in this case, thirdDay.c to file and so on.... */ } EOD; file_put_contents("secondDay.java",$code);
exec("javac secondDay.java");
echo exec("java secondDay");
echo "and a Partridge in a pear tree"; // runs after the other twelve have run
?>


Apologies for my rusty Java.

To reiterate:

1. The program is started
2. The program prints the appropriate verse
3. The program writes the source code for the next program to file, which in turn contains the code for the rest, and so on.
4. The program compiles (if needed) the next program, and runs it.

The final program will only print the line for Day 12. It will then exit, returning to its parent program, which will print the second line - Day 11, exit, and so on. In my example, this line will run last:

echo "and a Partridge in a pear tree"; // runs after the other twelve have run


Have fun with those quote marks. I started with PHP and Heredoc for a reason ;)

Assume that this will be run in a Linux/Unix terminal. Windows is okay if you can pull it off.

This is a popularity contest. Assuming that you can get everything escaped properly ;)

Merry Christmas!

• My comments on self-contradiction from the original question still stand. – Peter Taylor Jan 6 '15 at 21:43
• I'll edit it later, but since it's past Christmas, it's got lower priority now. Can you provide an example of self-contradiction? Perhaps I can remove the offending part to clear it up. (While the first 11 print the full song until day x, number twelve only prints its first line (Partridge) and then exits, sub-program number eleven then prints Turtle doves, exits, and so on until the original program.) – Austin Burk Jan 7 '15 at 0:29
• "It's not clear whether the final output should be the full lyrics of the song (one verse per program) or just the last verse (one line per program); or whether each program in the chain should print then execute (as per example code and numbered breakdown) or execute and then print (as per "*It will then exit, returning to its parent program, which will print Day 11, exit, and so on")*" – Peter Taylor Jan 7 '15 at 23:31

# A natural divisor

Expressiveness, natural language elements and readability, these are just a few of the awesome features/ideologies modern high-level languages promise us. But how "readable" and "natural" are these languages really? Can you really read them as they were english? In this challenge you have to prove how (un)natural your preferred language really is.

## Challenge

You're to write a program that accepts a list/string of numbers from the STDIN, and outputs their greatest common divisor to the STDOUT. However you also need to write a complete description of your program, an english explanation of your entire program. The challenge is to make your program resemble the description as much as possible. As in a perfect natural programming language there would be no difference, your score will be the Levenshtein distance between your program and your description.

## Rules

• Your description can only contain correct english sentences. The sentences must be at least six words long.
• The description must contain the full and correct process of your program. Nothing more or less. An example can be found below. As a general rule: a programmer that doesn't understand your language should completely understand your description and should be able to recreate the exact algorithm.
• Your program cannot contain both comments or strings.
• Your program should use the universal accepted definition to calculate the greatest common divisor. If the input only contains 0's, you have to output 0.

## Example

This is a fibonacci function to illustrate how a description should look like:

PROGRAM:
def F(n):
if n == 0: return 0
elif n == 1: return 1
else: return F(n-1)+F(n-2)

DESCRIPTION:
Define a function F with input n. If n equals 0, return 0.
Else, if n equals 1, return 1.
Else, return the output of F with input n minus 1,
plus the output of F with input n minus 2.


## Score

As mentioned earlier, your score is the levenshtein distance between your description and your program. You can calculate your levenshtein distance with the following snippet (thanks doorknob):

var f=document.getElementById("f"),g=document.getElementById("s"); function h(){var a=f.value,e=g.value;if(128<a.length)a="<span style='color:red'>First program is too long!</span>";else if(128<e.length)a="<span style='color:red'>Second program is too long!</span>";else{if(0===a.length)a=e.length;else if(0===e.length)a=a.length;else{var d=[],b;for(b=0;b<=e.length;b++)d[b]=[b];var c;for(c=0;c<=a.length;c++)d[0][c]=c;for(b=1;b<=e.length;b++)for(c=1;c<=a.length;c++)d[b][c]=e.charAt(b-1)===a.charAt(c-1)?d[b-1][c-1]:Math.min(d[b-1][c-1]+1,Math.min(d[b][c-1]+1,d[b-1][c]+ 1));a=d[e.length][a.length]}a="Distance = <strong>"+a+"</strong>"}document.getElementById("d").innerHTML=a}f.onkeyup=h;g.onkeyup=h;
<h3 id=ft>program</h3>
<textarea id=f rows=7 cols=80 style="width:100%"></textarea>
<h3 id=st>description</h3>
<textarea id=s rows=7 cols=80 style="width:100%"></textarea>
<p id=d></p>

# Sandbox questions/notes:

• The question was just crazy idea for the most part. Do you think this question would work?
• Are there any languages that would get an unfair advantage? Are there more things I should ban?
• I know the description of the program description is somewhat subjective, so the answers would mostly involve being creative with their description. Are their any additional rules that could restrain this?
• The six word restriction seems pretty arbitrary. I might want to write If so, return 0. which seems like a perfectly normal sentence in a program description to me. The main trouble will be determining if a description is "good enough". You could do so by defining a vote threshold an answer needs to be eligible, but it's not a perfect solution either. As for the Levenshtein distance, I'm sure Doorknob won't mind you reusing his Stack Snippet. – Martin Ender Jan 10 '15 at 13:27
• @MartinBüttner I added the six words restriction to avoid one word verbs as a sentence, and force some more verbose description. But I might delete/lower it... A vote threshold is not that bad of an idea actually... – Def Jan 10 '15 at 15:11

# Final Exam Grade Calculator

So, it's around time for finals, and many students want to know what grade they need on their final exam to achieve an A, B, or sometimes a passing grade. There are many factors here - the weight of the final, two quarters having weight, what grade the students want - but it is still a simple task.

## Objective

Write a program that will take three integers and output the grade they need to receive on the final.

### Input

Three integers. The first two will be from 0 to 100, and the last will be from 1 to 100. They represent the current score in the class, the desired score, and the weight of the final, respectively. A working example can be found here.

Any input outside the expected ranges can have undefined behavior.

### Output

The score the student needs to receive on the final exam. This score could be above 100 (every once in a while, students have unrealistic expectations), but if it is a negative number, it is automatically 0. The formula for score is as follows.

(desired - (current score * (1 - weight*.01))) * 100/weight

The output may not be an integer. In this case, round to the nearest hundredth (round up for .##5).

### Examples

Input: 100 90 20
50


Input: 65 60 30
48.33


Input: 54 100 25
238


### Scoring

This is a challenge, so the shortest code wins.

Bonuses

• -10% if your code can take either 3 or 4 integers as input. If four integers are taken, then the first two are averaged to give what would normally be the first integer. Each of the first two integers here represents a quarter grade.

What other bonuses should I add? I can't think of many right now, but even one or two more would be helpful.

• Maybe it's British vs American English, but I find that this question uses some words rather strangely. When the output talks about finding a score, that's the word I expect to see in almost every instance of grade; I would understand grade to mean the letter A, B, etc. That aside, there are some small changes which I think are improvements on either side of the pond: change expected to desired, and specify with the rounding which way to round ##.##5. It would probably also be useful to state explicitly that scores are always out of 100. – Peter Taylor Jan 14 '15 at 8:36
• Oh, corner cases. Input 80 80 0 is apparently legal, but gives NaN; I would change the spec to say that the weight ranges from 1 to 100. Input 90 80 1 will give a negative number from your formula, but IMO the spec should ask it to be clipped to 0. You could make that a bonus, but I'd make it a core requirement. – Peter Taylor Jan 14 '15 at 8:40
• @PeterTaylor Right on everything there. Edge cases will have to be specified. I didn't realize that there were so many. About the wording, I will see what I can do to make it more logical. – mdc32 Jan 14 '15 at 13:45

# Possible resistances from resistors

Meta: Note this is far from done; just putting this idea out so that I can continue working on it. IE way work in progress. I need to specify a lot more of this and I'm putting this here because I know I won't end up working on this if it isn't here.

Given a set of resistors, output all the possible resistances that can be formed with them.

Thoughts so far:

# Input:

Input will be a comma-separated or space-separated list of natural numbers such as

1 4 3 2 4 3 5 999


# Output:

Output will be all the possible formable resistances, sorted, on its own lines, plus the number of ways to form each resistance.

(no example yet)

• Sounds like a complicated combinatorial problem wrapped around codegolf.stackexchange.com/q/12483/194 . I wouldn't be surprised if you get a few wrong answers and zero correct ones. – Peter Taylor Jan 16 '15 at 8:45

# Implement the Henkin quantifier

Your goal is to implement the Henkin quantifier Q_H, a generalized (branching) quantifier on four variables x1,x2,y1,y2 and a Boolean function f. It expresses the idea that for every choice of the x's, there's a choice of the y's so that the four variables satisfy f, so that each y depends only on the corresponding x and not the other one.

The parallelness of the choice of is sometimes represented by stacking the paired quantifiers like this:

This quantfier cannot be expressed in first-order logic.

The parallel choices for the y's are like prisoners being interrogated in separated rooms. They are each asked the respective questions x1 or x2 and must give respective answers y1 and y2 without knowing what the other one was asked, so they are liable to be trapped in inconsistent claims. The guards then evaluate the validity of their responses ointly by some function f that depends on both questions and answers. If the prisoners can always win this game, then f satisfied the Henkin quantifer Q_H.

Formally, the Henkin quantifier Q_H takes in a Boolean function f of four inputs (x1,x2,y1,y2), and evaluates whether the following statement is True:

For every x1 there exists a y1, and for every x2 there exists a y2, so that f(x1,x2,y1,y2) is True, and the choice of y1 depends only on x1 and the choice of y2 depends only on x2.

Alternatively stated in Skolem normal form

There exists functions g1 and g2 so that for every x1 and x2, the function f(x1,x2,g1(x1),g2(x2)) is True.

For this challenge, the domain of discourse will be natural numbers from 0 to 9.

Input:

A function f that takes in four numbers x1,x2,y1,y2, each between 0 and 9 and produces a Boolean output.

Output:

A consistent Truthy value if f satisfies the Henkin quantifier Q_H, and a Falsey value if it does not.

Questions for Sandbox:

1. Does this challenge make any sense?

2. What should the input format be? Not every language can take in functions. What about nested lists? Subsets of four-digit numbers?

• Let me see if I can interpret it. Does it mean that there exist two functions g and h such that f(x1, x2, g(x1), h(x2)) is true for all x1,x2? – feersum Jan 21 '15 at 16:43
• @feersum Yes, that's right. – xnor Jan 21 '15 at 22:27
• The obvious input formats for non-functional languages would seem to be a 4D truth table array boolean[][][][] or a 2D "accepted" array int[][4]. – Peter Taylor Jan 25 '15 at 23:22

# The Great, White, North! code-golf - POSTED

• 1. What are the bounds on the relative proportions? 2. What are the RGB codes of the colours? 3. What are the minimum dimensions? 4. What's to stop me using a font which is so different that only I can read it? 5. Does "saves an image" include "writes an image on stdout"? – Peter Taylor Jan 8 '15 at 9:31
• Since there is no clear consensus on this yet you might want to mention explicitly whether you will allow golfed/compressed raw image files as submissions. – Martin Ender Jan 8 '15 at 11:35
• In-universe note: You should probably just save a highly compressed image instead of a program to produce the image. You might then be able to squeeze another syrup recipe on there (or a script to curl the latest hockey scores). – Geobits Jan 12 '15 at 2:33
• @PeterTaylor Been almost two weeks but I finally revamped it. Thoughts? – globby Jan 21 '15 at 2:41
• Sorry, I was travelling. Looks like you sorted all the issues I raised, though. – Peter Taylor Jan 25 '15 at 23:18

# Solve a LaserTank level (optimally?) [WIP]

LazerTank is more than just a computer game, it is a blast from the past. In this game, the player controls a tank that shoots lasers and navigates through a series of puzzles. The goal of this challenge is to write a program that solve game levels.

TODO: Actually explain how LaserTank works. There is an instructions page on the website.

Input will be an ASCII representation of the game map. TODO: determine which characters stand for what stuff.

Output will be the list of actions required. There are four possible actions for each step in the solution, "move forward," "turn left," "turn right," and "shoot".

Counting k-mers

The task is to count the number of distinct substrings of length k, for k = 1,2,3,4,.....

score

Your score is the highest k you can get to on my computer in under 1 minute.

You should use http://hgdownload.cse.ucsc.edu/goldenPath/hg38/chromosomes/chr2.fa.gz as your input and ignore new lines.

You should ignore all newlines. You can preprocess the input to decompress it before starting.

The following code outputs a histogram of all the 4-mers. You can then count how many there are with wc.

awk -v substr_length=4 '(len=length($0))>=substr_length{for (i=1; (i-substr_length)<len; i++) substrs[substr($0,i,substr_length)]++}; END{for (i in substrs) print substrs[i], i}' file.txt


(This question is not finished yet.)

• As pointed out by Geobits on chat, there's a simple approach which takes O(kn) to count distinct substrings of every length up to k. – Peter Taylor Jan 30 '15 at 20:18
• @peter But can you do faster? It might be possible to optimise in the common cases. If every k-infix is unique, then you know the number of n-infixes for every n>k. A BWT might be a viable approach as well - not sure how long that would take. – John Dvorak Jan 30 '15 at 20:49
• @PeterTaylor I was also thinking of adding a space restriction but I haven't worked out those details yet. – user9206 Jan 30 '15 at 21:18

# Elevator Control [WIP]

The controller is still a WIP, but I have a decent idea of how it'll work.

You have been hired as a Vertical Integration Specialist (programmer) at Ascension Incorporated to write advanced elevator controller software. (backstory wip)

# Elevators are Cool

The current setup is that there will be ten floors and three elevators. This is 100% subject to change. I'm not exactly sure how the game will be judged, below is an idea.

As people begin queue up, your elevators will be responsible for making sure that they get where they want to go. Each game tick, there is a certain % chance that a person will queue up at a given floor with a random destination. You goal is to transport 1000 people in the least time possible.

# Details

Your submission will be the the form of a Java class. This class must contain at least two methods: the constructor mySubmission(Elevator[] elevators, Floor[] floors) and update(Elevator[] elevators, Floor[] floors). The constructor class will be called once, and update after every game tick.

## Elevator Class:

• int location gives the current floor location of the elevator. (Read-only)
• int dest gives the destination of the elevator. All elevators have a destination, even an idle elevator, in which case the destination is the current floor. (readOnly)
• String status is idle or busy. Elevators which are idle are not moving and have no floors in queue. (read-only)
• boolean[] buttons tells which buttons have been pushed, signifying that a person in the elevator wants to go to that floor.
• ArrayList<Integer> destQueue gives the list of destinations for this elevator. An idle elevator with something in destQueue will become busy and have a new destination. (writable)
• goToFloor(int i) adds that floor to the queue if it is not already in it.
• clearQueue() clears the queue. Simple as that.

## Floor Class

• boolean waiting means that somebody is at that floor.
• boolean up means that somebody on that floor wants to go up.
• boolean down means that somebody on that floor wants to do down.

# Random distribution in array with exact number of occurences and max size

Write a program or a function, that takes 3 inputs x y z, where :

x is an integer representing the max size of each output array.
y is an integer representing the exact number of occurence of each z value.
z is a set of n integers to distribute

and outputs a set of arrays containing z values randomly distributed (each array must be unique, different ordered array are not the same).

# Rules

• Each value of z can only appear once in each output array
• x value is between 2 and 10
• y value is between 1 and 10
• n is between 2 and 50
• z's n values are between 0 and 50
• If and only if n * y isn't divisible by x you can output one array with less than x elements
• "Random" means that every possible output must be produced with finite probability (barring the finite length of the PRNG's cycle)
• You can assume valid inputs, and there will always be at least 1 possible solution

# Example

Input :

4 5 [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]


Output :

[[3 18 16 10][9 0 2 11][6 12 0 9][15 16 10 4][4 17 16 14][14 3 15 2][5 4 7 16][17 5 0 13][13 11 7 6][2 9 8 12][5 13 7 2][7 1 8 14][11 19 17 0][17 19 6 13][3 1 5 15][15 18 0 7][19 14 18 10][1 16 10 9][1 12 14 10][9 15 4 12][8 4 3 5][19 11 18 3][13 12 17 11][6 1 8 19][18 8 2 6]]


Input

4 5 [0 1 2 3 4]


Output

[[0 3 2 1][0 3 2 4][3 2 1 4][2 0 1 3][1 0 3 4][4 2 0 1][4]]


# Winning Criterion

This is code-golf so the shortest answer wins.

# Note

This is actually based on SO question that I asked, and you can find a Java implementation here : https://stackoverflow.com/questions/28544808/random-distribution-of-items-in-list-with-exact-number-of-occurences

# Sandbox

Definition of random : Should I accept output that contain same "subset" array ordered differently? Output format : How can I better define the output expected?

• I don't see why you posted this question here if you were to post it to main in an hour without any feedback. – Optimizer Feb 19 '15 at 10:09
• What next question ? The last sandbox post was 9 hours ago. That one was just lucky that the right people were awake. – Optimizer Feb 19 '15 at 10:12
• Is the choice of the word "set" deliberate? I.e. must all arrays in the output be unique? – Martin Ender Feb 19 '15 at 11:02
• As for randomness, if you want something decent you should specify that every possible output must be produced with finite probability (barring the finite length of the PRNG's cycle). – Martin Ender Feb 19 '15 at 11:02
• The rules seem to allow me to output a set of one-element arrays, reducing the problem to shuffling y copies of z. – Peter Taylor Feb 19 '15 at 12:19
• @MartinBüttner I updated my question with your suggestions. I also specified that differently ordered arrays are not considered the same. – Thrax Feb 19 '15 at 12:38
• @PeterTaylor You can only output arrays of size different than x in the case n * y is not divisible by x – Thrax Feb 19 '15 at 12:39
• You should be aware that at some point (probably already) it will be shorter to just generate random outputs and then check for validity (and regenerate as long as it isn't). – Martin Ender Feb 19 '15 at 12:50
• @MartinBüttner You provided a 8 byte CJam implementation, I find that more than satisfying. – Thrax Feb 19 '15 at 13:29
• @Thrax That isn't valid by the updated rules, as it doesn't produce every possible output and doesn't ensure uniqueness of the arrays. – Martin Ender Feb 19 '15 at 13:42
• @MartinBüttner I could put those 2 (hard) rules as bonus, maybe? – Thrax Feb 19 '15 at 13:45
• @Thrax That's up to you. I think they change the challenge quite substantially, so I'm not sure if they are suitable for being a bonus, but I don't know. – Martin Ender Feb 19 '15 at 13:46
• @MartinBüttner Java implementation (non-golfed) is 1600 bytes. I don't find that particularily excessive. With an appropriate language, it should be reduced to no more than 300 I think. – Thrax Feb 19 '15 at 13:49

# Can you reach this chess position?

This is currently a stub. If it makes sense I will write it out.

You should write a program which given a chess position outputs a list of moves (white and black alternating) with which the given position can be reached from the standard starting position. Your goal is to minimize the number of moves.

## Input details:

will be in following the format (but of course not the staring position):

rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR

• Inputs will be chosen from random positions of random low-level games (~1200 Elo).
• You only have to reach the given position with legal moves. You don't have to care if any castling or en-passant was available in the input.
• You can choose whose turn it is.

## Output details:

• Is a list of [a-f][1-8] [a-f][1-8][qrbn]? ([qrbn]? is for promotion, if there is a standard notation for it, that will be used).

## Other details:

• Running time of your program should not take more than one minute on your computer.
• Program shouldn't be longer than 50Kb. (this is against hardcoding databases thought that might wouldn't help that much)
• Standard loopholes are disallowed.

## Scoring:

• Sum of the moves (half-moves) for the 20 provided inputs. If hardcoding happens those are subject to change. If a program can't reach a given input in 1 minute it's score is 300 for that testcase.

Sandbox notes:

A validator would be useful. I can't do a JS snippet but maybe I can hack together a python3 one.

(You don't have to implement castling, en-passant, promotion if you don't want to and still can get a great entry.)

• One-minute limit? Is that for arbitrary positions? If so, beware that there are fiendish retrograde analysis problems that would stand up to search strategies. – xnor Feb 25 '15 at 1:20
• @xnor You don't have to be able to solve 100% of the positions. If you can't solve one you receive 300 points for that one. – randomra Feb 25 '15 at 3:52
• "one minute on your computer" seems to be a problem - giving an advantage to faster computers. – trichoplax Feb 25 '15 at 12:39
• I'm contemplating a challenge which will require termination within 30 seconds on any computer, but that requires the code to measure its own runtime. The actually scoring will still all be done on my machine for fairness. – trichoplax Jun 26 '15 at 23:14

# Find the Point of Maximum Light

Inspired by this program, this challenge is about finding the point where the mouse should be placed, given an input in a form which will be specified later, in order to color the most pixels yellow.

The above link will bring you to a program with a hexagon, a triangle, and a line. When the mouse is moved over the shapes, light rays shine from the mouse and the various shapes absorb the light.

Input is given in this format: [250,200,150,100 250,200,300,120 150,100,300,120] [250,350,350,250] (Compare to the lines array in the aforementioned program). Your program is to assume the perimeter ([0,0,400,0 0,0,0,400 400,0,400,400 0,400,400,400]) is always present.

This is code-golf, so the shortest code wins.

NOTE: please tell me if I can clarify my question.

• I would suggest you make the challenge self-contained... it's nice to have the link as a reference to the inspiration for your challenge, but people should be able to understand how exactly the program is supposed to work without having to follow the link. – Martin Ender Feb 28 '15 at 16:44
• on the link, where does one click in order to run the program? – feersum Feb 28 '15 at 16:44
• When the link is clicked, you should see a (mostly) black 400 by 400 square on the right. Try mousing over the square. – BobTheAwesome Feb 28 '15 at 16:45
• Since this is inspired by a mouse pointer based game, I take it the output should be integer, even if half way between two pixels would give greater coverage? – trichoplax Jun 26 '15 at 23:25
• @trichoplax Yes, the output should be an integer (or rather, two integers). – BobTheAwesome Jun 28 '15 at 12:56
• I assumed that would be the case, I was just asking so you could clarify the question by editing in a specific output format (or choice of formats). – trichoplax Jun 29 '15 at 1:44

## Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo

I'm not sure how or if this can even work in any language, but I figured I'd toss the idea up here for someone else to flesh out in case it's actually viable.

"Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo" is a grammatically correct American English sentence. This is possible because there are three different meanings of the word "buffalo" (or "Buffalo") used in the sentence, and some other words and punctuation are implied rather than explicitly included.

I think this would be a great code challenge to issue, if it is at all possible. It may not be proper for , but that would put an interesting spin on it as well.

The objective would be to create a script or program which is made up only of a single command, or sequence of commands, which is identically repeated throughout the source. No other code is permitted to fill or wrap the repeated piece. Within the script or program, those commands must do something in at least three different ways (or do three totally different somethings) despite being written exactly the same (perhaps with some allowance for deviations in capitalization, such as in the actual sentence) for every iteration.

A fictitious (and obviously invalid) PowerShell example is below.

Code:

echo 'buffalo';echo 'buffalo';echo 'buffalo';


Output

buffalo
Buffalo
BUFFALO

(Note: The Output could be easily achieved by simply modifying the capitalization of "buffalo" within the script, but that would be in violation of the spirit of the challenge - such deviations, if permitted at all, should not be allowed in string literals.)

• Have you heard of the language Ook? – Martin Ender Mar 5 '15 at 16:58

# Regex vs HTML

As the Stack Overflowers have been defeated, it is up to the Programming Puzzlers and Code Golfers to fight this final battle against the regex-resisting HTML-hordes. Pick up your flavour of choice and join the melee, with the shortest regex you can achieve (no, not like this)!

## Challenge

Write a regex which takes a html tag, and splits it into tag name, attributes and body. For example, <img src="something.jpg">caption</img> is converted to img, src="something.jpg" and caption. Your regex will be run by the controller against a list of tests. Any regex flavour can be used, as long as there is a driver available (or you want to write your own).

## Rules

• The regex should contain at least 4 groups, one each for tag name, tag attributes, tag body (contents) and a group for the html tag matched, which may be group 0 (which will not add to your regex length).
• Your regex does not need to handle all the test cases, but the more handled, the higher your score.
• The scoring formula is (100 - log(self.length) * 40) * ((passes - total) / total + 1), but this will be handled by the scoring program. This formula might change, based on how the challenge progresses. A higher score is better.
• For your regex, you must specify the driver you use (the name in square brackets), any flags and the group names or numbers that hold the split bits. Flags do not contribute towards regex length.

## Testing

• Your program will be run over 30 tests (more may be added) by the scoring program, and the number of passes counted.
• Length is in bytes.
• Your score then is (100 - log(length) * 40) * ((passes - total) / total + 1), but this will be handled by the scoring program. This formula might change, based on how the challenge progresses.
• Types of html that you can score points on (remember not all need to be handled):

• Paired html tags - <a>b</a>
• Tags with the self-closing syntax - <br/>
• Quoted attributes (using either single or double quotes) - <a href='mysite.com'>b</a>
• Unquoted attributes - <b strength=1>msg</b>
• Empty or boolean attributes - <input disabled/>
• Comments (tag name is !--, attrs is empty, body is the text of the comment) - <!-- Something important -->
• DOCTYPE sections (tag name is !DOCTYPE, body is the following text) - <!DOCTYPE html>
• CDATA sections (tags inside ignored) - <![CDATA[<br/>]]>
• Example tests (one on each line, full list of tests and answers):

<a>b</a>
<a href='mysite.com'>b</a>
<a href='mysite.com' color="blue" height=1>b</a>
<quote href="http://somewhere.com">"he said this"</quote>
<div class="quote">The answer is <div id='the-answer'>42</div></div>
f'g(<b>x</b>)g'(<b>y</b>)
<input text='Your name:' focused/>

• Answers to examples (one on each line):

Name   Attrs                                    Body                                         Matched
=================================================================================================================================================================
a                                               b                                            <a>b</a>
a      href='mysite.com'                        b                                            <a href='mysite.com'>b</a>
a      href='mysite.com' color="blue" height=1  b                                            <a href='mysite.com' color="blue" height=1>b</a>
quote  href="http://somewhere.com"              "he said this"                               <quote href="http://somewhere.com">"he said this"</quote>
div    class="quote"                            The answer is <div id='the-answer'>42</div>  <div class="quote">The answer is <div id='the-answer'>42</div></div>
b                                               x                                            <b>x</b>
input  text='Your name:' focused                                                             <input text='Your name:' focused/>

• There is a timeout for the regex matching (currently 5 seconds, but this may change depending on the number of submissions), so if you are making a bit / computationally expensive regex, use a fast driver. The tests will be run on a 2013 MacBook Air, most likely single threaded (although 4 cores are available).

## Drivers

Contributions of drivers is much appreciated. See the instructions on github.com.

## Results

Name                          Length    Score     Passes    Fails     Timeouts  Errors
==========================================================================================
Naive                         68        10.6799   12        18        0         0


## Sandbox Questions

• Is the scoring formula fair?
• Is this too easy / hard?
• Would abstracting the controller a bit more allow the controller and drivers be useful for scoring other challenges? Would anybody want to use it?
• There is currently a python and a perl driver. Are there any other major regex flavours that should be supported, or should I wait and see until after the sandbox?
• Is there any parts of the challenge that are a bit clunky and need rewriting?
• Could someone add this to the listing at the top?
• Anything I've missed?
• I think this needs the full HTML spec for what a tag can look like. Because you'd be surprised... Also, I'm not a fan of the restriction to a single regex flavour. That's like a language restriction in any other challenge, and usually not a good idea. – Martin Ender Jan 17 '15 at 15:27
• In particular (afaik) it doesn't cover the interesting ones, like recursion and balancing group. But mainly, I just think it's gonna put off people who don't know the flavour (even if it's similar to theirs), because they'll have to look it up. – Martin Ender Jan 17 '15 at 15:36
• When you say "HTML", what do you mean? IMO this would be a much more reasonable challenge if you restrict it to XHTML and thus remove the need to handle auto-closing <li>, <p>, etc. tags. I agree with @MartinBüttner that some formal spec would be useful, because although the example he links to is invalid, the fact that Optimizer got away with claiming that it was valid suggests that other people may try similar nonsense. – Peter Taylor Jan 17 '15 at 15:45
• I have nowhere in my answer mentioned that my answer is following proper HTML W3C spec. Instead, my answer was more on using the loose behavior of browsers parsing an HTML page. – Optimizer Jan 17 '15 at 17:20
• The edits still don't address the biggest problem with this question, which is a failure to state which HTML spec to follow. Adding a set of test cases doesn't really finesse that, especially since you say that you may add test cases later. – Peter Taylor Feb 27 '15 at 18:12
• @PeterTaylor Is that better? – matsjoyce Feb 28 '15 at 12:19
• The note to self indicates that you're specifically after HTML5 syntax. If you state that explicitly in the question itself then I will be perfectly satisfied. – Peter Taylor Mar 2 '15 at 12:17
• @PeterTaylor Well, it's HTML 5 syntax without the optional tags section. I listed those under the testing section. – matsjoyce Mar 2 '15 at 13:34

## Make a Space Heater

I've been out shoveling snow all day, and my hands are freezing! Heat them up with my computer.

Here's an (ungolfed) Linux C solution:

#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <sys/wait.h>
#include <sys/sysinfo.h>

int main() {
int cpu_cores = get_nprocs_conf();

for (int i = 0; i < cpu_cores; i++) {
if (fork() == 0) {
nice(19);
while (true);
}
}
while (wait(NULL) > 0);
return 0;
}


Additional Rules:

1. It must use all my CPU cores! More cores means more heat. (Processes are not required. You can use threads, or whatever. Just keep my cores pegged.)
2. Don't slow down my system. I might want to watch cat videos while my hands are warming. (The example does this with nice)
3. Shortest answer in bytes wins.
• I see a few problems with this. For one, heating up the CPU cores too high may damage your computer. Second, different computers have different CPUs, so what heats up one may not heat up another. – ASCIIThenANSI Apr 7 '15 at 13:13
• @ASCIIThenANSI Modern OSes will ease up on the CPU if it gets too hot. Also, every CPU you're likely to find in a consumer machine will get hot when it does a lot of work. Also, I may hay left this sitting here for a month. Oops. -- The idea with this challenge is to bring out languages that might not be perfectly optimized for golfing but are tightly integrated with the system. In practice, though, this would probably mean every answer would be in C, C++ or assembly. – Functino Apr 30 '15 at 21:57

# Navigate My Time Machine

This is a pretty broad idea, but time travel is a lot cooler than space travel. The basic idea is that the program will have to sort out the path of various objects through time, given certain constraints as to what must be where, when.

There are a few different models of time machine that could be used, based upon which type of time travel we want to use.

One possible example is the time travel model used in the film Primer. Notably, the machine must be turned on before it can be used. I find this model to be fairly "realistic," if that term can be used in regards to time travel.

There would also be the requirement of conservation of mass. If there there are multiple copies of an object, then "the number of forward-moving copies" - "the number of backwards-moving copies" = 1. The most important point is that there is a single "unified" timeline.

One idea is to create a long list of various objects, listing the known sightings of each one. From this list of information, the program must sort out the path of each object through time, ensuring that each duplicate object is accounted for and that conservation of mass is obeyed.

Additional ideas include determining how much additional aging each object has experienced as a result of the time travel.

# Design Logic Circuits with CSWAP Gates

A universal logic gate is a logic gate is one that is capable of creating any other logic gate or circuit. For example, it is possible to wire together dozens of NAND gates to form any logic circuit you so desire.

Beyond a universal gate, a reversible logic gate is one whose (multiple) outputs can be used to determine the input. One notable reversible universal gate is the Fredkin Gate, also known as the CSWAP gate. This gate has three inputs and three outputs, yet is very simple. CSWAP stands for "controlled swap" and describes exactly what the gate does. If the first input is a 0, the three outputs are the same as the three inputs. If the first input is a 1, the second and third outputs are swapped.

Here is the ever-so-important truth table.

in  | out
----+----
000 | 000
001 | 001
010 | 010
011 | 011
100 | 100
101 | 110
110 | 101
111 | 111


## The Challenge

You goal is to write a program that takes a truth table as input and constructs a logic circuit to match it. (other ideas are taking a non-CSWAP circuit as input and converting it to CSWAP).

Here are the rules of circuit design:

• A circuit has a certain number of inputs and outputs, the quantities of which will be given.
• You have an unlimited supply of CWAP gates with which to construct circuits.
• You also have an unlimited supply of constants (a source that always takes on the assigned value) and trash bins (a place to send an unneeded bit).
• Each data source (circuit input / gate output / constant) must be linked via wire to exactly one data sink (circuit output / gate input / trash bin), and vice-versa.
• Possible extra rule: no loops in the circuit.

## ASCII representation

Using ASCII to draw the circuits may be unnecessary, but here is how it could be done.

• Wires are - and |, which connect the two horizontally or vertically adjacent cells.

• Inputs are capital letters, while outputs are lowercase letters. Constants are 1s and 0s. Trash bins are #.

• CSWAP gates are formed by OXX in any of the four basic orientations. The O is the control, while XX are the two inputs/outputs to be swapped. I might need to adjust this so that adjacent gates with multiple orientations are unambiguous.

AND gate

A-O-#
B-X-#
0-X-a


NOT gate

A-O-#
0-X-#
1-X-a


(more details coming sometime not now)

# Game Of Riches

This is a programming challenge based off the game AdVenture Capitalist.

## Goal Of The Game

The goal is to have the most angel investors after 1 month (2,592,000 seconds) of gameplay.

## Angel Investors

Angel Investors are the primary way to increase your profit in the long run. Angel Investors can be sacrificed for Angel Upgrades. Angel Investors also increase your profit by ANGEL_EFFECTIVENESS% each. For example, 20 angel investors increase your profit by 40%. You earn Angel Investors in proportion to the square root of your life earnings. The catch is that Angel Investors can only be used after a reset.

ANGEL_EFFECTIVENESS is 2 by default. It can be increased by unlocks and upgrades.

Angel Investors are earned according to this formula: 150 * sqrt(LIFETIME_EARNINGS / 1e15)

## Money

You earn money through the use of businesses. Money is used to purchase businesses and upgrades. The more money you have earned in your lifetime (since your program started execution), the more angels flock to your cause.

## Businesses

Businesses can earn you money. There are 10 types of businesses. The price of a business increases exponentially. You can also earn unlocks by achieving certain numbers of businesses. You start with 1 lemonade stand.

Name               |    Base Price   |  Base Profit / second  | Price Increase per Purchase
-------------------------------------------------------------------------------------------
LEMONADE_STAND     |              $4 |$1.66 | 7%
NEWSPAPER_DELIVERY |             $60 |$20 | 15%
CAR_WASH           |            $720 |$90 | 14%
PIZZA_DELIVERY     |          $8,640 |$360 | 13%
DONUT_SHOP         |        $103,680 |$2,160 | 12%
SHRIMP_BOAT        |      $1,244,160 |$6,480 | 11%
HOCKEY_TEAM        |     $14,929,920 |$19,440 | 10%
MOVIE_STUDIO       |    $179,159,040 |$58,320 | 9%
BANK               |  $2,149,908,480 |$174,960 | 8%
OIL_COMPANY        | $25,798,901,760 |$804,816 | 7%


## Unlocks

Unlocks are bonuses that are earned when a set goal has been achieved.

Example list (not actual):

LEMONADE_STAND;25;LEMONADE_STAND;PROFIT;2
NEWSPAPER_STAND;900;OIL_COMPANY;PROFIT;11
ALL;2222;ALL;PROFIT;2


## Upgrades

Upgrades are bonuses that are purchased with money or angels. See Angel Upgrades for details on upgrades that are purchased with angels.

Example list (not actual):

0;CASH;2.5e5;LEMONADE_STAND;PROFIT;3
1;CASH;500000;NEWSPAPER_DELIVERY;PROFIT;3
2;CASH;1e21;ANGEL;EFFECTIVENESS;1


## Angel Upgrades

Angel Upgrades are bonuses that are purchased with the sacrifice of angels. Angels sacrificed for this purpose are not regained on reset of a game.

Example list (not actual):

3;ANGEL;10000;ALL;PROFIT;3
4;ANGEL;1e32;CAR_WASH;COUNT;100
5;ANGEL;3.4e134;ANGEL;EFFECTIVENESS;10


## Resetting

When you reset your game, you lose all unlocks, upgrades, businesses, and money that you had. You start out with 1 lemonade stand all over again. So why would you want to do that? Because all angels that you may have earned last session are now activated. The angels that you didn't spend last session are also carried over. With these angels, you can earn larger profits faster than those earned in last session.

Lifetime earnings are not reset when you reset.

The angels gained with reset is 150 * sqrt(LIFETIME_EARNINGS / 1e15) - ANGELS - ANGELS_SACRIFICED

# Bot Details

Your bot will be an independent program that sends and receives input and output through stdout, and stdin. They are allowed to write to and create files in the directory that they are in. All files that they create must be destroyed on death of the program. The program must be deterministic. If the program does not finish the game within 5 minutes, it is disqualified.

Your bot can send through stdout requests for information. Here is a list of each request along with the reply:

Request                                                                                    Reply
------------------------------------------------------------------------------------------------
TIME                                                                        game time in seconds
TIME_LEFT                                                              game time left in seconds
MONEY                                                                               cash on hand
LIFETIME_EARNINGS                                                              lifetime earnings
ANGELS                                                                             active angels
ANGELS_SACRIFICED                                       number of angels sacrificed in life-time
ANGELS_GAIN                                   number of angels that would be gained with a reset
COUNT type†                                                                       number of type
COST type†                                                                     cost of next type
PROFIT type†                                                               profit of all of type
UPGRADE or CASH_UPGRADE                                     the next cash upgrade you can afford
ANGEL_UPGRADE                                              the next angel upgrade you can afford
UPGRADES                                              the newline separated list of all upgrades
CASH_UPGRADES                                    the newline separated list of all cash upgrades
ANGEL_UPGRADES                                  the newline separated list of all angel upgrades
UPGRADE id                                                         the description of an upgrade
NEXT_UNLOCK type†                                                 the next unlock with type type
UNLOCKS                                                the newline separated list of all unlocks
UNLOCKS type†                           the newline separated list of all unlocks with type type
UNLOCK id                                                           the description of an unlock


† One of LEMONADE_STAND,NEWSPAPER_DELIVERY, CAR_WASH, PIZZA_DELIVERY, DONUT_SHOP, SHRIMP_BOAT, MOVIE_STUDIO, BANK, OIL_COMPANY, ALL

These commands return no value:

Request                                                                                                  Action
---------------------------------------------------------------------------------------------------------------
WAIT seconds                                                                              warps forward in time
WAIT_MONEY x                                                                     waits until you have x dollars
WAIT_ANGEL x                                                                      waits until you have x angels
BUY type amount                 purchases items one at a time, waiting as needed until you can afford each item
RESET                                                                                        resets the session
BUY_UPGRADE id                                                                             purchases an upgrade
If you can't afford the upgrade it will wait until you can afford it if it is a CASH upgrade or will return
immediately if it is an ANGEL upgrade


Format of an upgrade string: id;purchased[5];typeOfUpgrade[1];cost;bonus_string
Format of an unlock string: id;achieved[5];typeOfUnlock[2];amountNeeded;bonus_string
Format of a bonus string: type[3];subtype[4];amount

If subtype is PROFIT or COST, the bonus is applied multiplicatively, otherwise the bonus is applied additively.

[1]: One of CASH, ANGEL
[2]: One of LEMONADE_STAND,NEWSPAPER_DELIVERY, CAR_WASH, PIZZA_DELIVERY, DONUT_SHOP, SHRIMP_BOAT, MOVIE_STUDIO, BANK, OIL_COMPANY, ALL
[3]: One of ANGEL, LEMONADE_STAND,NEWSPAPER_DELIVERY, CAR_WASH, PIZZA_DELIVERY, DONUT_SHOP, SHRIMP_BOAT, MOVIE_STUDIO, BANK, OIL_COMPANY, ALL
[4]: EFFECTIVENESS if type is ANGEL; otherwise one of COUNT, PROFIT, COST
[5]: One of true or false

TODO

## Score:

Your score is determined as log10(ANGEL_TOTAL). The person with the largest score wins the contest.

ANGEL_TOTAL is determined by adding all active angels, sacrificed angels, and the number of angels you would gain with a reset.

## Leaderboard:

N/A

tag: code-challenge

• This is a very long post and only about 25% complete. It would really benefit from reformatting to take less space. Why not represent the companies in a table, and have parameterised commands to get the number, cost, and profits of company type X? – Peter Taylor Mar 19 '15 at 2:24
• Is the number of angels gained by a reset 150 * sqrt(lifeTimeEarnings / 1e15) or 150 * sqrt(lifeTimeEarnings / 1e15) - ANGELS - ANGELS_SACRIFICED? – Peter Taylor Mar 20 '15 at 8:39
• @PeterTaylor It's the latter :) – TheNumberOne Mar 21 '15 at 0:13

## Children Sum Game

When I was a kid I liked to play a sum game with my cousin (I don't know if there's a name for the game).

The first player choose a number between 1 to 9, then by turns players go summing a number between 1 to 9 to the result until one is able to reach 100.

So, the challenge consist in create a program to play this game. The program has to choose randomly if the human or the computer starts the game. The player should input the sum of a number between 1 to 9 and the previous result and the program should check if the sum is correct. Then the program should sum another number between 1 to 9 and give the result. Finally it should display a message.

Here's a example of the game, suppose computer starts:

Computer: 5
Player: 12
Computer: 18
Player: 25
Computer: 30
Player: 39
Computer: 42
Player: 55
Computer: Incorrect sum!
Player: 48
Computer: 57
Player: 65
Computer: 73
Player: 82
Computer: 90
Player: 92
Computer: 100
You lose!


Ideally, the program should have a strategy to make it difficult (for a kid) to win the game.

Outputs should be: You win!, You lose! and Incorrect sum!

• This is equivalent to the subtraction game, a variant of Nim. – Zgarb Mar 25 '15 at 15:58
• The correct spelling is actually "You lose", not "You loose". – ProgramFOX Mar 25 '15 at 15:59
• @ProgramFOX sorry for my bad english. – Migue Mar 25 '15 at 16:02
• @Zgarb is The 100 game, but I used to play with numbers between 1 to 9. – Migue Mar 25 '15 at 16:09
• "Ideally, the program should have a strategy to make it difficult (for a kid) to win the game." This part seems very vague and subjective. How difficult is difficult enough? Essentially, if the player starts the computer can always beat him. But that means it's not difficult, but impossible for the player to win. Likewise, if the computer starts he has no way of making it difficult for the player, because the player can always win. – Martin Ender Mar 25 '15 at 16:12
• @MartinBüttner If the computer always starts and the kid playing is learning how to sum, maybe it would be interesting to see when the kid get the strategy to win the game. – Migue Mar 25 '15 at 16:23
• @Migue That is not what your spec asks for though. – Martin Ender Mar 25 '15 at 16:27
• @MartinBüttner Yes, I know. I was just thinking how to change the question to make it some way interesting. – Migue Mar 25 '15 at 16:31

# One Code, All the Challenges

## tag: code-golf

Now, I always want to solve as many s as possible, so I thought "Why not solve them all at once?".

### Your task

Create a block of code that solves another code-golf challenge on this Stack Exchange network. You must also make it so that when it is rotated (90°, 180° or 270°) it solves a different challenge on this website. Examples of rotated code-blocks:

0°       90°      180°     270°
AB       FCA      F G       EF
CDE       DB      EDC      BD
F G      GE        BA      ACG


The code golf that you are answering must have a shortest answer > 10 score (usually bytes). It may also not be a duplicate of another challenge.
Answers do not have to have a code-gold linked to every rotations, although this helps with score.

When rotating, take the shape that the code occupies, and rotate that. Some more examples:

0°       90°   | 0°      90°
print    p     | print   hsp
r     | say~~   iar
i     | hi by    yi
n     |         b~n
t     |         y~t


This means non-rectangular code is allowed, but whitespace (like-all other characters) except newlines must stay in-tact. This means the tildes (~) must be occupied with a character to allow for the rotate.

### Scoring

Number of bytes in code * ((number of rotations that solve a challenge) * -2 + 7)
Lowest score wins.

Rotations | X
0 | Must work for at least one rotation
1 | 5
2 | 3
3 | 1
Number of bytes * X


Note
Please provide a link to each code golf question you are answering with each rotation. Also note that the questions answered must have been posted before this question, and each rotation must be in the same language. Also note if there are restrictions of source in one challenge, only the rotation that tries to solve that challenge has to comply with them.

### Python 3, 21 bytes, 2 rotations, 63 points

0 degrees: https://codegolf.stackexchange.com/questions/4/print-hello-world
180 degrees: https://codegolf.stackexchange.com/questions/3/crash-the-program
(Don't put in links in   in actual answers)

print("Hello world!")


0 degrees: prints the string 'Hello world!'
180 degrees: Crashes with a SyntaxError because of unopened close parenthesis.

• @Bigtoes That was an error. Fixed it, Thank you! – user34736 Mar 10 '15 at 17:01
• I can't figure out what you're trying to say about non-rectangular code. Maybe if you had an example which actually contained non-rectangular code it would be clearer. And I think allowing people to solve any of the 3000 existing questions is too broad. It essentially makes the spec 3000 pages long. – Peter Taylor Mar 10 '15 at 21:35
• Something tells me this question will just boil down to whoever can find the right subset of questions which work together. For example, taking the 1 byte from here sets the initial bar at 5. – Sp3000 Mar 12 '15 at 12:42

# Help the President!

## Tags: code-golf

There is an anonymous president of a country who needs your help! He wants to retain absolute control, but needs to have elections to prevent uprisings. They ask you to create a program to help them gerrymander.

These are the specifications:

### Input

(You will receive input via stdin or as a function argument)

You will be given an array of arrays of strings to represent the locations of voters (a 2D matrix), i.e:

[["Democratic", "Republican", "Republican", "Democratic"],
["Republican", "Democratic", "Democratic", "Democratic"],
["Democratic", "Republican", "Democratic", "Republican"],
["Democratic", "Republican", "Republican", "Republican"]]


Which is

[["Democratic", "Republican", "Republican", "Democratic"], ["Republican", "Democratic", "Democratic", "Democratic"], ["Democratic", "Republican", "Democratic", "Republican"], ["Democratic", "Republican", "Republican", "Republican"]]


You will also receive a party that is meant to win, like "Democratic" or "Republican". These will be in the matrix.

Thirdly, you will receive district sizes. The amount of items in the matrix will be a multiple of this. All districts must be this size.

## Output

An array of arrays of coordinates. Either the top left or the bottom left may be [0, 0] or [1, 1]. Going right increases the second number and going down / up increases / decreases the first number.

This country uses a first-past-the-post voting (Most votes win) per district (except if there is a tie, none of them win). You must split the matrix of voters into districts in such a way that the party wins as many districts as possible. A district is given by one of the arrays in the output. Districts must be contiguous, and going diagonally is not contiguous. Some visualisations by this helpful CGP Grey video on Gerrymandering and one example outputs:

f([["D", "R", "D"], ["D", "D", "R"], ["D", "D", "R"]], "D", 3)
[[[0, 0], [0, 1], [1, 0]], [[0, 2], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2]]]
# In this case, the D party wins all of the votes.
f([["D", "R", "D"], ["D", "D", "R"], ["D", "D", "R"]], "R", 3)
[[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2]]]
# R wins a third of the seats


This demographic could be visualised as

D  R  D
D  D  R
D  D  R


(Note there may be many possible "best" district boundaries. In this case, return any of them. And in a case where there are two cases that give the party the same amount in both cases, but the second case gives a smaller majority to another party, return the latter)

f([["B", "R", "B", "R", "B"], ["G", "B", "G", "R", "Y"], ["G", "R", "Y", "B", "Y"], ["B", "G", "B", "G", "Y"]], 4, "Y")
[[[0, 0], [1, 0], [1, 1], [2, 0]], [[0, 1], [0, 2], [0, 3], [0, 4]], [[1, 2], [1, 3], [1, 4], [2, 3]], [[2, 1], [3, 0], [3, 1], [3, 2]], [[2, 3], [2, 4], [3, 3], [3, 4]]]
# In this election, Y wins 2, B wins 1 and 2 are undecided


## Sandbox notes

This seems way too wordy for a problem which seems so simple. Any areas where it could be clarified to be more concise? I think it's my organisation of stuff that makes it unclear.

• Your proposal seems very similar to this earlier one. Is that intentional? Also, you should state whether the districts must have the same size. – Zgarb Mar 26 '15 at 10:23
• @Zgarb I never actually saw that. This one can be easier / harder than that one, as my one asks for the best district maps, but does not restrict perimeter. – user34736 Mar 26 '15 at 10:54

# Cooperative Tamagotchi

This is a new twist to the Tamagotchi-style ideas floating around. I also plan on creating a "no rules" version, but the cooperative version is the more complete idea at the moment.

Tamagotchi, more popularly known as StackEgg, is a game in which you nurture the growth of an adorable pet, also more popularly known as PPCG. The pet has a set of statistics which reflect the health and well-being of the pet. You also have a series of buttons. When you press a button, the pet's stats are affected. One stat receives a boost, but the other stats that did not receive a boost slowly wither away.

In the game, your goal is to work together to win a game of Tamagotchi. Each contestant program casts votes to determine which move will be played in a given game cycle. This is a competition, however, because your personal contributions are being measured. If you vote for a move, and that move wins the election, then the effect of the move will affect your score. If the action was beneficial to your pet, you gain points. If the action was detrimental to your pet, you will lose points.

I don't have a "theme" for the Tamagotchi yet. Here are some ideas for how it would work. I could alternatively wait for the source for StackEgg to be released or reverse-engineered and use those more realistic rules.

There would probably be a single game phase, probably based on the "full site" phase of StackEgg in terms of functionality. This means that there are five stacks and five "constructive" buttons.

Each stat has two numbers: the number of hearts, which is visible, and a decay counter, which is hidden. When calculating a player's positive or negative contribution, only the number of hearts is used (?).

More details coming sometime not now.

• One of the key (fun) things that StackEgg had going for it was figuring out what exactly did what. With the controller source being open (I assume), that mystery is gone. Without some big tweaks, I fear there will only be one optimum vote pattern which everyone uses. – Geobits Apr 2 '15 at 1:00
• @Bigtoes Yeah, I'm thinking about that too. Do you think adding in randomness would help? – PhiNotPi Apr 2 '15 at 1:36
• @PhiNotPi only if the randomness is at the initialization of the system, not each turn, so the bots have to figure out the best strategy, maybe? – rorlork Apr 2 '15 at 8:16
• How about completely randomly initializing the effects of each button, such as which stats are helped and hurt, and by how much? There would have to be some way to determine which settings are playable, but bots would have fun time trying to figure out causes and effects. – PhiNotPi Apr 2 '15 at 12:05
• @PhiNotPi I like the idea of randomly initializing the buttons. Also, perhaps a better way to measure the fitness of the bots would be to run the game K*N times, where N is the number of bots and K is a large constant, with a different bot missing for each of the N batches of K games. The score of a bot would be the average score of the games in which it participates. – Zgarb Apr 2 '15 at 12:48