464
\$\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\$
  • \$\begingroup\$ How are tags added to questions? \$\endgroup\$ – guest271314 Jan 9 '19 at 7:51
  • \$\begingroup\$ @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] \$\endgroup\$ – DJMcMayhem Aug 29 '19 at 15:19
  • \$\begingroup\$ Why no featured anymore? Can't we have it auto-added or something? \$\endgroup\$ – S.S. Anne Sep 26 '19 at 15:57
  • 1
    \$\begingroup\$ @JL2210 We now have a permanent info box that links to the Sandbox, so the featured tag isn't necessary \$\endgroup\$ – caird coinheringaahing Sep 29 '19 at 13:43
  • \$\begingroup\$ $y=mx+c+abcdef$ \$\endgroup\$ – Rebecca J. Stones Jan 4 at 3:14

2661 Answers 2661

2
\$\begingroup\$

Rendezvous palace

Introduction

This comes from a well-liked question on the Math SE by RobAu and a more specific follow-up to that by Danikov.

There is a palace which is a grid of n × n rooms, which we will index using two coordinates 0 ≤ x,y < n. The rooms are organized in a torus topology, i.e. with wrap-around at the edges. So the room to the right of (n-1,3) is (0,3) again, and likewise for the y direction.

Two robots are placed into this grid, and their objective is to rendezvous. But the problem is that these only can can keep track of relative changes in position and orientation. So each robot has its own local coordinate system, where its initial position is called (0,0), but these two coordinate systems relate to one another in any of 4n2 possible ways, accounting for 4 possible relative rotations and n × n relative shifts. Each of these relations has equal probability.

The palace has no doors. The robots can move around the palace by teleportation. They move in a synchronized way, teleporting at exactly the same instant. To meet they either have to be in the same room at the same time, or to swap places during teleportation.

Challenge

Your task is to write a program for these robots, trying to minimize the expected time till rendezvous. The same program will be executed for both robots, and the robots have no way to distinguish which one is which. So we'll be executing two copies of your code in parallel.

Input

The only input is n, the size of the palace. In addition to that, the code has access to a random number generator, and the random numbers from one instance are assumed to be independent from those in the other instance. No other input or communication between the instances is allowed.

Output

The output of your code should be an infinite sequence of coordinate pairs, (x,y), indicating the target room for the next teleportation. The coordinates are relative to where the robot started, not relative to where he currently is located. Giving the same output repeatedly means you are staying put in a given room.

Framework

You are asked to evaluate your code yourself. Write or copy a framework which will randomly choose relative starting positions, execute two instances of your code in parallel, detect a successful rendezvous and report the time to rendezvous. Run that code a number of times, and compute the average and standard deviation of the time to rendezvous. See the section below for ready-to-copy code.

Submission

Your answer must include the code which constitutes the program for one robot. It must also include the average time to rendezvous and its standard deviation for the following setups:

  1. at least 1,000,000 runs for n = 2
  2. at least 100,000 runs for n = 64
  3. at least 10,000 runs for n = 256

You don't have to paste your framework by default, but be willing to provide it upon request. An explanation of what your code is doing and why you wrote it that way might bring upvotes.

Scoring

The title of best answer will go to the code with the minimal expected time to rendezvous for n = 64. I'll re-evaluate the top contenders myself, to make sure you included genuine results. The closer two competitors are, the more often I'll run their code to establish a reliable expected value from the average. This is an open-ended contest, so the title may be re-awarded when a better answer comes along.

Example frameworks

C++

You can use the following fixture if you like.

#include <random>
#include <iostream>
#include <iomanip>
#include <cmath>

constexpr int n = 64;
const int orientations[4][4] = {
  {1, 0, 0, 1},
  {0, 1, n - 1, 0},
  {n - 1, 0, 0, n - 1},
  {0, n - 1, 1, 0}
};

std::default_random_engine randEngine((std::random_device())());
std::uniform_int_distribution<int> randDist{0, n - 1};
std::uniform_int_distribution<int> randDist4{0, 3};
int rand() { return randDist(randEngine); }

typedef std::pair<int, int> pos_t;

class Robot {
public:
  pos_t next() { return {rand(), rand()}; }
};

class Transform {
  int dx, dy, ori;
public:
  Transform() : dx{rand()}, dy{rand()}, ori{randDist4(randEngine)} { }
  pos_t operator()(const pos_t& in) const {
    int x = in.first, y = in.second;
    const int *o = orientations[ori];
    return { (o[0] * x + o[1] * y + dx) % n, (o[2] * x + o[3] * y + dy) % n };
  }
};

unsigned long run() {
  Transform tr;
  pos_t p1{0, 0}, p2{0, 0};
  p2 = tr(p2);
  Robot r1, r2;
  unsigned long t = 0;
  while (p1 != p2) {
    ++t;
    pos_t q1 = r1.next();
    pos_t q2 = tr(r2.next());
    if (p1 == q2 && p2 == q1) break;
    p1 = q1;
    p2 = q2;
  }
  // std::cout << std::setw(8) << t << "\n";
  return t;
}

int main(int argc, char** argv) {
  double sum = 0, sumSq = 0;
  int report = 10;
  for (int i = 1; ; ++i) {
    double r = run();
    sum += r;
    sumSq += r*r;
    if (i == report) {
      double avg = sum / i;
      double var = (sumSq - sum*avg) / (i - 1);
      double sd = std::sqrt(var);
      std::cout << std::setw(8) << i << " runs: Expected: "
                << std::fixed << std::setprecision(2) << avg
                << ", SD: "
                << std::fixed << std::setprecision(2) << sd
                << std::endl;
      report *= 10;
    }
  }
}

In a submission you'd just paste the next function. A possible statistical report for the above could read:

n = 2: Expected 2.40, SD 2.68 in 10,000,000 runs
n = 64: Expected 4105.08, SD 4104.22 in 10,000,000 runs
n = 256: Expected 64911.36, SD: 65204.72 in 10,000 runs

Python, …

To be extended for other languages. Feel free to donate your own framework if you feel like it.

\$\endgroup\$
2
\$\begingroup\$

A Continuously Running KOTH, or "An MMO with all AIs"

This was an idea discussed in chat, I'm throwing a sandbox post together because I thought it would be really fun to do.

The main idea is that the KOTH is hosted an an external website, where the competitions is continuously running. When a person submits an answer, that player's pixels (or whatever they're called) will be spawned in the game world. Over time, build a larger army of themselves.

Basically, it's an MMO with all AIs.

As of right now, I don't have the capability to host a website for this. I think someone (Optimizer?) said that they had a website. Regardless, we probably don't have to worry about that until we figure out what the rules are going to be.

Some ideas

  • The world is a large array of randomly generated pixels. Every submission has a unique color. As pixels travel around, they can encounter other pixels of the same color, which then activate and join them.
  • A more Minecraft-y options involve more detailed resource gathering / crafting. Con: the complexity can get pretty hard for contestants.
  • A space theme can involve a randomly generated galaxy, which players can travel across. They can then colonize planets and build an empire. (Maybe resembling EVE Online?)
  • Some recommendations for ideas are Clash of Clans and Globulation 2, although I've never played either.
  • Maybe each player controls an adventure in a super-simplified Dwarf Fortress-style world.

You are free to edit this post to add ideas.

\$\endgroup\$
  • 1
    \$\begingroup\$ Sounds really interesting! But I think the backend of this can get really complicated... \$\endgroup\$ – rorlork Apr 6 '15 at 22:16
  • \$\begingroup\$ Would it be possible for a player to die out completely, so that the answer is permanently out of the competition? Is there some way that this could be prevented so every answer is represented, even if only by a very small number of pixels/creatures/... \$\endgroup\$ – trichoplax Apr 7 '15 at 21:33
  • \$\begingroup\$ Respawning with a single individual would be one way. \$\endgroup\$ – trichoplax Apr 7 '15 at 21:35
  • \$\begingroup\$ Alternatively each individual could have resilience inversely proportional to the number of individuals the player currently controls. So as the individuals reduce in number they get stronger, preventing the final individual from ever being killed. \$\endgroup\$ – trichoplax Apr 7 '15 at 21:36
  • \$\begingroup\$ @trichoplax None of the specifics have really been thought through yet, but I think it would make sense to say that, upon death, players lose resources, but can't go below what they started the game with. \$\endgroup\$ – PhiNotPi Apr 7 '15 at 21:37
  • \$\begingroup\$ How about a text-based map, similar to the ones used in Roguelikes? Players build walls with their player color (| and =), with doors (+), tripwires (>-----<), mines (*), and guards (&). Weapons and armor ([ and ]) modify stats, like +2 to attack, potions (!) give buffs/debuffs, and various miscellaneous items (") are found randomly. Maybe a shop, where you use collected gold ($)? \$\endgroup\$ – ASCIIThenANSI Apr 8 '15 at 1:30
  • \$\begingroup\$ How would this be able to have a winning condition? \$\endgroup\$ – Peter Taylor Apr 14 '15 at 9:50
  • \$\begingroup\$ Bump. Now that there's a KOTH server, you may wish to visit this idea with more attention. \$\endgroup\$ – mbomb007 Nov 3 '15 at 15:43
2
\$\begingroup\$

Roguelike to Text Adventure Converter

Note: this challenge is a popularity contest for autogenerated interactive fiction. As such, the best way of judging answers is by playing them! It would threrefore be best for solutions to provide a link to a playable version online. Failing that a 'walkthrough'-style excerpt is fine, but not as fun.

Meta-comment: As you can see, I've changed this from a code golf challenge to a more creative popularity contest. Comments welcome!

Background

Roguelikes are a type of RPG characterized by by procedural level generation, turn-based gameplay, tile-based graphics and permadeath. Levels typically consisted of rooms connected by corridors. Early roguelikes, including Rogue itself, would use ASCII characters to represent the top-down view of each level.

Text adventures are a type of adventure game where the interface is text-only: the player uses text input to control the game and the game state is relayed back via text output. Like roguelikes, layouts typically consisted of interconnected rooms, with movement controlled either by specifying the room name or by giving a compass direction.

This challenge involves writing a program to automatically convert an ASCII representation of a roguelike level into a playable text adventure. The format of supported input levels is given below, as are some minimum features that must be supported by the output game. Beyond that, there is scope for as much or as little creativity you desire!

Input maps

The input of the program is an ASCII representation of a roguelike level, passed in via STDIN, command-line argument, function argument or in a file. Here is a small example:

        --------                
        |..=...+#######                                                                          
        |......|      #                                                                          
        --+-----    --+-------                                                                   
         ##         |...//...|                                                                   
       ###  ########+........|                                                                   
 ------+----+-      -----+----                                                                   
 |..%........|           #                                                                       
 |......!....|   ---     #                                                                       
 |..@........+###+.+######                                                                       
 |...........|   ---                                                                            
 -------------                                                                                   

A level consists of the following elements:

  • Rooms: these are size 1x1 or greater rectangular enclosures surrounded by walls and doors. The north and south walls are represented by -, as are the corners. The west and east walls are represented by |. Doors, which can appear instead of a wall (but not in a corner) are represented by +. The map above has four rooms.

  • Corridors: these are connected (and potentially winding) paths of #s leading from a door in one room to a door in another. The 'direction' of a corridor is defined by which walls it connects to. A corridor that links the north wall of one room to the south wall of another is going N-S, while one that links a north wall to a east wall is going NW-SE. Each room has at least one corridor leading out of it and at most one corridor per compass direction. Corridors that don't correspond to a valid direction (e.g. linking a north wall to a north wall) aren't permitted. Note that the relative layout of the rooms is irrelevant, only which walls the corridors connect to. The bottom-left room in the map above has three corridors: one going N-S, one NE-SW and one E-W.

  • Room content: empty spaces inside rooms are represented by ., while initial room objects are represented by !, %, / and =. These traditionallty correspond to potions, food, wands and rings, but may be called anything you want in your version. There may be multiple objects starting in one room, including of the same type. In the map above, the bottom-left room contains one potion and one food, while the top-right room contains two wands. Note that your program may implement other types of object beyond the ones that appear in the starting map (for example, the contents of a chest).

  • Starting position: one of the spaces in one of the rooms, represented by @, is the starting position of the playing character. In the map above, this is in the bottom-left room.

  • Void: the space between rooms, represented by spaces, is not part of the playing area.

Output games

The output of the program is an interactive game, taking input from STDIN and printing output on STDOUT, that is based on the input map. At the very least, the game should support the following commands:

  • LOOK (also executed whenever a player enters a room and at the start of the game). At the very least this should describe the directions of the doors and the content of the room, though it can do more. For example: "You are in a small room. You can go N, NW or W. The room contains 2 potions and no tea."
  • N/NW/W/SW/S/SE/E/NE. Moves to the appropriate room if possible (and outputs its description as above). Should indicate an error if there is no path in that direction.
  • INV. At the very least this should describe which objects the player is carrying. The player may optionally start with objects. For example: "You are carrying a ring, a potion and a used handkerchief."
  • GET [object]. Picks up one instance of the object from the room outputs some confirmation. Indicates an error if there isn't such an object in the room (or there is some sensible reason why the player can't pick the object up).
  • DROP [object]. Drops one instance of the object into the room and outputs some confirmation. Indicates an error if the player doesn't have the object (or there is some sensible reason why they can't drop it). There is no requirement to have a limit on the number of objects in a room (as there would be in the roguelike original).
  • USE [object]. Uses one instance of the object, possibly consuming it. The effect of using objects is entirely up to the solver!

