491
\$\begingroup\$

What is the Sandbox?

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

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

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

The Sandbox works best if you sort posts by "active".

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

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

| |
\$\endgroup\$

2970 Answers 2970

1
53 54
55
56 57
99
0
\$\begingroup\$

The Great, White, North! - POSTED

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ 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"? \$\endgroup\$ – Peter Taylor Jan 8 '15 at 9:31
  • \$\begingroup\$ 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. \$\endgroup\$ – Martin Ender Jan 8 '15 at 11:35
  • \$\begingroup\$ 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). \$\endgroup\$ – Geobits Jan 12 '15 at 2:33
  • \$\begingroup\$ @PeterTaylor Been almost two weeks but I finally revamped it. Thoughts? \$\endgroup\$ – globby Jan 21 '15 at 2:41
  • \$\begingroup\$ Sorry, I was travelling. Looks like you sorted all the issues I raised, though. \$\endgroup\$ – Peter Taylor Jan 25 '15 at 23:18
0
\$\begingroup\$

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

| |
\$\endgroup\$
0
\$\begingroup\$

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

| |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor Jan 30 '15 at 20:18
  • \$\begingroup\$ @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. \$\endgroup\$ – John Dvorak Jan 30 '15 at 20:49
  • \$\begingroup\$ @PeterTaylor I was also thinking of adding a space restriction but I haven't worked out those details yet. \$\endgroup\$ – user9206 Jan 30 '15 at 21:18
0
\$\begingroup\$

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.
| |
\$\endgroup\$
0
\$\begingroup\$

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?

| |
\$\endgroup\$
  • \$\begingroup\$ I don't see why you posted this question here if you were to post it to main in an hour without any feedback. \$\endgroup\$ – Optimizer Feb 19 '15 at 10:09
  • \$\begingroup\$ What next question ? The last sandbox post was 9 hours ago. That one was just lucky that the right people were awake. \$\endgroup\$ – Optimizer Feb 19 '15 at 10:12
  • \$\begingroup\$ Is the choice of the word "set" deliberate? I.e. must all arrays in the output be unique? \$\endgroup\$ – Martin Ender Feb 19 '15 at 11:02
  • \$\begingroup\$ 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). \$\endgroup\$ – Martin Ender Feb 19 '15 at 11:02
  • \$\begingroup\$ The rules seem to allow me to output a set of one-element arrays, reducing the problem to shuffling y copies of z. \$\endgroup\$ – Peter Taylor Feb 19 '15 at 12:19
  • \$\begingroup\$ @MartinBüttner I updated my question with your suggestions. I also specified that differently ordered arrays are not considered the same. \$\endgroup\$ – Thrax Feb 19 '15 at 12:38
  • \$\begingroup\$ @PeterTaylor You can only output arrays of size different than x in the case n * y is not divisible by x \$\endgroup\$ – Thrax Feb 19 '15 at 12:39
  • \$\begingroup\$ 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). \$\endgroup\$ – Martin Ender Feb 19 '15 at 12:50
  • \$\begingroup\$ @MartinBüttner You provided a 8 byte CJam implementation, I find that more than satisfying. \$\endgroup\$ – Thrax Feb 19 '15 at 13:29
  • \$\begingroup\$ @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. \$\endgroup\$ – Martin Ender Feb 19 '15 at 13:42
  • \$\begingroup\$ @MartinBüttner I could put those 2 (hard) rules as bonus, maybe? \$\endgroup\$ – Thrax Feb 19 '15 at 13:45
  • \$\begingroup\$ @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. \$\endgroup\$ – Martin Ender Feb 19 '15 at 13:46
  • \$\begingroup\$ @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. \$\endgroup\$ – Thrax Feb 19 '15 at 13:49
0
\$\begingroup\$

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

| |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – xnor Feb 25 '15 at 1:20
  • \$\begingroup\$ @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. \$\endgroup\$ – randomra Feb 25 '15 at 3:52
  • \$\begingroup\$ "one minute on your computer" seems to be a problem - giving an advantage to faster computers. \$\endgroup\$ – trichoplax Feb 25 '15 at 12:39
  • \$\begingroup\$ 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. \$\endgroup\$ – trichoplax Jun 26 '15 at 23:14