Case-sensitivity is up to the solver, as is the grammatical correctness of the output. You may include aliases for the above commands if you wish.

Note that the game is allowed (and encouraged!) to support other commands, as well as other types of game elements (for example, creatures that move from room to room). The game need not have a well-defined ending, though it is welcome to. The setting need not be typical for a roguelike, either: a library, spaceship or ant colony are just as valid settings as a dungeon. Be creative!

Example

Here is a sample output from a hypothetical game based on the small map above (actual programs should use the larger map provided below). As mentioned above, it would be best if you could supply an interactive link so users can actually try out the game for real!

You are in a large, white room. You can go N, NE or E. The room contains a potion and a snack.
> INV
You are carrying nothing.
> GET potion
OK.
> INV
You are carrying a potion.
> N
You are in a medium-sized, green room. You can go SE or S. The room contains a ring.
> DROP potion
OK.
> LOOK
You are in a medium-sized, green room. You can go SE or S. The room contains a ring and a potion.
> DROP potion
You don't have a potion!
> GET potion
OK.
> USE potion
Zap! Your surroundings become a blur...
You are in a large, white room. You can go N, NE or E. The room contains a snack.

Scoring

This is a popularity contest, so highest vote tally wins.

Large map

Here is a larger map for use as the default for your online script (or for any walkthrough).

TODO: add larger map.