0
\$\begingroup\$

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.

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Martin Ender Feb 28 '15 at 16:44
  • \$\begingroup\$ on the link, where does one click in order to run the program? \$\endgroup\$ – feersum Feb 28 '15 at 16:44
  • \$\begingroup\$ When the link is clicked, you should see a (mostly) black 400 by 400 square on the right. Try mousing over the square. \$\endgroup\$ – BobTheAwesome Feb 28 '15 at 16:45
  • \$\begingroup\$ 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? \$\endgroup\$ – trichoplax Jun 26 '15 at 23:25
  • \$\begingroup\$ @trichoplax Yes, the output should be an integer (or rather, two integers). \$\endgroup\$ – BobTheAwesome Jun 28 '15 at 12:56
  • \$\begingroup\$ 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). \$\endgroup\$ – trichoplax Jun 29 '15 at 1:44
0
\$\begingroup\$

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

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Have you heard of the language Ook? \$\endgroup\$ – Martin Ender Mar 5 '15 at 16:58
0
\$\begingroup\$

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         

Tags:


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?
| |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Martin Ender Jan 17 '15 at 15:27
  • \$\begingroup\$ 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. \$\endgroup\$ – Martin Ender Jan 17 '15 at 15:36
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor Jan 17 '15 at 15:45
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Optimizer Jan 17 '15 at 17:20
  • \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor Feb 27 '15 at 18:12
  • \$\begingroup\$ @PeterTaylor Is that better? \$\endgroup\$ – matsjoyce Feb 28 '15 at 12:19
  • \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor Mar 2 '15 at 12:17
  • \$\begingroup\$ @PeterTaylor Well, it's HTML 5 syntax without the optional tags section. I listed those under the testing section. \$\endgroup\$ – matsjoyce Mar 2 '15 at 13:34
0
\$\begingroup\$

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.
| |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – ASCIIThenANSI Apr 7 '15 at 13:13
  • \$\begingroup\$ @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. \$\endgroup\$ – Functino Apr 30 '15 at 21:57
0
\$\begingroup\$

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.

enter image description here

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.

| |
\$\endgroup\$
0
\$\begingroup\$

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)

| |
\$\endgroup\$
0
\$\begingroup\$

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

Controller:

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

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ 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? \$\endgroup\$ – Peter Taylor Mar 19 '15 at 2:24
  • \$\begingroup\$ Is the number of angels gained by a reset 150 * sqrt(lifeTimeEarnings / 1e15) or 150 * sqrt(lifeTimeEarnings / 1e15) - ANGELS - ANGELS_SACRIFICED? \$\endgroup\$ – Peter Taylor Mar 20 '15 at 8:39
  • \$\begingroup\$ @PeterTaylor It's the latter :) \$\endgroup\$ – TheNumberOne Mar 21 '15 at 0:13
0
\$\begingroup\$

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!

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ This is equivalent to the subtraction game, a variant of Nim. \$\endgroup\$ – Zgarb Mar 25 '15 at 15:58
  • \$\begingroup\$ The correct spelling is actually "You lose", not "You loose". \$\endgroup\$ – ProgramFOX Mar 25 '15 at 15:59
  • \$\begingroup\$ @ProgramFOX sorry for my bad english. \$\endgroup\$ – Migue Mar 25 '15 at 16:02
  • \$\begingroup\$ @Zgarb is The 100 game, but I used to play with numbers between 1 to 9. \$\endgroup\$ – Migue Mar 25 '15 at 16:09
  • 1
    \$\begingroup\$ "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. \$\endgroup\$ – Martin Ender Mar 25 '15 at 16:12
  • \$\begingroup\$ @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. \$\endgroup\$ – Migue Mar 25 '15 at 16:23
  • \$\begingroup\$ @Migue That is not what your spec asks for though. \$\endgroup\$ – Martin Ender Mar 25 '15 at 16:27
  • \$\begingroup\$ @MartinBüttner Yes, I know. I was just thinking how to change the question to make it some way interesting. \$\endgroup\$ – Migue Mar 25 '15 at 16:31
0
\$\begingroup\$

One Code, All the Challenges

This challenge has been abandoned due to poor wording. You may reclaim it if you wish without my permission.

tag:

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.

Example:

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.

| |
\$\endgroup\$
  • \$\begingroup\$ @Bigtoes That was an error. Fixed it, Thank you! \$\endgroup\$ – user34736 Mar 10 '15 at 17:01
  • \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor Mar 10 '15 at 21:35
  • \$\begingroup\$ 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. \$\endgroup\$ – Sp3000 Mar 12 '15 at 12:42
0
\$\begingroup\$

Help the President!

Tags:

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.

| |
\$\endgroup\$
  • 3
    \$\begingroup\$ Your proposal seems very similar to this earlier one. Is that intentional? Also, you should state whether the districts must have the same size. \$\endgroup\$ – Zgarb Mar 26 '15 at 10:23
  • \$\begingroup\$ @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. \$\endgroup\$ – user34736 Mar 26 '15 at 10:54
0
\$\begingroup\$

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.

| |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Geobits Apr 2 '15 at 1:00
  • \$\begingroup\$ @Bigtoes Yeah, I'm thinking about that too. Do you think adding in randomness would help? \$\endgroup\$ – PhiNotPi Apr 2 '15 at 1:36
  • \$\begingroup\$ @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? \$\endgroup\$ – rorlork Apr 2 '15 at 8:16
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ – PhiNotPi Apr 2 '15 at 12:05
  • \$\begingroup\$ @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. \$\endgroup\$ – Zgarb Apr 2 '15 at 12:48
0
\$\begingroup\$

Quine Creator

The program F is in language A. F takes a program in language B as input. Lets call this program G. F outputs a program in language B. Lets call this program O. O Takes some input and for some values it will be a quine and for others it will run G.

The exact values which O decides behaviour must be the same for each different input to F but you can decide what the conditions will be. They must be short (5 or less bytes), reasonable and not turned into code and executed for the sake of a shorter program F. Acceptable behaviours include (but are not limited to):

  • Quines for even digit, G for odd
  • Quines for truthy input, G for anything else
  • Quines for the input "0", G for anything else

For example your program F could be written in Java and take a Python program (G) as input and output a program in Python (O) that runs G when given at least 1 arg and prints it's source when not given any args.

Sorry if this is a bit confusing

| |
\$\endgroup\$
  • \$\begingroup\$ This is very similar to this challenge. I'd definitely be tempted to close this as a duplicate. You're also missing a winning criterion. \$\endgroup\$ – Martin Ender Apr 3 '15 at 9:53
  • \$\begingroup\$ The code challenge tag is for when you make up your own winning criterion, so it would contradict the code golf tag. You might want to include a short sentence like "This is code golf, so the shortest submission (in bytes) wins." anyway, although the tag is pretty clear. Just for completeness's sake. \$\endgroup\$ – Martin Ender Apr 3 '15 at 12:22
  • \$\begingroup\$ @MartinBüttner That challenge is different to this one but I'm new to asking questions, so you be the judge of if mine should go ahead. \$\endgroup\$ – HEGX64 Apr 3 '15 at 12:32
  • \$\begingroup\$ Yes, it is certainly different, but very similar I think. For the record, my CJam submission would be "{q{;"q'}"_~"`"?}_~" which may look quite different but is essentially the same idea. I guess I probably wouldn't vote to close as duplicate myself, because I've got a dupehammer on the code golf tag, but I'm just saying others might think it's a dupe and close it. (Just to be clear, this is not a bad challenge idea. I really quite like it... just saying something very similar has been done before.) \$\endgroup\$ – Martin Ender Apr 3 '15 at 12:43
  • \$\begingroup\$ One thing that's not entirely clear about the challenge is how general G is allowed to be. E.g. if O reads all of STDIN to decide whether to use G or print O, then G cannot receive any input on STDIN. Is this fine? \$\endgroup\$ – Martin Ender Apr 3 '15 at 12:47
  • \$\begingroup\$ Is your edit intended to address my comment? If so, let me try to rephrase my question. I was asking whether G must potentially be completely general. E.g. the program G could be a program which reads a string on STDIN and reverses it. But if I generate O such that it reads all of STDIN and is a quine if STDIN is empty and calls G otherwise... then O has already read all of STDIN and G will have nothing to read on STDIN to reverse. Would this be allowed or does G have to be completely general? \$\endgroup\$ – Martin Ender Apr 3 '15 at 16:04
  • \$\begingroup\$ In other words can the input method of O be destructive? Another example would be clearing the ARGV array to determine which code to execute - if I did this, then G could never use ARGV itself. \$\endgroup\$ – Martin Ender Apr 3 '15 at 16:05
  • \$\begingroup\$ @MartinBüttner you can try to rephrase the question if you like. O should not consume too much input and I also think that G should be able to receive any input possible. So O taking the first arg and giving the rest to G or taking the first 4 bytes of STDIN would be fine. And yes the edit was sort of made in response to you comment so feel free to make an edit. \$\endgroup\$ – HEGX64 Apr 4 '15 at 3:32