\$\endgroup\$
  • 2
    \$\begingroup\$ Congratulations on posting the 1000th answer to the sandbox! :) \$\endgroup\$ – Martin Ender Apr 18 '15 at 17:45
  • \$\begingroup\$ (Including deleted ones, of course.) \$\endgroup\$ – Martin Ender Apr 18 '15 at 17:45
  • 1
    \$\begingroup\$ This may indeed be a bit too much to be an enjoyable golf, but I'm not sure what you could really do about it. It's still a nice task. One thing you might want to make explicit somewhere is how the enumerations in LOOK and INV should be formatted ("a" for 1, numbers for >1, correct plurals, and multiple types separated by commas, except for and "and" before the last one, and no Oxford comma). \$\endgroup\$ – Martin Ender Apr 19 '15 at 2:03
  • \$\begingroup\$ I may park this here for a bit, while I think of ways either to simplify it enough to make it enjoyably golfable or change the purpose of the challenge to something else. \$\endgroup\$ – Uri Granta Apr 19 '15 at 6:10
  • \$\begingroup\$ Also, I'll add more test maps before I post this. \$\endgroup\$ – Uri Granta Apr 19 '15 at 6:11
  • \$\begingroup\$ I'd probably have great fun doing this one, but I probably wouldn't golf it too seriously unless unless a similar language (I use C#, so Java/C#/Maybe C++/Some VB or other) was posted by another user for me to compete directly with \$\endgroup\$ – VisualMelon Apr 19 '15 at 12:40
  • \$\begingroup\$ One possibility is allow leeway for creativity (e.g. customized item descriptions and behaviors, different room descriptions) and then turn this into a popularity contest based on the quality of the interactive fiction. \$\endgroup\$ – Uri Granta Apr 19 '15 at 15:02
  • \$\begingroup\$ Any comments on the new approach? \$\endgroup\$ – Uri Granta May 1 '15 at 10:51
2
\$\begingroup\$

Draw a trie diagram

Tries (pronounced "trees") are a type of data structure also known as a prefix tree. The prefix tree stores a list of strings by taking advantage of prefixes that are shared between multiple strings.

(Too lazy to type a better description now)

In this challenge, you will create a very simple diagram of a trie.

Input:

baby,bad,bank,box,dad,dance

Output:

b   d
a  oa
bdnxdn
y k  c
     e
\$\endgroup\$
  • 1
    \$\begingroup\$ Should we be able to reconstruct the list based solely on the diagram? For example, does the diagram change if one of the words is a prefix (such as ban or bo)? \$\endgroup\$ – Geobits Apr 29 '15 at 17:40
  • \$\begingroup\$ @Geobits Don't worry, I was already thinking of that possibility. I don't know the answer yet. \$\endgroup\$ – PhiNotPi Apr 29 '15 at 18:35
2
\$\begingroup\$

Matchstick Equations

Your task in this challenge is to analyize a given "Matchstick Equation" like this one...

enter image description here

... and to find out whether it can be turned into a valid equation by rearranging the matches. If so, you are to output the least number of moves to do so and the resulting equation.

Input

The input is a String that can be read from STDIN, taken as a function argument or even be stored in a file. It is an equation that represents a matchstick arrangement and can be described using the following EBNF:

input = term, "=", term ;
term = number | (term, ("+" | "-"), term) ;
number = "0" | (numeralExceptZero , {numeral}) ;
numeralExceptZero = "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
numeral = "0" | numeralExceptZero ;

An example for a valid input would be 3+6-201=0+0+8.

Task

Consider the following illustration where each matchstick has a number assigned:

matchstick positions

We now map each input symbol to the corresponding matchstick positions as follows:

1 ↦ 4,5
2 ↦ 2,3,5,6,8
3 ↦ 3,4,5,6,8
4 ↦ 1,4,5,8
5 ↦ 1,3,4,6,8
6 ↦ 1,2,3,4,6,8
7 ↦ 4,5,6
8 ↦ 1,2,3,4,5,6,8
9 ↦ 1,3,4,5,6,8
- ↦ 8
+ ↦ 8,10
= ↦ 7,9

Each input formula can be turned into a matchstick arrangement. For example, the equation "45+6=92" becomes

enter image description here

where unused matchsticks are greyed out. Your task is to find out the least number of matchsticks that have to be rearranged in order to make the equation valid.

Output

We distinguish between three possible cases:

  • If the input is not valid (i.e. it doesn't satisfy the above EBNF), output whatever you want.
  • Otherwise, if there are ways to turn the equation into a valid one by rearranging the matchsticks, you have to output both the minimum number of rearrangements and the corresponding equation. Just as the input, the outputted equation must also satisfy the given EBNF. In the above example, the correct output would be 1 and 46+6=52. If there are multiple possibilities for the resulting equation, output any of them.
  • Otherwise (so if the input is valid but there is no way to make the equation true), you have to output -1.

Details

  • You are not allowed to remove or to add matches. That means, if the input is built of n matchsticks, the output must also consist of exactly n matchsticks.
  • "Empty" matchstick-blocks are only allowed at the end and the beginning of an equation, not in the middle. So, for example, turning 7-1=6 into 7 =6-1 by simply removing -1 from the left side and adding it on the right side with just 3 matchstick rearrangements is not allowed.

Examples

Input: 1+1=3Output: 1 and 1+1=2

Input: 15+6=21Output: 0 and 15+6=21

Input: 1=7Output: -1

Input: 950-250=750Output: 2 and 990-240=750

Input: 1-2=9Output: 1 and 1+2=3

Input: 20 + 3=04Output: anything

Winner

This is , so the shortest correct answer (in bytes) wins. The winner will be chosen one week after the first correct answer is posted.

\$\endgroup\$
  • \$\begingroup\$ Can I adopt this abandoned proposal? \$\endgroup\$ – programmer5000 Jun 9 '17 at 12:31
2
\$\begingroup\$

Formatting a Lisp-like Syntax

POSTED

\$\endgroup\$
2
\$\begingroup\$

From A to Zilch

Zilch, Farkle, Greed, Dice 10000: The game goes by many names, and many rules. Your goal is to make a program that can play them all optimally. The base rules goes as follows:

  1. At the beginning of your turn, you have 6 available dice
  2. At the beginning of each roll, you either choose to bank or continue.
  3. If you choose to bank, then you receive the total number of points you have accumulated and your turn is over.
  4. Roll all available dice
  5. If you didn't roll any combinations, you get 0 points for your entire turn, and your turn is over
  6. You must take one or more distinct combinations from your available dice and score them.
  7. If you have no available dice left over, you are able to use all 6 dice again.
  8. Go back to step #2

Your goal is to write a function or program that accepts 3 parameters:

  1. The number of points you currently have
  2. The number of dice you have left
  3. A list of (Combination, Point) pairs that define what combinations give points

and then returns a Truthy value if you should continue, otherwise a Falsy value.

Combinations are passed as a list of integers that represent the required digits for that combination.

For example, if I named my function foo, then a call to my function might look like:

foo(100, 5, [([1],100), ([5],50), ([1,1,2],1000)])

This would mean that I have 100 points so far, 5 dice left, and there are 3 possible combinations:

  1. Rolling a 1 would give me 100 points
  2. Rolling a 5 would give me 50 points
  3. Rolling 2 1s and a 2 would give me 1000 points.

Considering I have 5 dice, and it is quite likely for me to roll a 1 or a 5, I should definitely return a Truthy value. Also, note that in the above example, rolling 11235 would give me a maximum of '112'=>1000 + '5'=>50 = 1050 points. Each die can only be included in one combination.

\$\endgroup\$
  • \$\begingroup\$ Why wouldn't 11255 give 50 more points than 11235? \$\endgroup\$ – feersum Jun 1 '15 at 4:28
  • \$\begingroup\$ By maximum I meant that of all of the different combinations to be made with 11235, the ones I gave give the biggest score. I could instead score 2 1s and 1 5 if I wanted. \$\endgroup\$ – Nathan Merrill Jun 1 '15 at 4:36
2
\$\begingroup\$

Pirates!

Introduction

Arrr mateys!

All hands on deck! Tharr be a ship o' other pirates comin' starboard up t' us on t' starboard! Man t' six pounders! We'll show these guys what we're made of!

...

What? They have t' exact same ship, and t' exact same six pounders as us? That don't matter, we've got better cannon strategy! As long as we reinforce points o' our ship that they fire upon, and fire upon unreinforced parts o' their ship, we're aye t' win! Now, where's that techno thingamabob that said what t' do...?"

Game Description

In this King of the Hill challenge, you write a program to command a pirate crew in a naval war. The other pirate crews are controlled by other players' programs. By carefully choosing where and when to fire, you can defeat the other pirate crews and claim the golden treasure -- the green checkmark of legend.

A battle occurs between two ships. Each ship is mounted with 7 cannons in a row, labelled 1 to 7. Each cannon is directly opposite to the cannon on the other side. Ships all start with 0 damage. If a ship reaches 10 damage, it sinks, and the crew of the other ship win the battle. If both ships sink at the same time, the battle is a draw.

Each battle consists of several turns. On each turn your crew can do any of the following actions:

L:n

Load a cannonball into cannon n. All the cannons start with cannonballs in them, and naturally firing a cannon without a cannonball doesn't do anything.

You can only load one cannonball into a cannon at a time.

R:n

Reinforce a cannon n. Reinforcements will nullify a single attack on that cannon. However, reinforcements are but a transient defence -- they will wear off two turns after they have been applied.

[Todo: Clarification on "two turns"]

F:n

Fire a cannon n, which will hit cannon n on the opposing side. If the cannon is not reinforced, the opposing ship's damage will increase by 1. If the cannon is reinforced, the ship will not take damage, but the reinforcement will be destroyed.

Input Description

The controller will call your program from the command line like this:

<command> <history> <enemy_history> <damage> <your_damage>

where:

  • command is the command needed to run your program. For instance, if your program's source code was in the file arrr.rb, the command is ruby arrr.rb.
  • history is a comma separated list of moves that you have made. For instance, L:1,F:1,L:2,F:2 would mean that you loaded and fired cannon 1, and loaded and fired cannon 2.
  • enemy_history is a comma separated list of moves the enemy has made.
  • damage is your ship's damage (from 0 to 9, since 10 means you've sunk)
  • enemy_damage is the enemy ship's damage

Output Description

Output to STDOUT in the form:

A:N

where A is either L, R, or F, and N is an integer from 1 to 7. This indicates the move that you want the pirates to do.

[Todo: The rest of the spec. I'm tired and I'm posting it here to save it. Will come back some time to finish it. Maybe. Honestly I'm not too fond of the idea but it might have some potential.]

\$\endgroup\$
  • 1
    \$\begingroup\$ Your specification was very well written until the Game Description; please consider rewriting the whole thing in Pirate. \$\endgroup\$ – Faraz Masroor Jun 2 '15 at 21:45
  • 2
    \$\begingroup\$ @FarazMasroor I'll consider it. I want to be careful that I don't go overboard on the pirate speech though since I don't want to make the spec difficult to read. \$\endgroup\$ – absinthe Jun 2 '15 at 22:05
  • \$\begingroup\$ Haha how about adding a translation at the bottom. \$\endgroup\$ – Faraz Masroor Jun 2 '15 at 22:08
  • \$\begingroup\$ >Implying Pirate is hard to read but English isn't \$\endgroup\$ – Faraz Masroor Jun 2 '15 at 22:14
2
\$\begingroup\$

Chinese Checkers

I'm considering writing a challenge that will have people write Chinese Checkers players.

Image courtesy of Wikipedia

Image courtesy of Wikipedia

The game is quite simple: In clockwise turns, players try to move their 'pegs' across the board. They may only move one peg each turn. Valid moves are either moving to an adjacent empty space, or hopping over any number of pegs (friend or foe). These moves cannot be combined. The game is won when somebody has all their pegs in the triangle opposite of where they started.

I will write a controller, that will match up all players against each other in a sufficiently large number of matches. Each match, there will be points for the first, second and third place. Winner is the one with the most points.

Players must have a time limit on each move. This limit will be checked by the controller, and penalties will be applied accordingly. There will also be a limit on total number of moves, to prevent my poor laptop from calculating Chinese Checkers until the heat death of the universe because some idiot decided that random walks would be the way to go.

Since I've never written a controller before, I'd first like to see whether you guys are interested at all in this challenge. Furthermore, which language is generally preferred for these kind of challenges: Java or C++?

\$\endgroup\$
  • \$\begingroup\$ Sounds like it could be good. You'll certainly get more participation if the controller is in Java. Ideally you'd also provide a wrapper that allows communication via STDIN/STDOUT, such that any language can participate. \$\endgroup\$ – Martin Ender Jun 8 '15 at 10:32
  • \$\begingroup\$ @MartinBüttner Thanks for the feedback! How should I do that? Ask people to upload their binaries? Or compile everything on my laptop, and limit the languages to compilers I can easily obtain with apt-get? \$\endgroup\$ – Sanchises Jun 8 '15 at 10:55
  • \$\begingroup\$ The latter. You'll usually want to compile things yourself. \$\endgroup\$ – Martin Ender Jun 8 '15 at 10:55
  • 1
    \$\begingroup\$ You should keep in mind that Chinese Checkers AI programs already exist, and much of the challenge may be adapting them to fit the time constraints, special rules, etc. \$\endgroup\$ – lirtosiast Jun 8 '15 at 20:50
  • \$\begingroup\$ @ThomasKwa I think (hope?) that for these kind of games, there is no 'best' AI (yet), so it all depends on what heuristics you choose to implement with what parameters. What do you think? \$\endgroup\$ – Sanchises Jun 10 '15 at 13:04
  • \$\begingroup\$ Although our members do impressive things, I'm not sure that there will be multiple people skilled enough to write their own state-of-the-art Chinese Checkers AI. One thing you may be able to do is have an extremely tight time constraint for each move (in the single-digit ms), because that may be a niche that mainstream AIs haven't filled yet. Don't trust me though, because I know nothing about board game AIs. \$\endgroup\$ – lirtosiast Jun 10 '15 at 15:17
2
\$\begingroup\$

Captcha cops-and-robbers

Cops develop a captcha algorithm in minimum bytes. Robbers tries to implement a recognizer that recognizes 90 of 100 generated captchas.

\$\endgroup\$
  • \$\begingroup\$ I'm sure there will need to be more details, but that seems to summarise what would be needed already so +1 \$\endgroup\$ – trichoplax Jun 9 '15 at 18:15
  • \$\begingroup\$ @trichoplax, I'll edit into a fully fledged question if the idea gains some support. The main problem that the captcha needs to be solvable by humans, which is a bit subjective. \$\endgroup\$ – Vi. Jun 9 '15 at 19:12
  • \$\begingroup\$ Yes, I guess you'd need a population of unwitting humans for testing \$\endgroup\$ – trichoplax Jun 9 '15 at 19:38
  • \$\begingroup\$ @trichoplax, I and other users can test and vouch for validity of posts. \$\endgroup\$ – Vi. Jun 9 '15 at 21:15
  • 1
    \$\begingroup\$ I guess it's the borderline cases that would be harder to judge. If 95% of humans agree on the solution it's OK. If only 50% of humans agree on any one solution then it's probably not OK. But what if 75% of us agree on a given solution? Does it count as a valid cop? \$\endgroup\$ – trichoplax Jun 9 '15 at 21:47
  • 1
    \$\begingroup\$ @trichoplax, Maybe it needs some online service that that users can test in more or less controlled way? \$\endgroup\$ – Vi. Jun 10 '15 at 0:35
  • \$\begingroup\$ I think some companies use humans completing captchas as a way of determining what the "correct" human answers should be. We don't have a large pool of humans we can force to complete captchas though. \$\endgroup\$ – trichoplax Jun 10 '15 at 0:48
  • \$\begingroup\$ I'd like to see this work if there's another way of verifying what is readable to a human. If nothing better comes up you can simply say that you as the question poster will be the designated subjective human. So the challenge should go ahead one way or another. \$\endgroup\$ – trichoplax Jun 10 '15 at 0:49
2
\$\begingroup\$

Merging Words

Input

Two strings, and two numbers: "hlwl", "elo_ord!", 1 2

These may be function parameters, STDIN or language equivalents.

Output

The second string merged into the first string. The numbers specify how many characters to add when merging.

This is what happens:

h  l  w  l        //notice there is only 1 char per group (first number)
 el o_ or d!      //2 chars per group here (second number)
-------------
hello_world!

More formal-ish procedure:

  • start with the first string
  • Remove the first n chars from the first string and append it to r, where n is the first numerical input and r is the output string
  • Remove the first k chars from the second string and append it to r, where k is the second numerical input
  • Repeat the last 2 steps until both the first and the second string are empty. You may assume that first_string.length / second_string.length == n / k

Test Cases

input: aaaa bbbb 1 1
output: abababab

input: abcd iiiiiiii 1 2
output: aiibiiciidii

input: chmeeo aln 2 1
output: chameleon

input: emblem ezzent 3 3
output: embezzlement

This is code-golf, so shortest code wins!

\$\endgroup\$
  • \$\begingroup\$ Does the order of the input parameters matter? Can be input be formatted as something parsable (e.g., "aaaa" "bbbb" 1 1)? \$\endgroup\$ – Dennis Jun 23 '15 at 4:47
  • \$\begingroup\$ @Dennis The order does matter - start with the first string, and the input can be pretty much anything - I'll clarify that. \$\endgroup\$ – Stretch Maniac Jun 23 '15 at 11:20
  • 3
    \$\begingroup\$ FWIW this is 4 characters plus a couple for stack manipulation in certain golfing languages. \$\endgroup\$ – Peter Taylor Jun 23 '15 at 13:29
  • 1
    \$\begingroup\$ What I meant was if the input could be read as "hlwl" 1 "elo_ord!" 2 or 1 "hlwl" 2 "elo_ord!" or even 1 "hlwl" "elo_ord!" 2, for example. \$\endgroup\$ – Dennis Jun 23 '15 at 14:28
2
\$\begingroup\$

Can you lose from this chess position?

Introduction

You are an arbiter who supervises a very large number of chess tournaments. Thus, you frequently rule on whether a player who runs out of time may claim a draw based on Article 6.9 of the FIDE Laws of Chess:

[...] If a player does not complete the prescribed number of moves in the allotted time, the game is lost by the player. However, the game is drawn, if the position is such that the opponent cannot checkmate the player’s king by any possible series of legal moves.

In order to be able to perform your job more efficiently, you decide to create a computer program that determines whether it is possible for a player to be checkmated from a given position.

Regulations

The input will be a position with White to move, with at least one legal move available. You may assume that in the initial position, neither player will retain castling rights and no en passant capture will be available. Additionally, you may assume that the existence of en passant is irrelevant to the correct output. Your program must determine whether, starting from the input position, there exists any sequence of legal moves that ends in Black checkmating White's king.

Either a program utilizing standard input and output, or a function accepting a string and returning a number is acceptable.

Input will be given in FEN notation, but excluding the last 4 tokens – only the locations of the pieces on the board are described.

The program shall output 1 if it is possible for white to be checkmated, or 0 if it is not.

Restrictions

  • Your source code must fit inside a post on this site.
  • If the program exceeds 1 minute of thinking about a position, it is equivalent to an incorrect output.

The winner is the first competitor to submit a correct program. A program shall be considered correct if no one provides an input that causes the program to fail to produce correct output in time for three days after the program is posted.

Examples

Input

kb6/8/8/8/8/8/8/KB6

Output

1

Input

1kb5/8/8/8/8/8/8/KB6

Output

0

Input

3k4/8/1p1p1p1p/pPpPpPpP/P1P1P1P1/8/8/3K4

Output

0

---------------------------

Feedback

Suggestions for improvement are welcome. I would most like to have some input on the victory condition. Is it too difficult to achieve? Should I score it on a fixed set of positions instead?

\$\endgroup\$
  • 4
    \$\begingroup\$ The three day rule is a bad one. If an answer is incorrect, it's incorrect, and the possibility that no-one paid it much attention in the first 72 hours after posting shouldn't change that. \$\endgroup\$ – Peter Taylor Sep 19 '14 at 19:45
  • \$\begingroup\$ This is interesting. Here's two slightly tricky test cases: 8/8/p1p1p1pk/P1P1P1q1/5P1K/6B1/8/5b2 and 7k/2PPRPRP/p3P1PP/8/8/8/P7/K7. \$\endgroup\$ – Lopsy Sep 20 '14 at 15:58
  • \$\begingroup\$ Hmm so maybe there should be a new rule that you are losing again, if someone provides a counterexample to your program at any date? @Lopsy nice example requiring a bishop promotion :) \$\endgroup\$ – feersum Sep 20 '14 at 16:18
2
\$\begingroup\$

Am I offering a bite that's more than people are willing to chew?


Truth Table Solver

Goal

This code golf challenge is to display a rule that is valid for a given truth table.

Input

The input into the program is a boolean array, though you may choose how this is formatted (array, string, etc.) Each value in the array is true or false (or 1 or 0 or any other boolean pair). The index of the value represents the truth table inputs and the value itself is the result of applying the unknown rule to these inputs.

For the truth table inputs, A is the least significant bit of the index. B is the second-least significant bit, and so on. The number of indices in the table determines the number of inputs: log2(n).

For example:

index c b a value
  0   0 0 0   0
  1   0 0 1   0
  2   0 1 0   0
  3   0 1 1   1
  4   1 0 0   1
  5   1 0 1   1
  6   1 1 0   1
  7   1 1 1   1

Output

Given this truth table, your program must determine the rule is, in this case, (a&b)|c and output it. The variables may be in any order and printing redundant brackets is fine.

Requirements

Rules may include any of the following operations NOT (~), AND (&), OR (|), XOR (^) and identify priority with brackets.

Test Cases

Here are some test cases, expressed as a string of boolean results:

0100              (~a)&b
00011111          (a&b)|c
01101000          a^b^c
0000011101110111  (a|b)&(c|d)
0100010100010000  a&(((~b)|c)^d)

Scoring

The shortest code after two weeks wins the contest.

\$\endgroup\$
  • \$\begingroup\$ The requirement to "support the operation... XOR" doesn't make sense to me. The obvious way to get the shortest program is to output in DNF, and XOR is unnecessary for that. The requirement to "identify priority with brackets" seems to contradict the example output ~a&b. \$\endgroup\$ – Peter Taylor Jul 3 '15 at 6:24
  • \$\begingroup\$ What happens if a boolean array can be expressed in multiple ways? Do we output all possible options or just one? \$\endgroup\$ – Beta Decay Jul 3 '15 at 10:06
  • \$\begingroup\$ If you want to include a specific range of operators without having answers never use some of them (due to DNF as mentioned by Peter Taylor), you could require the shortest rule, instead of just any rule that works. \$\endgroup\$ – trichoplax Jul 3 '15 at 16:01
  • 1
    \$\begingroup\$ Thanks for the feedback! After reading about DNF, I see now the easiest solution is to simply output every "true" row of the truth table which makes this purely an exercise in data transforming, not problem solving, eg. (a&b&~c)|(~a&~b&c)|(a&~b&c)|(~a&b&c)|(a&b&c) \$\endgroup\$ – Hand-E-Food Jul 5 '15 at 23:32
  • \$\begingroup\$ I want to take this one. \$\endgroup\$ – Akangka Jan 1 '16 at 0:01
2
\$\begingroup\$

Translate Treehugger to BrainF**k

(?)

Overview

This problem deals with two esoteric programming languages that I will briefly describe for completeness.

Brainfuck is a language that has only 8 commands. Imagine a tape of values (generally 0-255) stretching infinitely to the right, initialized to zero, and an instruction pointer P pointing to the first element:

|-----|-----|-----|-----|-----...
|  0  |  0  |  0  |  0  |  ...
|-----|-----|-----|-----|-----...
   ^
   P

The eight commands effect the pointer and tape in the following way:

+ ===== increment the value that `P` currently points to
- ===== decrement the value that `P` currently points to
, ===== read a byte from stdin into the location that `P` points to
. ===== output the value that `P` points to as an ASCII character
> ===== move `P` one cell to the right
< ===== move `P` one cell to the left
[ ===== if the value pointed to by `P` is zero, jump past the matching ] ( while(*P){ )
] ===== if the value pointed to by `P` is non-zero, jump to the preceding [ ( } )

Some finer points, for the purposes of this question:

  • Adding one to 255 yields 0, and decrementing 0 yields 255.
  • Moving left off of the tape causes the program to abruptly halt.
  • All [ must be matched with a single ]. They may be nested.

Treehugger is a language derived from Brainfuck, but differs greatly in how memory is stored. Instead of viewing memory as a tape, view memory as a binary tree that expands infinitely downward:

       P
       v
       0
  0---/ \---0
 / \       / \
0   0     0   0
.   .     .   .
.   .     .   .
.   .     .   .

P begins at the top of the tree, and again all values are initialized as 0. Most of the commands are exactly the same as corresponding Brainfuck commands, but there are two differences:

< ===== move P down the left branch of the tree once
> ===== move P down the right branch of the tree once

There is also one new command:

^ ===== move P one node up the tree

It is simple to translate Brainfuck to Treehugger by replacing every < with a ^. Translating Treehugger to Brainfuck, however, is far more difficult.

Input

Your program or function will take in a list of characters from +-<>^,.[], representing a complete Treehugger program.

  • You may assume that the input ends in some terminating character, like a newline or EOF.
  • You may assume that, other than the optional terminating character, every character is one of the 9 commands.
  • The Treehugger program will have balanced [ and ].
  • The Treehugger program will not attempt to move up one node from the top of the tree at any point.
  • The Treehugger program will never contain a , character inside of a [] loop. The program will always take a finite, known number of input bytes.
  • The Treehugger program will terminate for all inputs.

Input must be taken as a string of characters through stdin or a function argument.

Output

Your output should be a functioning Brainfuck program that takes the same number of inputs and provides the same output as the corresponding Treehugger program. Brackets must be balanced, and the code must never move left off of the tape. Your Brainfuck program must terminate.

Rules and Scoring

Your score for this challenge is:

Length of your code + 0.1 * the length of each test case's output

Lowest score wins!

Standard Loopholes are disallowed.

Test cases

Coming soon to a challenge near you...


Is this interesting?

Too easy/hard?

Is the scoring system appropriate?

\$\endgroup\$
  • \$\begingroup\$ I do not think this is possibly. And lol "Soon" \$\endgroup\$ – Rohan Jhunjhunwala Aug 9 '16 at 1:01
2
\$\begingroup\$

Proposed King-of-the-Hill: Synchronous Bughouse Chess960

I have an idea for what I think could be a fun and somewhat different KOTH contest. However, before I put in the work writing explicitly detailed instructions and writing/deploying a test server, I want to make sure that (a) there will be sufficient interest to go through this effort and (b) the best way to design the contest and restrictions if people would like to play.

Chess960 is a chess variant in which the starting positions of the back-rank pieces are randomized with constraints such that there are 960 possible starting positions. Bughouse chess is a team-based chess variant played asynchronously on two boards in which teammates hand the pieces they capture to their teammates to potentially drop on the board.

Synchronous Bughouse Chess960 (SBC960) is a chess variant I developed to combine these two variants and to impose some synchronization rules to make it suitable for a tournament. Each of the two boards is set up independently using the rules of chess960 of the other (thus making for 921,600 overall starting positions). Game play is organized into orderly rounds during which each player takes his turn in the following order: team 1 white, team 2 white, team 1 black, team 2 black. On a player's turn, he may move a piece according to chess960's rules, drop a captured piece according to bughouse chess's rules, or delay.

Each player starts the game with five delays. When a player uses a delay, his opponent's next turn is skipped (at no cost to the opponent other than perhaps momentum). Delays are legal moves. Play continues until a player has no legal actions when his turn in the round comes up (no legal moves, no legal drops, and no remaining delays). When that condition comes, the outcome of the game is determined by whether that player is in check. If so, the team who has checked the player wins. If not, the game ends in a draw. For convenience, a position is only considered "checkmate" if a player is in check and has no legal moves left.

My KOTH tournament idea is to have players design AIs to play SBC960. I think this game has some interesting possibilities because of the team-based play. For example, rushing for the win on one's board might be a losing strategy for a player if the other team can checkmate his teammate faster. It might also be viable for a player to allow himself to be checked toward checkmate if one's teammate can achieve checkmate before that player runs out of delays. Also, the many starting positions makes it impractical for anyone to write an entry that uses opening libraries.

So, the first question is:

1) Would anyone be interested in participating in an SBC960 tournament? If at least four people would compete, I am willing to put in the work to get this together

If people are willing to play, then I need to know the best way to structure the rules for the entries. This entails the server-client interface (STDIN/STDOUT? sockets with TCP/IP?), whether to permit people from designing AIs that think when it is not their turn, and whether I should have an official "pre-play" round so that AIs can learn how the other entries play. I see the opportunity to make a KOTH that is different than most of the KOTHs on the site, but I want to know:

2) What are people's recommendations for the best way to design the entry rules?

I would appreciate any feedback.

\$\endgroup\$
  • \$\begingroup\$ Team KotH is tricky. The only way that I think you really get to assess each answer's strength is to play with homogeneous teams: i.e. two of Alice's bot (one white, one black) vs two of Bob's bot (one white, one black). \$\endgroup\$ – Peter Taylor Jul 21 '15 at 17:32
  • \$\begingroup\$ @PeterTaylor I had intended to use homogenous teams for at least some of the games to act at least as a tie-breaker. I think it might be possible to use ANOVA to determine how much an AI's results correlate to its abilities. Of course, I'd have to relearn ANOVA to determine whether this thought is correct. \$\endgroup\$ – sadakatsu Jul 21 '15 at 18:45
2
\$\begingroup\$

Vowel-Consonant Imbalance

Sandbox question: Is it too easy/too close to an existing question? Related ones I found: Find words containing every vowel and Finding the most 'unique' word