0
\$\begingroup\$

Find sequences in RSA_1024

I found an interesting way to factor numbers, while its far from been any efficient in compare to other known methods, its lots of fun!

Lets assume we want to factor N. X will be its factor, if and only if

N/X = floor(N/X)

So theoretically, if you could find a different representation of floor(N/X), you could easily find X, so while find such representation is unlikely it is very easy to find it within a small range, for example take a look at floor(N/X) of N = 691 ∗ 983 = 679253

At left is X at right is floor(N/X) - floor(N/(X+1))

512 2 
513 3 
514 3 
515 2 
516 3 
517 2 
518 3 
519 2 
520 3 
521 2 
522 3 
523 2 
524 3 
525 2 
526 3 
527 2 
528 2 
529 3 
530 2 
531 3 
532 2 
533 2 
534 3 
535 2 
536 3 
537 2 
538 2 
539 3 
540 2 
541 2 
542 3 
543 2 
544 2 
545 2 
546 3 
547 2 
548 2 
549 2 
550 3 
551 2 
552 2 
553 2 
554 3 
555 2 
556 2 
557 2 
558 2 
559 3 
560 2 
561 2 
562 2 
563 2 
564 2 
565 2 
566 3 
567 2 
568 2 
569 2 
570 2 
571 2 
572 2 
573 2 
574 2 
575 2 
576 2 
577 2 
578 2 
579 2 
580 2 
581 2 
582 2 
583 2 
584 2 
585 2 
586 2 
587 2 
588 2 
589 2 
590 2 
591 2 
592 2 
593 2 
594 2 
595 2 
596 2 
597 2 
598 2 
599 1 
600 2 
601 2 
602 2 
603 2 
604 2 
605 2 
606 1 
607 2 
608 2 
609 2 
610 2 
611 2 
612 1 
613 2 
614 2 
615 2 
616 2 
617 1 
618 2 
619 2 
620 2 
621 1 
622 2 
623 2 
624 2 
625 1 
626 2 
627 2 
628 2 
629 1 
630 2 
631 2 
632 1 
633 2 
634 2 
635 1 
636 2 
637 2 
638 2 
639 1 
640 2 
641 1 
642 2 
643 2 
644 1 
645 2 
646 2 
647 1 
648 2 
649 1 
650 2 
651 2 
652 1 
653 2 
654 1 
655 2 
656 2 
657 1 
658 2 
659 1 
660 2 
661 1 
662 2 
663 2 
664 1 
665 2 
666 1 
667 2 
668 1 
669 2 
670 1 
671 2 
672 1 
673 2 
674 1 
675 2 
676 1 
677 2 
678 1 
679 2 
680 1 
681 2 
682 1 
683 1 
684 2 
685 1 
686 2 
687 1 
688 2 
689 1 
690 1 
691 2 
692 1 
693 2 
694 1 
695 2 
696 1 
697 1 
698 2 
699 1 
700 2 
701 1 
702 1 
703 2 
704 1 
705 1 
706 2 
707 1 
708 1 
709 2 
710 1 
711 1 
712 2 
713 1 
714 1 
715 2 
716 1 
717 1 
718 2 
719 1 
720 1 
721 2 
722 1 
723 1 
724 2 
725 1 
726 1 
727 1 
728 2 
729 1 
730 1 
731 2 
732 1 
733 1 
734 1 
735 2 
736 1 
737 1 
738 1 
739 2 
740 1 
741 1 
742 1 
743 2 
744 1 
745 1 
746 1 
747 1 
748 2 
749 1 
750 1 
751 1 
752 1 
753 2 
754 1 
755 1 
756 1 
757 1 
758 2 
759 1 
760 1 
761 1 
762 1 
763 1 
764 2 
765 1 
766 1 
767 1 
768 1 
769 1 
770 1 
771 2 
772 1 
773 1 
774 1 
775 1 
776 1 
777 1 
778 2 
779 1 
780 1 
781 1 
782 1 
783 1 
784 1 
785 1 
786 1 
787 2 
788 1 
789 1 
790 1 
791 1 
792 1 
793 1 
794 1 
795 1 
796 1 
797 1 
798 1 
799 1 
800 1 
801 2 
802 1 
803 1 
804 1 
805 1    
806 1 
807 1 
808 1 
809 1 
810 1 
811 1 
812 1 
813 1 
814 1 
815 1 
816 1 
817 1 
818 1 
819 1 
820 1 
821 1 
822 1 
823 1 

Its easy to tell that in the range of 566,599 floor(N/X) act like a strait line y = 2x + 566. Also it's easy to verify as we can calculate the difference between floor(N/566) and floor(N/599) and see if its equal to 2 * 599 - 566, and indeed it is.

So now lets play

Input

Your input is the number RSA_1024, while we will only use this input, your app should be able to work with any other inputs as well.

Output

10,000 sequences that you found starting from Sqr(RSA_1024) and going up. Each sequences will be outputted in a new line. For each sequences you should output the next

  • starting range value
  • end range value
  • type

Type is just a string defined by you that tells us what kind of sequence is it, strait-line or some thing else.

After you output the sequences, output one line with the total range you been able to cover with all the sequences.

Criteria

Who covers the biggest Range wins.

| |
\$\endgroup\$
0
\$\begingroup\$

Realistic Fractal Terrain Generation

Don't you find that typical algorithms to generate random fractal terrains are boring and not too much realistic?

Fractal terrain generation is usually implemented with some random noise function applied in a fractal way. This can be seen with the typical Diamond-Square algorithm or the Perlin Noise function:

Diamond-Squares example output:

Diamond-Squares example output

Perlin noise example output:

Perlin noise example output

The problem is that these are used by their simplicity in creating them, but they are actually pretty boring when they are used as height maps:

Diamond-Squares as heigh-map

Perlin noise as heigh-map

... To be continued ...

| |
\$\endgroup\$
  • \$\begingroup\$ Terrain generation is interesting. I'd like to see this idea developed. Here is a simple, but pretty good, terrain generator, if you are looking for examples: Realistic Terrain Generation in 130 Lines. \$\endgroup\$ – PhiNotPi Apr 5 '15 at 1:47
0
\$\begingroup\$

Make a fighter, then have them battle

Well, I was browsing around KOTH one day. I found two little interesting challenges: Save the last bullet for yourself and Codémon, I choose you!. But what if we combined the two?

How your bot will work

Each match, your bot is assigned an opponent. It is randomly decided who goes first. Your bot is given HP of 100. You must output:
ATKID DEFID MOVED ATKDIR DEFDIR
ATKID is the attack's ID, and DEFID is the defense (or support) ID, for skills. MOVED is your move direction, on a number-pad (5 being 'stay still'). ATKDIR and DEFDIR are attack and defense skill directions (for Bullet, Wall, etc.)
Your bot must accept the following as input:
MYHP YOURHP MYPOS YOURPOS (additional projectile positions)

Your bot is allowed 2 attack and 2 defense skills.
List of attack skills:

0: Attack: Deal 10 damage.
1: Psychic Blast: Deal 5 damage this turn and 5 damage the next.
2: Bullet: Fire off a bullet that damages for 15 points when it hits an enemy.
3: Hadouken: Fire of a large flaming ball that can fly for 3 squares, and deals 50 damage.

List of defense skills:

0: Block: Block up to 10 points of damage this turn.
1: Heal: Heal for 10 points.
2: Wall: Add a wall in target direction.

How the arena works

The arena starts as follows:

==========
|        |
|        | 
|a      b|
|        |
|        |
==========

where a and b are bots' starting positions.