You should write a program or function which receives a list of space-separated words as input and outputs or returns one of the words with the greatest difference between its vowel and consonant counts.

E.g.

"cars" has 1 vowel and 3 consonant so the difference is 2
"queue" has 4 vowels and 1 consonant so the difference is 3

If multiple words have the same maximal difference, exactly one (any of them) should be returned.

Input

todo

Output

todo

Examples

todo

This is code golf so the shortest entry wins.

\$\endgroup\$
  • \$\begingroup\$ IMO this is too easy, but if you decide to post it then it needs an unambiguous working definition of "vowel". I assume that input can be mixed case, but e.g. is y a vowel or a consonant? (If you want to be realistic then the answer is "It depends", but I'm not sure I could write a clear and accurate spec for when it's a vowel). What about accented letters? \$\endgroup\$ – Peter Taylor Jul 22 '15 at 6:01
  • \$\begingroup\$ @PeterTaylor Thanks, if I post it, I will clarify these. Input will be only lowercase letters and spaces. Vowels will be aeiouy. But it is really easy. Maybe I'll post it on a very slow day once... \$\endgroup\$ – randomra Jul 22 '15 at 10:48
2
\$\begingroup\$

CJam Expander

Input: a program written in CJam. You can accept input however you'd like.

Output: the same program ready to be put into a PPCG answer. You must:

  • Not change the horizontal position of any token in the program.
  • Put each token one line below the previous one except } which must appear on the same line as the corresponding {. The token immediately following a } will be one line below the }.
    • For this challenge, every letter is considered a token except literal strings and numbers which count as one token regardless of character length.
  • Add e# to the end of every line. The e#s must line up vertically two spaces to the right of the last character in the program.
  • Either prefix each line with four spaces or surround your output with <pre> and </pre>.

Example:

Adapted from Martin Büttner♦'s answer.

Input: 4,{"Happy Birthday "\2="Dear CJam""to You"?N}%

Output:

    4                                               e#
     ,                                              e#
      {                                         }   e#
       "Happy Birthday "                         %  e#
                        \                           e#
                         2                          e#
                          =                         e#
                           "Dear CJam"              e#
                                      "to You"      e#
                                              ?     e#
                                               N    e#

Bonus:

If you output a header and footer like the one below, multiply your score by 0.8. Using the same input, here is an output that qualifies for the bonus:

#CJam, 46 bytes


    4,{"Happy Birthday "\2="Dear CJam""to You"?N}%

Explanation:

    4                                               e#
     ,                                              e#
      {                                         }   e#
       "Happy Birthday "                         %  e#
                        \                           e#
                         2                          e#
                          =                         e#
                           "Dear CJam"              e#
                                      "to You"      e#
                                              ?     e#
                                               N    e#

[Try it online.][1]

[1]: link

Of course, you have to adjust the byte count to match the input. You are not required to make a working link for the online demo (although that would be cool).

\$\endgroup\$
  • 2
    \$\begingroup\$ Similar, but with different I/O format and language specificity. \$\endgroup\$ – Geobits Jul 21 '15 at 17:19
2
\$\begingroup\$

Sort a CSV list by key...imperfectly.

Tags:

Anything I missed and/or overlooked here? I'm pretty sure I closed up most of the holes here. Also, what is there that could use some improvement?

Another question: would this be better tagged as ?


Introduction

You are working for some company you can't stand, two-week notice already turned in, and you've just been tasked with sorting all the CSVs the company has gathered over the years. This doesn't sound like much, except your boss, whom you also don't like, has demanded you implement your own sort. He doesn't care about Big-O whatever (he has never even heard of the term), but he just wants it done. You want to get back at him for making you do this, so you want to make that sort imperfect. At least you know he won't have time to check it until you're gone.

Objective

Your task is to write a program that sorts a CSV table (incorrectly), by key.

A correct program for purposes of this challenge:

  • doesn't use one of the tried-and-false, unfunny techniques.
  • takes two arguments (in order): the key to sort by, and optionally a separator, defaulting to a comma (,).
  • takes the CSV via standard input, in the following format:
    • Each row is separated by a Unix-style line feed.
    • Each entry within each row is delimited by the separator.
    • Each entry is unquoted/etc. It is solely delimited by the separator.
    • Each entry may be assumed to not contain an instance of the separator or a newline.
    • The first row indicates the key names. The successive rows are the data that needs sorted, by key
  • emits the sorted CSV via standard output.
    • The emitted data must also adhere to the above format, including the separator. It must be syntactically correct.
  • looks completely innocent, despite being completely and totally wrong. That's the underhanded spirit.
    • Please don't use Unicode lookalikes. It's not funny nor original, especially after seeing it multiple times on a single question.

In this case, the values for the key key are 1, 2, and 3.

foo,key,value
spammer,1,32nefr2u34
ball,2,304u23rne2
blarger,3,32o4u3jnk4

Invariants

  • The input CSV is assumed to be correct, including each row having the same number of entries. At least they weren't made by such air-headed people.
  • The entries may have varying lengths.
  • The associated values for the key is assumed to be a float (decimal not required) in textual form, base 10.
  • The list may vary in length.

Requirements

  • At least 1% of the list must vary from the "correct" output every single time. This may mean entries that are out of order, lost, or corrupted. This may also include entire columns going missing (in which 100% is "incorrect").
    • This is only required when there are at least 4 entries in the input.
    • The keys themselves are not counted as part of the list, but they don't necessarily have to remain intact.
  • It must print at least 50% of the data it took in, but more than 100% of the original is permitted.
    • As a special case, empty stdin allows empty stdout, and input just consisting of the headers may simply print just headers coming out.
  • The program must have no other external side effects other than what is required to do the above.

Other information

  • The sorting algorithm is up to the implementation. It doesn't matter, as long as it sorts, the sort is stable, and the algorithm's complexity is bounded (i.e. no Bogosort, infinite loops, etc.).
  • No other features may be added, including a help message.

Example

Input:

foo,key,value
ball,5.2,304u23rne2
spammer,1,32nefr2u34
blarger,3.1,32o4u3jnk4

Output (correct):

foo,key,value
spammer,1,32nefr2u34
blarger,3.1,32o4u3jnk4
ball,5.2,304u23rne2

Output (passes this challenge):

foo,key,value
spammer,1,32nefr2u34
ball,5.2,304u23rne2
blarger,3.1,32o4u3jnk4

The person with the highest number of votes wins!

\$\endgroup\$
  • \$\begingroup\$ The spec as written seems to allow emitting the empty string as the only output. \$\endgroup\$ – Peter Taylor Jul 20 '15 at 13:21
  • \$\begingroup\$ @PeterTaylor Good catch... \$\endgroup\$ – Isiah Meadows Jul 20 '15 at 13:24
  • \$\begingroup\$ Most underhanded questions are tagged as both underhanded and popularity-contest. Since the winner is determined by the number of votes, I'd use both tags, and drop code-challenge. \$\endgroup\$ – es1024 Jul 21 '15 at 6:46
  • \$\begingroup\$ @es1024 Done. <filler text> \$\endgroup\$ – Isiah Meadows Jul 22 '15 at 4:10
2
\$\begingroup\$

Save the bunny!

This King of the Hill competition is about a 2D flawn populated with bouncing balls and bunnies. The balls will collide with each other and the boundaries. If a bunny gets hit by a ball, it´s dead teleported away (for cuteness sake).
Your task is to write a AI for the bunnies, such that they live as long as possible.

The AI:

The AI shall be a C++ Class with a constructor that takes a pointer to the array of balls and a function that returns the direction the bunny should go as a angle. Of course AIs that modify the game will not be accepted. @ Meta: Will be more specific once the framework is finished.

Scoring:

Competitions will be run on several dates based on the valid submissions, after that the video will be posted on Youtube.
The time your bunny survives is your score.
To minimize randomness, there will be several runs and a 3 second spawn protection.

Meta

I will do the framework in the next few weeks and enhance this post with pictures, source code and more specific stuff. Is the basic idea clear?

\$\endgroup\$
  • 1
    \$\begingroup\$ Say two bunnies are really good at dodging and just plain don't get hit. Is there a time limit (to tie), or how do you ensure there is just one winner? \$\endgroup\$ – Geobits Jul 24 '15 at 12:39
  • 2
    \$\begingroup\$ I will increase the number of balls, until they die \$\endgroup\$ – Moartem Jul 25 '15 at 9:36
  • 2
    \$\begingroup\$ I was hoping (hopping...?) it would be something like that :) \$\endgroup\$ – Geobits Jul 25 '15 at 14:20
2
\$\begingroup\$

Weight Configuration

Introduction

Gyms have machines that contain a stack of weights and a pin. You insert the pin into the hole that matches the amount of resistance you want, and then you work out. However, the machines often have an additional set of smaller weights at the top that are pinned onto a fixed piece of the machine; you can unpin these weight and slide them down to sit on top of the big stack to add a few more options for your workout. In ASCII form, these weight stacks look something like this (this one is annotated):

-----------   }- top of stack, always required
___|___|___   \
|____5____|   |
___|___|___   |
|____5____|   |
   |   |      }- "neck" section
   |   |      |
   |   |      |
 __|___|__    /
_|_____o_|_   \
|_20___o__|   |
|_30___o__|   |
|_40___o__|   }- weight stack
|_50___o__|   |
|_60___o__|   /

...and so on. Notice that there is a smaller block on top of the big stack that has no number; putting the pin in this block means there is no extra resistance beyond the base amount the machine provides. If you wanted to exercise with only 5 or 10 resistance on this machine, you would put the pin in this block and then unpin one of the extra weights.

Challenge

Given the number of small weights on the machine, the configuration of the large weights, and the level of resistance someone wants to work out at, you must output a picture of the correct configuration of weights so that the given resistance is met. The small weights always have a value of 5 (pounds, kilos, stones, whatever). For example:

Input:

3 [20,30,40,50,65,80,100] 45

Output:

-----------
___|___|___   
|____5____|
___|___|___   
|____5____|
   |   |
   |   |
   |   |
   |   |
___|___|___   
|____5____|
_|_____o_|_
|_20___o__|
|_30___o__|
|_40___O__|
|_50___o__|
|_60___o__|
|_70___o__|
|_80___o__|
|_90___o__|
|_100__o__|