Meta Questions

  • What should I add as skills? Healing? Defensive?
  • Is the arena too small?
  • Have I left out any restrictions?
  • Can I have some help with the 2D grid?
  • Is the input/output sufficient?
  • Does anyone want to pick up this challenge? I already have another KOTH, this was just an idea everyone liked.
| |
\$\endgroup\$
0
\$\begingroup\$

Missing distance between points

There are N points on a straight line. Someone calculates all possible distances between each pair of points and sort them.

In the following example I used 5 points. The sorted list of distances is [2, 5, 6, 8, 9, 14, 15, 17, 20, 22].

---X--X------X---------X-----X---

   |-2|---6--|----9----|--5--|
   |-----8---|-------14------|
      |--------15------|
   |---------17--------|
      |----------20----------|
   |----------22-------------|

You will receive the list, but one of the numbers is unreadable. This will be indicated by a zero. So you might receive the list [2, 5, 6, 8, 9, 0, 15, 17, 20, 22]. Your job is to find the missing number.

Input / Output:

Write a function/program that finds the missing number. The input (via STDIN, command-line argument, prompt or function argument) format is a list or an array of distances (integers). You can optionally take the number of points (one integer) as a second parameter if you want. The output (via return value or STDOUT) is one single integer, namely the missing number in the distances list.

This is code-golf. Therefore the shortest code wins.

Test cases:

#points, distances -> output
5, [2, 5, 6, 8, 9, 0, 15, 17, 20, 22] -> 14
3, [1, 0, 2, 2, 3, 4] -> 2
...

Sandbox notes:

  • This challenge is based on one problem of this year's Mathematical Kangaroo. My dad is a math teacher and brought me a copy of the 7.-8. grades test.

  • Example and test cases don't look pretty and will be improved and extended for the final question on PPCG.

  • My main concern about the challenge is the speed of the programs. My first (and only) solution is quite slow, because of the bad time complexity (about (n^2)^(n-1), where n is the number of points on the line). The 5-point example takes already about 1 second to compute, a 6-point example took about 10 minutes. My guess is, that most code-golf solutions will use a similar approach and the programs may be quite difficult to test.

    There's definitely a better way of computing the missing number.

    Maybe I'll add a few big testcases (one with 6, 7, 8, 9 and 10 points) and promise a 50% bonus if the program can solve all test-cases in under one minute.

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ Are you sure the solution is unique? \$\endgroup\$ – xnor Apr 7 '15 at 23:25
0
\$\begingroup\$

Shadows to Height Maps

The goal of this code challenge will be to take a grayscale image with shading as input and produce a height-map image with the same dimensions as output.

The input image will be a grayscale 256x256 png image, shaded with only a diffuse term, no ambient or specular term. It will be lit by a directional light source hitting the surface at a 45 degree angle, from above.

The output must be a 256x256 png image containing the height-map.

This is a code-challenge, the answer with the most accurate results wins. (A perfect match between the reverse engineered height-map and the original height-map used to produce the shaded image is near impossible, it is not expected that they are identical).

(working on test cases)

tags:

image-processing, code-challenge, graphical-output, conversion

| |
\$\endgroup\$
0
\$\begingroup\$

SVG file optimization

Yep, I got my idea off of this question, and it's amazing answer. All credit for this question goes to Illmari Karonen's answer

Now, for the challenge: Write a program that removes unnecessary clutter from SVG files in order to reduce their byte counts.

  1. Remove comments <!-- comment -->
  2. remove metadata <metadata ...> </metadata>
  3. Shorten necessary ids to 1 letter, and remove unused ids.
  4. remove unnecessary attributes and XML namespace attributes

Any other methods used to shorten the SVG files are welcome. (You can refer to the linked answer to look at an extensive list of ways to shorten SVG files)

Your program's score is how many bytes it removes from these SVG files:

test cases in progress

| |
\$\endgroup\$
  • \$\begingroup\$ See also Warm Welcome Secret Hat. If you're going to allow changing the paths, you should specify permitted changes / accuracy. E.g. if a transform is given to 3d.p. and the path coordinates to 3d.p., inlining the transform and then rounding to 3d.p. could produce visually perceptible changes. \$\endgroup\$ – Peter Taylor Apr 14 '15 at 9:47
0
\$\begingroup\$

Randomly generated "Bézier petals"

Introduction