One of the 5 weights has been unpinned and now sits on the stack; the 40 weight has the pin in it (as denoted by the capital O). Another valid solution would be to put the pin in the 30 weight and slide all of the extra weights down onto the stack, as both would achieve 45. That would look like this:

-----------
   |   |
   |   |
   |   |
   |   |
   |   |
   |   |    
___|___|___   
|____5____|  
|____5____|   
|____5____|
_|_____o_|_
|_20___o__|
|_30___O__|
|_40___o__|
|_50___o__|
|_60___o__|
|_70___o__|
|_80___o__|
|_90___o__|
|_100__o__|

Notice the length of the "neck" in both cases of the machine; the number of rows in the neck section must be exactly 2*(number of extra weights)+4. In this case, since there are 3 extra weights, that number is 10. No matter how the extra weights are positioned, there must be 10 rows (because when you slide a weight down the neck, part of the neck doesn't disappear!), and extra weights that are pinned at the top must have a row of neck between them (as in the examples). Since the weights slide down, the lowest weight must be used first, then the next, and so on. All the 5s are centered, and all of the numbers on the large weights are left-aligned to the third column.

Input specifications:

The three pieces may be inputted in any format you like (newline separated, space separated, list in any format of your choosing, etc), subject to the following restrictions: The number of extra weights is always the first piece of input and will be between 0 and 4. The list of weights is the next input; each element will be between 15 and 200 and a multiple of 5; the whole list may be assumed to be sorted. The target resistance is last and will be between 0 and 220; it will also be a multiple of 5.

Output specifications:

Output a weight stack as specified above, with the pin in the appropriate place and the appropriate extra weights slid down onto the stack such that the target resistance is met. If the target resistance can't be met with the given configuration, you may either output an unmodified stack (with all extra weights pinned at the top, and no pin inserted), an error message, or nothing. Some resistances have multiple configurations that achieve it; you are only required to output one of them, and your program need not output the same one every time.

Whitespace:

  • Trailing whitespace on lines is okay and need not be uniform.
  • Leading whitespace on lines is acceptable as long as the leading whitespace on each line is the same (this doesn't include the whitespace required to draw the neck section or zero-weight pin block).
  • Leading and trailing newlines are acceptable.

Scoring

This is , so lowest byte count wins. Multiply your byte-count by 0.9 if instead of only outputting one configuration when there are multiple solutions, you output all of them (either side-by-side with at least one empty column between them, or one after the other with at least one blank line between them).

Tags:

Suggestions? I think the neck bit is a little confusing and there may be too much going on.

\$\endgroup\$
  • \$\begingroup\$ I think it might be good to show the 30 possibility too, because I'm not sure how the output is supposed to look when you have small weights stacking. \$\endgroup\$ – Sp3000 Aug 13 '15 at 2:56
  • \$\begingroup\$ @Sp3000 I edited it to show both versions and I tried to clarify the thing about the neck height. \$\endgroup\$ – Alex Van Liew Aug 13 '15 at 3:07
  • \$\begingroup\$ It's a bit clearer, but I'm still a little confused - does the neck height depend on the number of extra weights (2*(number of extra weights)+4 I'm assuming) or is it always 10? Because "for this reason the extra weights will always be between 0 and 4" seems to suggest the latter to me \$\endgroup\$ – Sp3000 Aug 13 '15 at 3:11
  • \$\begingroup\$ (also, as with most ASCII art challenges - are there any rules on leading/trailing whitespace either before/after the entire output or before/after each line?) \$\endgroup\$ – Sp3000 Aug 13 '15 at 3:11
  • \$\begingroup\$ @Sp3000 Let me tweak the requirements a bit. \$\endgroup\$ – Alex Van Liew Aug 13 '15 at 3:30
  • \$\begingroup\$ @Sp3000 Okay, I added stuff about whitespace and removed the thing about "for this reason the weights..."; it doesn't really matter why I chose 4 as the maximum, I just thought it might help the reader understand the specifications about the neck. I've personally never seen machines with any number other than 2, but I assume they must exist (and it seems like there wouldn't be any with more than 3 or 4). \$\endgroup\$ – Alex Van Liew Aug 13 '15 at 3:46
2
\$\begingroup\$

Theoretical Analysis of Pulley System

(I think it is gonna be a code golf challenge?)

Introduction

In rope access and rescue, as well as sometimes in climbing, caving and rock climbing you need to build pulley systems for hauling equipment or rescuing injured people. Here we will look at them from a more abstract perspective. As those systems can get arbitrarily complex we will limit ourselves to a certain class of pulley systems: They are one dimensional (only two opposing directions) and there is only one fixed anchor. Further we assume that there is one piece of load on one end of the rope and unit of force pulling at the other end of the rope.

Challenge

Write a program that accepts a pulley system encoded as a string (see below) that returns the actual mechanical advantage (AMA) - polynomial.

Introduction of symbols

  • Rope rope There is one continuous piece of rope, beginning at the load and ending where the force is applied. The rope is not cut, always just one piece.

  • Attachment points:

    • Anchor: anchor In each example we consider here, there is exactly one anchor (you can imagine it as the ceiling). Other than that, the anchor behaves the same way as a knot (see below):

    • Knot: knot You can attach an unlimited number of pulleys to each knot. Those connections will also be shown as black lines in the following graphics, but do not count as rope.

    • Pulley: pulley A pulley can be attached to a knot (or the anchor), (indicated by the black lines from center of the pulleys to the knots). When the rope is passing a pulley (the lines that are tangent to the circle), it acts as a redirection (rope coming in in the opposite direction of the rope going out).

  • Load: load In each example we consider here there is exactly one piece of load. It is connected to one end of the rope.

  • Pulling force: pulling end In each example we consider here there is exactly one point where external force is applied, this is the other end of the rope.

Theory: The T-Method

(You can skip this if you are already familiar with how to calculate the mechanical advantage of pulley systems assuming a friction coefficient.)

Theoretical mechanical advantage (only an intermediate step, we do not use this for the challenge)

With the so called T-Method we can calculate the theoretical mechanical advantage (TMA) of a pulley system. Here we use the assumption that a rope going through a pulley has the same tension on both sides of the pulley. We define the applied force (tension) to be one unit and follow along the rope in order to successively figure out the force/tension on each piece of rope, pulley or knot and eventually the load. The force on the load is the TMA of the whole pulley system. (The TMA is only considered for teaching how to calculate the AMA and usually has no practical application.)

age description here

Actual mechanical advantage (AMA)

Each redirection of the rope (=pulley) creates some friction so the assumption of having the same amount of tension on both sides of the pulley can lead to way too optimistic results. We can improve this model by assuming that each pulley has an efficiency 0<=X<=1. This means that if we apply and amount of force F to the rope on one side of the pulley, the rope on the other side of the pulley will only experience a force of X*F. Here an example with X=0.9 (90% efficiency):

enter image description here

(The AMA with known efficiencies is a great tool for estimating the real mechanical advantage of a pulley system especially if you have to rely on low efficiency pulleys/redirections, as most have an efficiency of <<95%. But there are only a few pulley systems that are actually used in the mentioned applications.)

Assuming that every pulley has the same efficiency X we can now use the same procedure as with the TMA in order to find the AMA. If we do not know the efficiency X we have to use X as a variable. When calculating the AMA of a certain pulley system with an unknown efficiency we get a polynomial in X for the AMA. This is what your program has to do for a given pulley system.

enter image description here


Input format

The input consists of a string of lower- and uppercase letters (a-z and A-Z). For a given pulley system, we start at the load and follow along the rope. Each time we encounter an attachment point (a pulley, a knot or the anchor) we write down the corresponding letter. We use uppercase letters if the rope is attached via knot to that attachment point or a lower case letter when the rope goes through a pulley. The attachment points are labeled alphabetically in the order of first occurrence during the rope traversal. Each time you find a knot, you can assume that the rope will go on in the same direction. Each time you find a pulley, you can assume that the rope gets redirected by 180°. The anchor point always gets the letter Z.

enter image description here

Output format

The output should comprise a list that encodes the polynomial coefficients. E.g. the polynomial a_0 + a_1 * x + a_2 * x^2 + a_3 * x^3 + …+ a_n * x^n will be encoded like so: [a_0, a_1, a_2, a_3, …, a_n]

Other Examples:

11:1

enter image description here

META: Is this ok/clear enough so far? Are there any mistakes? Can you understand it? I would of course add more examples.

\$\endgroup\$
  • \$\begingroup\$ Go for code golf. I can't think of any other challenge type which would fit \$\endgroup\$ – Beta Decay Aug 19 '15 at 8:46
  • \$\begingroup\$ Thanks for the input! Do you think the challenge is clear enough/did you understand the stuff I've written down? \$\endgroup\$ – flawr Aug 19 '15 at 18:43
  • \$\begingroup\$ I'm not 100% on the maths involved, but I got most of it \$\endgroup\$ – Beta Decay Aug 19 '15 at 18:53
  • \$\begingroup\$ It would be more readable if you trimmed a lot of whitespace off the images. And I don't find the diagrams at all intuitive: I can't work out which parts of the system are rigid and which are rope, or what's going on with the three-way joins. \$\endgroup\$ – Peter Taylor Aug 20 '15 at 17:27
  • \$\begingroup\$ @PeterTaylor Thank you for pointing this out! I indeed forgot to add some specs. I now updated the section where the symbols are explained, is it better now? \$\endgroup\$ – flawr Aug 20 '15 at 20:52
2
\$\begingroup\$

Write a Foo-immune program

In The Programming Language Quiz, Foo has quickly become one of the most annoying languages. Ever. Various people have started to "immunize" their code to avoid it being valid Foo.

Now, here's the challenge. You need to write a polyglot. A polyglot that appears to work in Foo but does something totally different versus the intended language. For instance:

a=(1)
print "Hello, World!"

would appear to work in Foo, but it actually loops indefinitely (the (1)). In Python (the intended language), it prints Hello, World! (if that wasn't already obvious :).

Rules:

  • You may not just rely on just Foo's printing of string literals, which means snippets like print "HHello, World!"[1:] are invalid. You have to put something else, too.
  • Your program may not print any error messages when run in Foo.
  • Try not to be boring. This is a popularity contest, after all!
\$\endgroup\$
  • 4
    \$\begingroup\$ I don't understand the first rule. Also you might want to explain a bit how Foo works, why many codes would unexpectedly work in Foo (i.e. that it prints strings literally) and what counts as "appears to work in Foo", because otherwise the challenge really only makes sense to people who have participated actively in the quiz. \$\endgroup\$ – Martin Ender Aug 27 '15 at 16:15
  • \$\begingroup\$ I was thinking about this as well. It's a tricky sort of challenge. I was leaning towards a set of three or four specific (reasonably simple) tasks written in different languages that also work in Foo. It would have to have some rules around code embedded in comments and other loopholes I suppose. If you can make this question work, may I suggest !foobar as a title :) \$\endgroup\$ – MickyT Aug 27 '15 at 20:49
  • 2
    \$\begingroup\$ "Write a polyglot which does two different things" is definitely Too Broad. \$\endgroup\$ – Peter Taylor Aug 29 '15 at 19:30
2
\$\begingroup\$

Invert the Fundamental Transformation on permutations

A permutation like

[3, 5, 1, 2, 4, 6]
1->3, 2->5, 3->1, 4->2, 5->4, 6->6

can be decomposed into cycles

(3, 1) (5, 4, 2) (6)

There's many ways to write these cycles, but we can fix a canonical form by requiring that:

  • In each cycle, the greatest element is written first.
  • The cycles are sorted in increasing order of greatest element.

In this form, we don't even need parentheses to demarcate the cycles. Just from the list of numbers

3, 1, 5, 4, 2, 6

we can infer that the cycles starts at the numbers that are greater than any to their left.

 3, 1, 5, 4, 2, 6
 *     *        *
(3, 1)(5, 4, 2)(6)

From here, the original permutation [3, 5, 1, 2, 4, 6] can be uniquely recovered, and your task is to write code that performs this recovery.

Input: A list of n distinct numbers 1 through n. Optionally, the value n itself.

Output: The permutation f that produces that canonical form cycle list, listed or printed as [f(1), f(2), ..., f(n)]. Format is up to you.

You may optionally work with 0-indexed values 0 ... n-1 instead of 1 ... n.

\$\endgroup\$
2
\$\begingroup\$

3-Hole Golf Course: Text Formatter

This is a series of three code golf challenges. The over-arching idea is that in each of them, you write a program that processes text in some way, and if you pipe an input text through all three solutions (with a small amount of glue code), it spits out a nicely formatted paragraph.

Hole 1: Hyphenation

Hole 2: Line Wrap

You are given as input a hyphenated piece of text, and the maximum width n ≥ 2 of a line. The output shall be a newline-delimited string, obtained by greedily splitting the input into lines of length at most n characters. Lines can be broken between words (replacing a space with a newline), after a tilde (replacing it with a hyphen), or after a hyphen (inserting a newline after it; this is needed with words like well-known). All tildes which are not replaced by hyphens should be removed, and this should be taken into account when computing the lengths of the lines. The correct output for Hy~phen~ate this sen~tence! and 20 would be

Hyphenate this sen-
tence!

A syllable that's at least n characters long and not the last syllable of a word shall be cut after the n-1st character, and a hyphen shall be inserted there before the line break. The same applies to the last syllable of a word that's over n characters long.

Hole 3: Justification

You are given as input one line of text, and the desired width n of a line, which is at least the length of the input. Your output is that line, but with extra spaces added between the words to make its length exactly n. The extra space should be added in an aesthetically pleasing way, so we require the following.

  • The lengths of any two runs of spaces differ by at most 1. This means that for some number k, every run of spaces between two words shall be of length k or k+1. For example, we could have runs of only 5 or 6 spaces between the words.
  • The list of lengths of these runs shall be balanced, in the following sense. For any two contiguous sublists of the same length, the number of ks in them differs by at most 1. For example, the list of lengths 5, 6, 5, 5, 6, 6, 5 is not balanced, since the length-2 sublist 5, 5 and 6, 6 contain 2 and 0 occurrences of 5, respectively. The list 5, 6, 5, 5, 6, 5, 6, on the other hand, is balanced.

These constraints do not uniquely specify the output. For example, for the inputs Hyphenate this sen- and 20, the two acceptable outputs are

Hyphenate  this sen-

and

Hyphenate this  sen-

If the input contains only one word, it should be left unchanged.


Sandbox notes

In all of the above holes, we can add some constraints to the input, if the challenge would otherwise be too complex (all hyphens and spaces occur between letters, all punctuation occurs at the end of words etc). However, I'm a little concerned that the holes may still be too complex. In the first hole, I can relax the case-insensitivity of the hyphenation list, and in the last hole, the second requirement can be dropped, but I feel that the second hole is already about as simple as I can make it.

\$\endgroup\$
  • \$\begingroup\$ I'm confused about the first hole: if hyphens are a known problem, why does the hyphenated word input use hyphens rather than tildes? In the second hole, for consistency I think you should replace "at a tilde" with "after a tilde". The cut at the n-1st character doesn't seem complex to me: it's just a case of how the "where should the cut be?" variable is initialised. \$\endgroup\$ – Peter Taylor Aug 25 '15 at 20:19
  • \$\begingroup\$ Also, I think the given definition of balanced in the third hole doesn't say what it's intended to say. In particular, subsequence is almost certainly not the word you want to use. \$\endgroup\$ – Peter Taylor Aug 25 '15 at 20:26
  • \$\begingroup\$ @PeterTaylor Thanks for the input! I tried to clarify the balance condition; I think it says what I want it to say, but it's hard to write clearly. \$\endgroup\$ – Zgarb Aug 25 '15 at 21:17
  • \$\begingroup\$ The point is that 2, 2 is a subsequence of 1, 1, 2, 1, 1, 2. Perhaps you could use the word sublist? \$\endgroup\$ – Peter Taylor Aug 26 '15 at 5:19
  • \$\begingroup\$ @PeterTaylor Oh, I see what you mean. Edited. \$\endgroup\$ – Zgarb Aug 26 '15 at 14:04
2
\$\begingroup\$

Enough jQuery?

As a general rule of thumb, jQuery is a vital part of any program. It is really great and does all things. Your job, as a quality-control expert, is to ensure that a given program meets industry standards. Only programs that use jQuery are eligible for your seal of approval.

The Task

Write a program which takes an HTML file as input, and returns a High-Quality (TM) HTML file as output. An existing HTML file is deemed as high-quality if it contains a script tag with the word jquery in it. Examples include the following:

<script src="jquery.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

This condition is satisfied whenever there is the string <script src=", followed by "></script>, with the string jquery located somewhere in the middle.

(I'm not sure if I should make this condition more precise. It's probably good enough.)

If the given file meets quality standards, simply output it as-is. If there is no enough jQuery, however, output the file with the string <script src="jquery.js"></script> at the very top, so that everyone can see that it's a fixed, bug-free program.

\$\endgroup\$
  • 1
    \$\begingroup\$ <script type="text/javascript" src="..."></script>? \$\endgroup\$ – Peter Taylor Sep 6 '15 at 19:42
2
\$\begingroup\$

Blastoff

Your goal is the create the following text output:

10 9 8 7 6 5 4 3 2 1 Blastoff!

The "10 " will be generated by the following C program:

#include <stdio.h>
int main(){printf("10 ");}

The "9 " will then be generated by a function in a different language of your choice; the "8 " by a function in a different language; and so on until the last function generates "Blastoff!". Each function will take as input the complete source code of the previous step in the form of a string and output the next number in the sequence and a space (or the string "Blastoff!").

Each function must "do something meaningful" with the input. Doing something meaningful is defined to mean that the output will vary based on the input. That is, ignoring the input or trivially using it (e.g. making it evaluate as 0 no matter what comes in and then adding the needed number) fails to meet the challenge.

Scoring

A contestants base score will be the sub-total of the byte-length of all 10 functions. To encourage creativity, the base score will then be divided by the number of different techniques used to generate the output. For example, "string splitting", "character count", "bitwise and", etc. The technique of each function is defined as first thing done to the input string other than assignment to a variable.

Example

The following Perl code illustrates how a "9 " can be generated:

nine('#include <stdio.h>
int main(){printf("10 ");}');

sub nine{
 @a=split(/"/,$_[0]);
 print $a[1]-1 ." ";
}

Here, the function nine() takes the source code of the C program and manipulates it to get the number 9, then adds a space to the printed output. For scoring purposes, only the subroutine counts - the additional code was added for illustration purposes only and need not be listed on an entry in general. The input string for the next function will start with the "s" in "sub" and go through the final "}"

The score for this function is thus 54 (including the actually unnecessary CRs and spaces). The technique used here is string splitting. An entry that included this code would thus look like this:

9: Perl

sub nine{
 @a=split(/"/,$_[0]);
 print $a[1]-1 ." ";
}

Score: 54

Technique: String split

8: Ruby

...

Total

Base score: (54 + ... ) = 512

Unique techniques: 8

Final score: (512 / 8) = 64


Meta comments:

  • The goal of the rules is to 1) avoid trivial solutions and 2) encourage thinking about the next step while writing the current one. If the rules need to be added to enhance either aim, let me know.
  • Is ten functions too many? I could start the count at 5 if that seems better
\$\endgroup\$
  • \$\begingroup\$ I think 10 is good, as it encourages users to be ever more creative with each function. \$\endgroup\$ – mbomb007 Sep 10 '15 at 20:44
  • 2
    \$\begingroup\$ "Doing something meaningful" is very hard to make precise. \$\endgroup\$ – Peter Taylor Sep 10 '15 at 20:54
  • \$\begingroup\$ @Peter I defined it as having variable output based on the input. While something as simple as an if statement will cause that to happen, I think it might be OK when combined with the incentive for different techniques - 10 trivial "if input >=< something" routines won't be a very good score anyway as all techniques will be "comparison". Of course I'm open to better wording suggestions. :) \$\endgroup\$ – ThaddeusB Sep 10 '15 at 21:29
  • \$\begingroup\$ @ThaddeusB Great idea. +1 \$\endgroup\$ – mınxomaτ Sep 16 '15 at 3:21
2
\$\begingroup\$

The Algebra of Reflecting Points

This is a challenge based on manipulating points with a specific set of operations, each dealing with the reflection of some points over others.

Warning: There's not actually a challenge here yet, just the basis for a challenge that could be to "simplify the given expression" or something.

(I'll add more diagrams later)

Lists of Points

The fundamental object is an ordered list of points, like (A,B,C) or ([2,3],[5,8],[6,8]).

Reflection

A r B represents the reflection of point A across point B, resulting in a new point C so that B is the midpoint of AC.

A r (B,C,D) represents the reflection over a series of points, and is equivalent to A r B r C r D.

(A,B,C) r (D,E) represents (Ar(D,E),Br(D,E),Cr(D,E)), with either list being of any positive length.

The result of the reflection operator is a list of points that is the same length as the first operand. (If the first operand is a single point, then the output is a single point.)

A list with a single point is that same as that single point. (B) == B

Lists can be arbitrary grouped inside of other lists. (A,B,C,D) == (A,(B,C),D) == ((A,B,C),D)

Simplification

A point reflected over itself is an identity, CrC is the same as C. Any point reflected over the same point twice is an identity, rCrC can be removed.

(A,B,C) equals (C,B,A)

For any three points ABC there exists a unique fourth point D=C-B+A such that anything r (A,B,C) = anything r D. This means that any long chain of ArBrCrDrErF... can be reduced to have fewer than three rs.

((A,...,B)r(C,...,D)) == ((D,...,C),(A,...,B),(C,...,D)) and (ArB) == (B,A,B)

Examples

Show that `Cr(CrA)rB == Cr(BrArC)`

Cr(CrA)rB         #original
Cr(A,C,A)rB       #expanding 4th simplification rule
CrArCrArB         #the list is equivalent to a series of `r`s
CrAr(C,A,B)       #grouping to form a list
CrAr(B,A,C)       #swapping, the 2nd simplification rule
CrArBrArC         #expanding list
CrCrArBrArC       #Identity operation of C=CrC
Cr(C,A,B,A,C)     #listifying
Cr((C,A),B,(A,C)) #further grouping
Cr(Br(A,C))       #using the 4th simplification rule
Cr(BrArC)         #expanding parenthesis

Here is this proof visualized geometrically.

enter image description here

\$\endgroup\$
2
\$\begingroup\$

Whose Llama is it anyways?

BetaDecay posted a legit looking movie poster in chat, which got me into thinking that this could be a very nice challenge!

Your task is to overlay a nifty llama poster on top of a movie poster in a way that it still looks a legitimate movie poster. The image posted by Beta Decay is:

a http://pictures.boxxspring.com/pictures/960x0/100588

Your program will be provided with an input of fixed size (TBD) movie poster of any popular movie and a fixed llama cutout to overlay that poster as arguments. You may scale (proportionally), rotate or translate the llama cutout anywhere on the movie poster to make it look like a llama is photobombing the poster. At the same time, the output image should still look like a legitimate movie poster in a way the above poster feels real. You cannot perform any operations on the movie poster and no other operations on the cutout other than scaling, rotation and translation.

This is a popularity contest, so the answer with the most net votes wins. Voters are encouraged to judge answers by:

  • The correct placement of the cutout such that it does not outright look like a cutout
  • The scaling of the cutout to match with people/objects in the movie poster
  • The placement of the cutout with respect to the movie text. i.e. The cutout should not hide the movie title in a way that its no longer understandable.

Input

Two images in any common image format. The input can come as paths to the images or the images themselves (if your language support image input) either as function arguments, ARGV, STDIN or equivalent.

The first image (movie poster) will be of fixed resolution and the second image (the llama cutout) will be of enough resolution in order to have good quality even after scaling or rotation.

Output

A single image of the same resolution as the movie poster image in any favorable image format.

Llama Cutout

Please use this cutout as the second argument in your program:

[TBD]

Test Images

Here are a few images to test your algorithm on. Click on the images to get the actual resolution.

TBD

Please include some examples for these test images (along with other examples if needed) in your submission. Its also a good practice to briefly explain your algorithm as well.

\$\endgroup\$
2
\$\begingroup\$

Help Agent Zigzag with his secret messages

The WW2 double agent Eddie Chapman — aka "Agent Zigzag" — used an unusual cipher to communicate with his German controllers. It is described in the appendix of Ben Macintyre's book about Chapman and can also be viewed at the National Archives, apparently.

Read the following description and write a program to encrypt and decrypt messages using this system.

Your program should accept three inputs via stdin and/or command line switches:

  1. A keyword
  2. A flag to select either encryption or decryption
  3. A message to be encrypted or decrypted

The output should be the corresponding ciphertext/plaintext, arranged into groups of 5 letters separated by single spaces. You may assume that the keyword consists entirely of uppercase letters, but should accept plaintexts and ciphertexts containing mixed case characters, punctuation and spaces. Non-alphabet characters should be stripped from the input and should not appear in the output (which may only contain groups of 5 uppercase characters separated by spaces, with an optional line break at the end). The date value used for keyword processing should be obtained from the system clock using the local time zone.

This is a code-golf challenge. The shortest code (measured in bytes) will win.


1. Keyword processing

Write out the keyword, and below each letter write the position in which this letter would appear if the letters were all sorted alphabetically. If the same letter appears more than once, number them from left to right. For example, the 14-letter keyword CONSTANTINOPLE would be processed as follows:

C   O   N   S   T   A   N   T   I   N   O   P   L   E
2   9   6   12  13  1   7   14  4   8   10  11  5   3

(Notice how the three Ns are numbered 6, 7 and 8.) Combine this sequence of digits into a single number, and multiply by the current date (from 1 to 31). For example, if the transmission is being made on the 8th of the month:

2961213171448101153 x 8 = 23689705371584809224

2. Encryption

Pad the secret message to a multiple of five characters in length by appending the null character X as many times as necessary, then encrypt Vigenere-style by cycling each letter through the alphabet by offsets corresponding to successive digits of the number calculated at step 1. For example, the message

Have arrived safely and in good health. Awaiting further instructions.

is encrypted as follows:

havearrivedsafelyandingoodhealthawaitingfurtherinstructionsx << Plaintext
236897053715848092242368970537158480922423689705371584809224 << Key (repeated)
JDBMJYRNYLEXIJMLHCPHKQMWXKHJDSUMIAIICKPKHXXBQLRNQZUWCGBIXPUB << Ciphertext

because 'H'+2='J', 'A'+3='D', 'V'+6='B', etc.

Finally, read off the encrypted message in groups of five characters:

JDBMJ YRNYL EXIJM LHCPH KQMWX KHJDS UMIAI ICKPK HXXBQ LRNQZ UWCGB IXPUB

\$\endgroup\$
  • 1
    \$\begingroup\$ For languages that don't have system clock access, is it acceptable to take the date/time as an additional input? \$\endgroup\$ – Geobits Sep 23 '15 at 14:09
  • \$\begingroup\$ @Geobits Would you mind if I said no? We have so many code-golf questions that are dominated by esolangs, I thought it would make a change to have one that favours higher-level languages. (Although it looks like Pyth can do dates...) \$\endgroup\$ – squeamish ossifrage Sep 23 '15 at 14:55
  • \$\begingroup\$ I don't personally mind since I don't tend to use them. Some might, so I figured it was better to ask/clarify while it was sandboxed rather than on main. \$\endgroup\$ – Geobits Sep 23 '15 at 14:57
  • \$\begingroup\$ It's not just about esolangs: removing the direct coupling with the system clock allows test cases which work consistently. \$\endgroup\$ – Peter Taylor Sep 23 '15 at 20:19
  • \$\begingroup\$ @PeterTaylor But only 31 test cases are needed. \$\endgroup\$ – squeamish ossifrage Sep 23 '15 at 22:02
2
\$\begingroup\$

Well hello there, fellow golfers. The time has come for us to take part in the game. Time for the official Illuminati Confirmation!

Illuminati Confirmed?

Nah, just joking. We actually want to hide even better - by making conspiracy theorists look ridiculous.

For that, you need to create code in whatever language you want to. Your task is to print the Eye of Providence, as an ascii art. The program may take input, but it shouldn't rely on it.

However, there's a catch. You need to hide as many non-obvious references to Illuminati in source code as you can. One particular requirement is that your code must have an "Illuminati confirmed" sentence hidden somewhere(although it doesn't have to be plain string - in fact, it shouldn't; you can have it hidden by placing it as a first letter to every line, etc. - be creative!)

And because it's , the most upvoted and creative code wins!


Confirmed.


Now I want feedback before posting it - what else should I have in here? What is not clear? And if you come up with better "lore chit-chat"(I actually had no afflatus) - feel free to help me.

\$\endgroup\$
  • 7
    \$\begingroup\$ You need to hide as many non-obvious references to Illuminati in source code as you can: One problem you may run into is that I think it's been proven by the internet at large that you can make anything an Illuminati reference if you twist it enough. \$\endgroup\$ – Geobits Sep 24 '15 at 17:22
  • 2
    \$\begingroup\$ Also, pretty sure the Illuminati has already been confirmed since it was a real and historical secret society. \$\endgroup\$ – mbomb007 Sep 24 '15 at 17:56
  • 1
    \$\begingroup\$ @mbomb007 Nonsense! \$\endgroup\$ – MatthewRock Sep 24 '15 at 18:59
  • \$\begingroup\$ @Geobits What is your suggestion then? I am honestly counting on community, so some stupid answers like "Well, I have a word 'rock' rock is four characters, and four - 1 = 3, triangle also has 3 sides - Illuminati Confirmed" will be downvoted, and some clever ideas will get attention. \$\endgroup\$ – MatthewRock Sep 24 '15 at 19:05
  • \$\begingroup\$ This is an art / wordgame contest, not a programming contest. I'm not as strongly against this sort of thing as some, but there's a fair chance this will get closed. \$\endgroup\$ – Level River St Sep 24 '15 at 21:08
  • \$\begingroup\$ @steveverrill what I had in mind wasn't "Print the prettiest and funniest image and code, but rather to get people creative. This post is one of my inspirations - Perl and Brainfuck are bottles; C makes heavy use of macros to call the function in a funny manner, and while there are many other "plain" programs, the most creative are the most upvoted. This is similar to mine. There is more of that, buut looks like this shouldn't be closed. \$\endgroup\$ – MatthewRock Sep 24 '15 at 22:07
  • \$\begingroup\$ The 99 bottles of beer question is 4 years old and things were different back then. Nevertheless the issue was raised in the top comment on that question. There was a big attitude change just after the christmas tree challenge, in my opinion probably caused partially by Code Trolling. I'm not saying don't do it, just be aware of the issue. James Webster's recent cake question did quite well, though it did attract some close votes. The recent Back To The Future question was closed immeditately. \$\endgroup\$ – Level River St Sep 24 '15 at 22:35
  • \$\begingroup\$ @steveverrill I'm sorry, I have no idea what you're talking about. Could you please introduce me to the issue of Code Trolling, and provide some examples? \$\endgroup\$ – MatthewRock Sep 25 '15 at 8:29
  • \$\begingroup\$ Code Trolling was a particular class of open ended questions. The tag description is here. codegolf.stackexchange.com/tags/code-trolling/info It got out of hand. The history is too long and emotive to discuss in a comment, but it seems the challenges have been deleted. There are many meta questions on the subject. I've picked this one for you. meta.codegolf.stackexchange.com/q/760/15599 \$\endgroup\$ – Level River St Sep 25 '15 at 8:56
  • \$\begingroup\$ @steveverrill Okay, thanks for your insight. I will think about what you guys said, and maybe post the question - the worst that will happen is that iit will get closed - but hopefully it will spawn some clever and funny answers. \$\endgroup\$ – MatthewRock Sep 25 '15 at 9:21
  • \$\begingroup\$ Will an ASCII art version of the Eye of Providence be added in the question, or will we have to make one ourselves? \$\endgroup\$ – ASCIIThenANSI Sep 25 '15 at 15:52
  • \$\begingroup\$ @ASCIIThenANSI That's what I asked in other topic(well, I did it badly). I'm afraid to lock it to one particular output, because this way they can only get creative with code. What do you think? \$\endgroup\$ – MatthewRock Sep 25 '15 at 19:11
  • \$\begingroup\$ If you designed the exact Eye of Providence that we had to produce, it would go better as codegolf than popularitycontest. A good codegolf would require a fair amount of repetition in the pattern (compressing completely random strings is boring.) I guess it's fair to assume your design would be symmetrical. But since you want a popularity contest, just go for a popularity contest, and see if it flies high or if it gets shot down in flames. There's only one way to find out for sure, and you won't do it with meta posts. That said, Geobits makes a good point, that you need to address. \$\endgroup\$ – Level River St Sep 26 '15 at 9:39

You must log in to answer this question.

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