A "bézier petal" is a:

  • simple closed curve (no loops or self-intersection)
  • made by two cubic Bézier curves which
    • share endpoints
    • but not necessarily control points

Challenge

The challenge is to generate these randomly, such that:

  • the entire space of possible valid curves is covered,
  • any specific valid curve is as likely as any other,
  • no "degenerate" (non-simple) petals are output.

Background

I've been thinking about this for a while (see https://www.youtube.com/watch?v=TJdApKcAVD0), but was only able to arrive at a partial solution, which only covers a "safe" subset of possibilities (it never generates crescent or s-shapes). But, having followed this site for a while, I know that many of you are way more clever than I am.

Output

The result should be a function which returns a single random petal, defined by two endpoints and two sets of two control points (six values in all) on a Cartesian plane — let's say with values between -1 and 1.

Notes

Ideally, the algorithm works in constant time, or at least has a bounded stop; generating and filtering out degenerate petals until a good one is found is acceptable but a step down.

Entries which do not cover the entire possible space but do so with low complexity and at least beat out my "sort radially around center" approach are partial credit.

Sandbox notes

I'll add some illustrations for valid and invalid petals, once I draw them.

| |
\$\endgroup\$
  • \$\begingroup\$ Are you sure "any specific valid curve is as likely as any other" is well-defined? \$\endgroup\$ – feersum Apr 22 '15 at 22:20
0
\$\begingroup\$

Minimal convex partition (code-golf)

The goal of this challenge is dividing up the 'white' shape of a given 'black and white' pixel image into smaller pieces, which together form the original image (let's call this a partition). The restriction is that those pieces have to be convex, in our case everything is made up from square pixels, therefore the convex pieces can only be rectangles. Now of course you can just divide the whole shape up into the pixels it consists of, but that way you will get too many pieces (usually). The goal here is finding one partition that has the lowest number of (convex) pieces.

Specs

Input

The 'black and white' pixel image of $n \times m$ pixels is given as a string, row by row, each row separated by a comma. The white pixels are represented by a full stop ., and the black pixels are represented by a hash mark #.

Output

The output consists of the same string, but now the white pixels must be replaced by alphabetic characters, one character for each piece of the partition. The minimal number of partition never exceeds 26 (you do not have to consider input that does not meed this condition), therefore you only have to use the letters a-z. If the minimal number is $n$, you have to use the first $n$ letters of the alphabet. Of course, the output is not necessarily unique.

Examples (without the commas, for better visibility):

n=2:
Input: 
#.
..
Ouptut:
#A
BB

n=4
Input:
....
..#.
....
Output:
AABB
AA#C
DDDD

n=6
Input:
.....
.#...
.....
...#.
.....

META:

I'd be happy for any interesting input examples. I could not think of any really interesting ones right away now.

| |
\$\endgroup\$
  • \$\begingroup\$ Very similar: codegolf.stackexchange.com/q/44654/14215 The output might not be minimal in some cases, though. \$\endgroup\$ – Geobits Apr 20 '15 at 16:26
  • \$\begingroup\$ Thanks for pointing this out, I did not remember this challenge but it is indeed similar, but I still think looking for the solution with the minimal numbers of rectangles is again a different challenge, don't you agree? But I just noticed that I could write the introduction way more intuitive by using covering a region with rectangles instead of *partitioning into convex pieces*=) \$\endgroup\$ – flawr Apr 20 '15 at 19:28
0
\$\begingroup\$

IRC reader

Internet Relay Chat (or IRC for short) is a simple yet popular chat communication method. The challenge is to create a program that can take an IRC server from program arguments and print out new messages sent on that server.

e.g.: <your_irc_client> irc.freenode.net

A very simple implementation in Python of this idea which does not print responses to the user can be found here

| |
\$\endgroup\$
0
\$\begingroup\$

Interpret a Turing-Complete Language

This challenge is inspired by this esolangs.org page, which lists some languages with very small interpreters. There have been some similar challenges before, like this one about a self-interpreter, or a few other interpreter challenges, like one for BF.

This goal of this challenge is to write the smallest interpreter possible for a Turing-complete language. You may choose any Turing complete language (even one you create?) to interpret.

Your interpreter should take input representing the program to be executed, and give output representing the end result of the program. "Interactive" I/O is not required.

More Rules

Your interpreter program may not contain/execute any eval-like commands.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Maybe this could be a popularity contest, and whoever has the most creative answer wins? \$\endgroup\$ – ASCIIThenANSI Apr 20 '15 at 21:18
  • \$\begingroup\$ I like this, but I think it needs to be more specific. Why not pick a specific OISC? That would probably be the winning strategy for the more general problem anyway. Also, I/O format should either be locked down or explicitly left open. If I'm golfing an OISC in Python 2, for example, I'd like to have the I/O be the memory of the machine represented as a Python list, read via input(). Is that okay, or cheating? \$\endgroup\$ – DLosc May 4 '15 at 4:06
  • \$\begingroup\$ @ASCIIThenANSI For the popularity-contest version, see this question. \$\endgroup\$ – DLosc May 4 '15 at 4:07
0
\$\begingroup\$

Number of ways to sum [1..n] with [n+1..2n] such that each sum is prime

In as few bytes as possible, write a program or function which produces this sequence (A070897), either as an infinite list on STDOUT, or in your interpreter of choice.

Example

a(5)=2 because there are two ways: 1+10,2+9,3+8,4+7,5+6 and 1+6,2+9,3+10,4+7,5+8

Rules

No built-in primality tests. No lookup table ;). No standard loopholes.

| |
\$\endgroup\$
  • \$\begingroup\$ Are build-in prime functions allowed? \$\endgroup\$ – Jakube Apr 22 '15 at 21:13
  • \$\begingroup\$ Fixed //char count \$\endgroup\$ – alexander-brett Apr 22 '15 at 21:16
  • \$\begingroup\$ It would be good to actually define the sequence explicitly in the question body instead of just in the title and by linking to OEIS (the link is still good for further reference, but it shouldn't be necessary to understand the question). Likewise, if you could reproduce the first 20 or so elements as test cases, that would be good to make the challenge self-contained. It's also not clear if "produce this sequence" means to print consecutive number ad infinitum, or given n to return a(n) or to return all numbers from a(1) to a(n). \$\endgroup\$ – Martin Ender Apr 24 '15 at 12:42
  • \$\begingroup\$ @MB - I'll amend to repeat the title & give more examples. However I think 'an infinite list on stdout' is pretty clear? \$\endgroup\$ – alexander-brett Apr 24 '15 at 12:44
0
\$\begingroup\$

Rabbit in a Snow Storm

Scenario

A group member is giving a presentation in PowerPoint. He reaches a point where he wants to start writing on the whiteboard, but his slides have text that get in the way. He motions to the guy with the keyboard to just blank the screen so he can write. The next 2 minutes consist of everyone in the room bickering about how to do it until we arrive on using a full-screen-ish terminal (which is black, so we have to turn up the lights). Awful.

Objective

Have the primary monitor become completely white.

Rules

  • You start with no programs running (or at least none that are important towards the goal)
  • You may only use programs that are installed by default on your OS/distro (i.e. needs to be repeatable by someone else without installing anything in particular)
  • You can't pre-load your background, slide-show, etc. with a pure-white image (though you could create the image then show it)

Scoring

  • Number of keystrokes required (keys depressed and released, i.e. opening Spotlight takes two (Command + Space), likewise Run... (Win + R))
  • Clicks are scored as 5 keystrokes.
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ In your scenario, PowerPoint is running. Yet in the rules, it isn't. I can understand if this is because the one-stroke solution w isn't interesting, but it still makes for a confusing question. Why not ditch PowerPoint from the scenario and replace it with a demo of some in-house software? \$\endgroup\$ – Peter Taylor Apr 23 '15 at 8:49
  • 1
    \$\begingroup\$ Oh, and you should probably add to the bit about "installed by default" that the OS hasn't learnt which programs you use, so you should assume that no auto-completion occurs. \$\endgroup\$ – Peter Taylor Apr 23 '15 at 8:50
  • \$\begingroup\$ @PeterTaylor I didn't know about w...magical! In the scenario the guy was actually using PDF slides, so I'm not sure if Reader has the same functionality. Good comment though, probably just forbid autocompleting? \$\endgroup\$ – Nick T Apr 23 '15 at 16:11
1
53 54
55
56 57
99

You must log in to answer this question.

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