568
\$\begingroup\$

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

Sandbox FAQ

Posting

To post to the sandbox, scroll to the bottom of this page 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, though you can optionally add a title at the top. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it.

When you think your challenge is ready for the public, go ahead and post it, and replace the post here with a link to the challenge and delete the sandbox post.

Discussion

The purpose of the sandbox is to give and receive feedback on posts. If you want to, feel free to give feedback to any posts you see here. Important things to comment about can include:

  • Parts of the challenge you found unclear
  • Comments addressing specific points mentioned in the proposal
  • Problems that could make the challenge uninteresting or unfit for the site

You don't need any qualifications to review sandbox posts. The target audience of most of these challenges is code golfers like you, so anything you find unclear will probably be unclear to others.

If you think one of your posts requires more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended! Be patient and try not to nag people though, you might have to ask multiple times.

It is recommended to leave your posts in the sandbox for at least several days, and until it receives upvotes and any feedback has been addressed.

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

To add an inline tag to a proposal, use shortcut link syntax with a prefix: [tag:king-of-the-hill]. To search for posts with a certain tag, include the name in quotes: "king-of-the-hill".

\$\endgroup\$
0

4549 Answers 4549

1
50 51
52
53 54
152
1
\$\begingroup\$

Code Bots ϕ

This is a challenge based on the popular Code Bots ("What's wrong with public variables?") challenge.

I made a few observations during the development of the original Code Bots:

  1. I had a literal ton of ideas and wouldn't stop harassing Nathan Merrill about them.
  2. Nathan Merrill already claimed Code Bots 2.

The solution is obvious: make my own challenge. So, that is exactly what I intend to do.

Note: I am working on various ways to distinguish the two challenges.

Variables

Note: I have changed the names of some variables to make them more "intuitive."

The variables A and B each store an integer 0-23.

The variable C (for Control) stores an integer 0-23 and is incremented at the end of every turn. It indicates which line of the program is to be executed.

The variable D (for Direction) stores and integer 0-23, which determines the current direction of the bot. The direction is determined by {north east south west}[[D % 4]].

The variable E (for Entropy) is overwritten by a random integer at the end of each turn, but only if your bot uses it that turn.

The variable F (for Feeling) provides a sense of touch. This allows you to detect when a bot is next to you. The value equals the number of adjacent bots. For example, F equals 4 when you are completely surrounded on all four sides (and thus out of luck).

The variable G (for aGe) provides a timer. The value is incremented after the end of every turn, mod 24. This allows an easy way to do for-like loops.

Instructions

Each line contains a single command, and each command takes a variety of arguments.

Flag : This represents your flag. Your goal is to smear your flag across the known universe. Each flag line has a hidden identifier denoting the owner. These lines do nothing upon execution.

Move : This moves the bot 1 unit forward in the direction that it is facing.

Copy [expr|line] [var|line] : This copies one expression to another. Both expressions must be of the same type. You can copy a line to another line or copy the value of one variable to another. Copying to yourself has a new advantage in that, instead of making an immediate change, the change is made just prior to the start of your next turn.

Copy2 [expr|line] [var|line] : This is a new version of copy, but instead of performing the action immediately after your turn, it performs the action immediately before your next turn. [todo: find a better name for it. Maybe "DelayCopy"]

If [cond] [line] [line] : This is an If statement, one of the most important statements. If the conditional evaluates to true, then the first of the two lines is executed immediately afterwards (on the same turn). If the conditional is false, then the second line is executed immediately afterwards. In order to prevent infinite loops of various kinds, a bot is not allowed to execute the same line twice in a single turn.

Jump [expr] [cond] : This is a new instruction designed to help speed up bots. Given a number N, it immediately sets the value of C to N and then executes #N on the same turn. The condition is optional, but if present it will determine whether or not the Jump command is executed or not.

Block [var|line] : This blocks a certain variable or line. Each variable or line can be blocked once, and this block prevents one modification attempt of that variable/line. If an opponent (or yourself) attempts to modify that variable, then the variable is merely unblocked rather than modified.

Arguments

There are four types of arguments, var, line, expr, and cond. Here are their relationships:

 var = *[var] | A | B | C | D | E
expr = [var] | [expr][op][expr] | [literal number]
 op = + | - | %
line = *[line] | #[expr]
cond = [expr] | [line] | [expr]=[expr] | [expr]==[expr] | [line]=[line] | [line]==[line]

There are three types of operators which can be used in expressions: Addition +, Subtraction -, and Modulo %. The modulo operator has highest preference (left to right), with addition/subtraction being applied afterwards.

There are several different kinds of conditionals.

  1. If [expr] usually returns true if the value of the expression is non-zero. There are several special cases. If D returns true if there is a bot directly in front of you. If E returns true if E is odd. (Note: add more special cases)

  2. If [line] returns true if the line contains a flag.

  3. If [expr]=[expr] returns true if the two expressions are equal mod 4.

  4. If [line]=[line] returns true if the two lines are the same type (same command).

  5. If [expr]==[expr] returns true if both expressions are equal mod 24.

  6. If [line]==[line] returns true if the two lines are exactly equal (such as both flags having the same owner).

The Turn Structure

(Initially, all variables are 0 except for E)
[command execution starts]
The command at line #C is executed.
If there is a chain of logic, it is followed until it stops or a line is visited twice.
[updates]
The effect of a Copy statement is applied, if any.
C is incremented
If needed, E is randomized.
(other bot's turns here)
F is updated
The effect of a Copy2 statement is applied, if any.
[next command execution]

Line Labels

To increase the ease of writing bots, there will be new things called line labels, which look like this word: and can be placed at the start of a line. Later in the code, you can reference the line label like this :word. (Note: The exact formatting is up for discussion).

During preprocessing, the controller will replace all instances of :word with the number of the line labeled word:. If the :word label is the only thing on the line (no command) then the entire line will be copied into that blank line. Here is an example:

main: If D #:move #:attack
:main
:main
Jump :main
move: Move
attack: Copy #:flag *#*C

Other usability features

The language will be completely case-insensitive. Comments will take the form of //comment.

The Arena

There will be 50 bots of each type entered into an arena. Initially, all of the bots will be evenly spaced on a grid and facing north.

....@.......@.......
.......@.......@....
..@.......@.......@.
.....@.......@......
@.......@.......@...
...@.......@.......@
......@.......@.....
.@.......@.......@..

Note: I believe this to be an improvement because the bots are not directly lined up with each other. In Code Bots 1, a bot could Move on its first turn and end up right behind another bot. In this grid, a bot has a much smaller chance of

A complicated example bot

Each bot can contain up to 24 lines, and each line contains an instruction. If there are any blank lines (after substitution with line labels), then those lines are filled by Flags.

main: If D #:attackloop #:move        //attack if an opponent 
:main                             //automatically filled in with the same line
loop: jump :main                  //executes line 0 again and sets C to 0
move: if T #:run #:turn           //always move (never rotate) when being attacked
run: Move
turn: If E #:run #:turn2          //randomly pick move or rotate
turn2: Copy2 D+1 D
attackloop: jump :attack
attack: Copy #:freeze *#*C         //freeze the opponent
plant: Copy #C+6 *#E              //plant your flag
:plant
:plant
:plant
Jump :loop                        //return to main loop
freeze: Copy2 C-1 C             //this creates an endless loop when executed

After preprocessing, the above bot turns into the bot below. You can also simply submit the bot below without using any line labels if you'd like.

If D #8 #3
If D #8 #3
Jump 0
If T #4 #5
Move
If E #4 #6 
Copy2 D+1 D
Jump 9
Copy #14 *#*C
Copy #C+6 *#E
Copy #C+6 *#E
Copy #C+6 *#E
Copy #C+6 *#E
Jump 2
Copy2 C-1 C
Flag
Flag
Flag
Flag
Flag
Flag
Flag
Flag
Flag

Short, Useful Code Snippets

Block #G
Jump 0 G   //block all the lines in 24 moves
\$\endgroup\$
1
\$\begingroup\$

A covering array is an N by k array in which each element is one of {0, 1, ..., v-1} (so v symbols in total), and for any t columns chosen (so an N x t array) contains all possible v^t tuples.

Input: N, k, t, v (all 4 are positive integers), and then N x k integers, each of which comes from {0, ..., v-1}. Each of the integers are separated by spaces.

Output: Yes if the input is a valid covering array, and No if it is not.

Goal: in any language you want, write a program that validates if the input is a covering array in the fastest time. I will run programs on my machine, which is a Macbook Pro 2.2 Ghz Intel i7 with 16 GB RAM.

\$\endgroup\$
4
  • \$\begingroup\$ Are you planning a follow-up which asks people to generate minimal covering arrays? That seems to be the more interesting direction. \$\endgroup\$ Jun 11, 2015 at 5:31
  • \$\begingroup\$ @PeterTaylor that's actually a cool idea, but other than v=t=2, the minimal case is not known, and no explicit construction is known (other than orthogonal arrays, which only work for one value of k). One question could be to ask for the best known minimal CA, which is actually something I'd really like (because it is part of my research). \$\endgroup\$ Jun 11, 2015 at 11:46
  • \$\begingroup\$ I was thinking of a code-challenge which scores by the best CA for certain parameters, possibly required to be deterministic and inside a certain time limit. \$\endgroup\$ Jun 11, 2015 at 12:33
  • \$\begingroup\$ @PeterTaylor I like that idea, possibly allowing any technique such as simulated annealing. \$\endgroup\$ Jun 11, 2015 at 21:02
1
\$\begingroup\$

KOTH Simpleton's Chess

Introduction

Disclaimer: The word "simpleton" is not meant to offend anyone who is simple or anything else. Don't take it personally, please.

It is a lovely afternoon at the Completely Average Chess Club, and like most afternoons, the chess players, who are also part-time code golfers, are golfing programs to play chess. They use incredibly complicated move-finding algorithms and are golfing them down into 4 byte programs. However, on this particular afternoon, some aliens, who are looking to use human intelligence to play alien chess, steal the chess players' intelligence, turning them into simpletons! Now they can't even remember all the pieces, let alone perform an alpha-beta tree-search.

Today, we won't be focusing on restoring the chess players' minds back. Instead, we'll be playing a modified chess game with simpler rules!

Rules

The pieces

Like regular chess, Simpleton Chess has two teams: white and black. Unlike regular chess, however, Simpleton Chess only has one piece that can attack north, north west and north east and can move two squares at a time. If you are familiar with regular chess, this is much like the pawn except for the fact you can attack forward (or north) and can move two squares at a time. Like regular chess, to take a piece you must move in the place of the piece that you wish to take. If there is a piece in of you, and you move 1 square in front, then you will take that piece.

Castling and en passant are ignored.

Winning the game

To win the game, you must take all the pieces of the opposing team.

Time limit

Each entry has an allowed time is 3 minutes (180000ms).

The board

Any piece that moves outside the board will disqualify you. The board is a 2D int array that you can access by assigning a variable to SimpletonUtils.read

Entries

Your entry is expected to have two methods: getName() and move().

The getName() method will return a String of the name of your entry.

The move method is a void and is called every time you need to move.

To submit the board you use SimpletonUtils.submitBoard

Entries are suggested (and very, very much encouraged) to verify the board using SimpletonUtils.verifyBoard (you have 3 minutes, no need to worry about speed). You will be disqualified if you submit an invalid board, however, you will not be disqualified for sending an invalid board to SimpletonUtils.verifyBoard. If you don't verify the board, a warning will be sent to console output if debug is on (edit SimpletonConfig.java).

Entry template

Here is an example entry to follow:

package SimpletonChess;
import SimpletonChess.SimpletonPlayer;
import SimpletonChess.SimpletonUtils;

public class MyEntry extends SimpletonPlayer {

    /**
     * Return the name of our bot to the controller
     */
    public String getName(){
        return "MyEntry";
    }

    /**
     * Method to carry out the logic for our entry
     */
    public void move(){
        SimpletonUtils utils = new SimpletonUtils();
        int[][] board = utils.read(); // Your own local copy of the board

        /*
        * TODO: Template. Add logic here
        */

       utils.submitBoard(board); // Note that you will be disqualified if your board is invalid! Check it with utils.verifyBoard(board), just use an if statement.
    }

}

** Remember to add your entry to the controller's main class, SimpletonTournament.java, when you're finished! **

Controller

The controller is on GitHub. (Link will be added when the controller is ready)

Your entries are expected to be written in Java (unless I find the time to write a console parser).

Final words

Good luck simpletons! I would very much like to see an entry using the monte carlo method, that would be splendid!

Also, a fantastic link for all things chess programming related: http://chessprogramming.wikispaces.com/

That's it from me, send your entries over today!


Notes

  • I know there is another KOTH chess tournament. I don't think this is a duplicate since it has simpler rules and different pieces
  • Is this too similar to checkers?


TODOs

  • Fix overbolding

  • Fix possibility to mess up the board with illegal moves (feedback needed)

  • Themed intro, since a lot of other people are doing it (feedback needed!)

  • Finish controller

  • Add some diagrams

  • Fix numerous typos and formatting errors

\$\endgroup\$
9
  • \$\begingroup\$ "Any pieces that the board will be deleted" Did you mean "Any pieces that the board contains will be deleted"? Also, your KOTH seems to have too much boldness . Use bacticks(`) instead of bold for code formatting and try to use bold whenever appropriate.. \$\endgroup\$
    – Spikatrix
    Jun 12, 2015 at 4:54
  • 2
    \$\begingroup\$ From your description of the move method, it sounds like an entry has the opportunity to change data that it shouldn't be allowed to change. We all tend to be sportsmanlike here, and I'm sure nobody would try to game the system like that, but you should try not to make such things available. And anyway, if somebody tries to obfuscate their code, or has a bug, an accident could end up catastrophic. I don't know how rigorous your movechecking will be, but be careful. \$\endgroup\$
    – BrainSteel
    Jun 12, 2015 at 5:12
  • 1
    \$\begingroup\$ What size is the board? Does a piece which gets level with the rearmost of the opponent's pieces become irrelevant except as a guarantee that you can't lose? \$\endgroup\$ Jun 12, 2015 at 8:57
  • \$\begingroup\$ Thank you for your feedback everyone. CoolGuy: My apologies for over-bolding, will fix. I was editing in another editor, not on StackExchange. @BrainSteel I will play around with various ways of making sure moves are not illegal. Any ideas for how I can make it impossible to unfairly change the board? I'm not very sure about this one, and I'll have a look at other KOTHs to see how they handle it. If you have any suggestions please let me know. Peter Taylor: The size of the board is 8x8. \$\endgroup\$
    – Matt Y
    Jun 13, 2015 at 3:51
  • \$\begingroup\$ @BrainSteel I have now finished a system for checking the move which should stop people from changing the board. They receive a local copy of the board and must submit it back with submitBoard (hence now move() is a void). So now I can do move checking. There will also be a method called verify which will verify the board. \$\endgroup\$
    – Matt Y
    Jun 13, 2015 at 5:52
  • \$\begingroup\$ Thanks, that looks like a fine way to handle it! You can never be too careful. I await your controller! \$\endgroup\$
    – BrainSteel
    Jun 13, 2015 at 15:48
  • \$\begingroup\$ Some diagrams/images would really help clarify the rules- for example the starting set up - I assume each player starts with two rows of pieces at their end of the board but this is not clear. Also a diagram showing the allowable moves would be really great. What happens when one of your pieces reaches the opposite edge of the board and cannot be taken. Other than that looks like a really interesting challenge and looking forward to it... :) \$\endgroup\$
    – euanjt
    Jun 13, 2015 at 16:38
  • \$\begingroup\$ Thanks for the feedback! @TheE Controller is on its way. Might take a while... I code as slow as a tortoise ;) \$\endgroup\$
    – Matt Y
    Jun 13, 2015 at 22:31
  • \$\begingroup\$ I don't think the themed intro adds anything. \$\endgroup\$
    – mbomb007
    Dec 12, 2016 at 16:07
1
\$\begingroup\$

How Many Isomers of Nonane / Undecane Are There?

Background

Hydrogen and carbon form various series of compounds called hydrocarbons. Carbon forms four bonds and hydrogen forms 1 bond. The alkanes are the series of hydrocarbons without any double bonds between carbon atoms. The first four alkanes are shown below. Hydrogen atoms are omitted for simplicity. We know each carbon forms four bonds, so the unused bonds must have hydrogen atoms on them.

Methane     Ethane    Propane    n-Butane    Isobutane
C           C-C       C-C-C          C-C     C-C-C
                                       |       |
                                     C-C       C

Note that Methane, Ethane and Propane have only one isomer, whereas Butane comes in two isomeric forms. Both have four carbon atoms but in n-Butane they are arranged in a continuous chain, whereas in Isobutane (also known as 2-Methyl Propane) they are arranged as a continuous chain of 3 atoms plus a side branch of one carbon atom.

In both cases, the ten loose bonds on the carbon atoms are occupied by hydrogen atoms. In general, for hydrocarbons with no rings or multiple bonds, the formula is Cn H(2+2n).

Task

  1. Your task is to create a program or function that accepts a single integer 0 < n < 10 and outputs to STDOUT or a file all the possible structural isomers of the hydrocarbon of formula Cn H(2+2n). That is to say, all the different ways in which n carbon atoms can be connected together, assuming freedom to twist about all bonds.

  2. The carbon atoms shall be represented by the symbol C. In the interest of simplicity, hydrogen atoms shall be omitted. The bonds shall be represented by the symbols - and |. Only horizontal and vertical bonds are allowed. Each isomer shall be represented by a network of carbon atoms separated by bonds. As such the character C will appear on a grid of pitch 2x2.

  3. Your program / function shall draw each possible isomer once and only once. The type of isomerism to be considered is structural isomerism. That is to say, compounds with different branching patterns shall be considered different. Different stereoisomers and different conformations shall be considered equivalent. Any conformation that complies with Rule 2 is valid.

  4. The different isomers shall be displayed one below the other, in any order. To assist in checking, each isomer shall be preceded by a sequential number (starting at 1) on its own line. There shall be no more than 5 blank lines between any isomer and the preceding / following numbers. Unnecesary whitespace to the left and right of each isomer shall not exceed 10 characters in either direction.

  5. To avoid extreme brute force solutions, execution time shall not exceed 1 minute on my machine for any input case.

  6. Scoring: This code golf. Shortest code wins. If your program can handle up to n=11 instead of n=9 there is a -50% bonus. Above n=9 is significantly harder, because the sidechains can themselves have sidechains.

Above n=11 there exist some isomers that cannot be represented according to the rules of this question as some atoms would overlap.

The number of isomers for each value of n is given in https://oeis.org/A000602. Note that behaviour for n=0 can be undefined. The names of the isomers are here: http://www.kentchemistry.com/links/organic/isomersofalkanes.htm

n       0  1  2  3  4  5  6  7   8   9  10   11   
isomers 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159

EXAMPLE OUTPUT n=6 (all 5 possible isomers) Note: you must display the isomers one below the other. They are displayed side by side here to save space. For further explanation, a video explaining structural isomerism with this example is here: https://www.youtube.com/watch?v=qOhEJK4Umds

1            2          3           4         5
                                                C
                                                |
C-C-C-C-C-C  C-C-C-C-C  C-C-C-C-C   C-C-C-C   C-C-C-C
               |            |         | |       |
               C            C         C C       C

EXAMPLE OUTPUT n=8 (only some of the possible isomers, you must display them all.)

n-Octane

C-C-C-C-C-C-C-C

3,4dimethyloctane. Those who know about stereoisomerism will know that in 3 dimensions the bonds are arranged in a tetrahedron around the carbon atom. This means that this compound can exist in 3 distinct forms: a lefthand form, a righthand form and a mirror symmetric form. For the purpose of this question these are equivalent and any one of the following is acceptable (and there are many other acceptable ways of drawing this isomer.)

    C-C-C-C          C          C-C-C-C             C          C-C-C-C       C-C-C-C-C-C  
      |              |              |               |            |               | |
  C-C-C-C      C-C-C-C-C-C        C-C-C-C       C-C-C-C-C-C    C-C-C-C           C C
                   |                                  |    
                   C                                  C

EXAMPLE OUTPUT n=10 (only some of the possible isomers, you must display them all.)

triisopropylmethane, or 2(methylethyl)1,3dimethylpentane (n=10 is the smallest n where there can be a sidechain of three C atoms, and therefore also the smallest n where a sidechain itself can be branched.)

    C   C
    |   |
  C-C-C-C-C
      |
    C-C-C

2,2,3,4,4pentamethylpentane (it can be shown that for n=10 a maximum of 2 carbon atoms can be completely surrounded by four other carbon atoms each.)

  C   C
  |   |
C-C-C-C-C
  | | |
  C C C
\$\endgroup\$
5
  • \$\begingroup\$ I'm surprised this hasn't been asked before, but I can't find it. Is code challenge (with codegolf tie break) the best scoring? I'm not sure about making it a codegolf, because I think the higher n are probably quite hard and it would discourage participation. \$\endgroup\$ Jun 14, 2015 at 10:27
  • \$\begingroup\$ Do enantiomers count twice? \$\endgroup\$
    – feersum
    Jun 15, 2015 at 5:37
  • \$\begingroup\$ "Your task is to create a program or function that accepts a single integer 0 < n < 12 ... The winning entry will be the program that produces correct output for the highest value of n ... Above n=11 there exist some isomers ... that cannot be represented according to the rules of this question" What I understand from this is that every valid submission gets the same score, which seems a bit pointless. With the given tie-breaker, it's effectively just a code-golf. \$\endgroup\$ Jun 15, 2015 at 7:13
  • \$\begingroup\$ @PeterTaylor I've changed it to a codegolf for n=9, plus a generous bonus for n=11. n>9 is fiddly (more for display reasons than underlying maths) because sometimes the sidechains have sidechains. I want to see all the way to n=11, but I don't want to exclude people by making it too hard. \$\endgroup\$ Jun 15, 2015 at 14:20
  • \$\begingroup\$ @feersum to avoid complication, enantiomers and other types of stereoisomers are considered equivalent, you should only include one of them for each structural isomer. In any case they can't be distinguished properly according to the display spec. Bond symbols such as < and > would be needed to show whether an atom is closer/further than another. I thought this was clear from rule 3 and example 3,4 dimethyloctane, but I'm not surprised someone asked. Is there a way to make this clearer? \$\endgroup\$ Jun 15, 2015 at 14:28
1
\$\begingroup\$

Solve the nonogram

Nonograms, also known as Hankie or Picross, are fascinating. They are really simple is essence, but to solve the most complexe one, some tricks have to be learned.

Basics

Nonograms are usually presented this way :

           1
         2 1 2
       3 2 1 2 3
     +-----------
    3|
  2 2|
1 1 1|
  2 2|
    3|

The numbers in lines and columns determine how much box in a row will be present, and how much sets there will be on this line/columns. The seconde line says 2 2which means "2 boxes in a row, at least one space, 2 boxes in a row" Let's give it a try with the 5x5 sample above. I will use #for boxes and .for blank confirmed.

           1
         2 1 2
       3 2 1 2 3
     +-----------
    3|
  2 2|
1 1 1|
  2 2|
    3|
As we said, second line says 2,some spaces,2. 
As we are playing on a 5x5 board, there's only one space remaining after 
putting the boxes, so their position is certain.
           1
         2 1 2
       3 2 1 2 3
     +-----------
    3|
  2 2| # # . # #
1 1 1|
  2 2|
    3|
There's some other 2 2 rows, let's fill them !

           1
         2 1 2
       3 2 1 2 3
     +-----------
    3|   #   #
  2 2| # # . # #
1 1 1|   .   .
  2 2| # # . # #
    3|   #   #

We can say this puzzle is over :
Look at the 1 1 1 rows, they have already 2 blank confirmed
which means there's only 3 spaces left. We can fill these, and complete the
puzzle.

           1
         2 1 2
       3 2 1 2 3
     +-----------
    3|   # # #
  2 2| # # . # #
1 1 1| # . # . #
  2 2| # # . # #
    3|   # # #

We didn't checked all confirmed blank, but it's not the matter, we only need
to check the boxes. Note that the 3 rows has been useless to solve this 
puzzle.

There you got the basics, but some tips on the wikipedia page could be useful.

Goal

Your job is to write a program in the language you want to solve nonograms.

There shouldn't be any problem, but here's some loopholes that are forbidden, just in case :).

I'd also like you to write which down command have to be run to execute your code, and

Input

The input can be graphic, an array, a string via stdin, or whatever you want. You may hard-code it, I want to know how fast your program is to solve nonograms, not how fast it is to parse datas. I'll provide two format for each test case. A ASCII-Art'd one, as shown above, and one structured as an array in the form :

 [[columns],[lines]]
 columns and line will also be noted the same way, the array for the sample :
 [[[3],[2,2],[1,1,1],[2,2],[3]],[[3],[2,2],[1,1,1],[2,2],[3]]]

Output

You must produce the solved nonogram, formated as you want as long as it is clear. It should be outputed via stdout, or your language closest alternative, as an Image, Ascii-art or left on top of the stack.

Test Cases

Puzzles will never be greater than 99*99, nor smaller than 2*2.They all are solvable by using basic techniques, the ones shown on wikipedia are far more than enough.

I might add some test cases latter, but big ones take time, a lot of time. If you want to give it a try, post one with your answer, and it will be added if it is solvable without any guess. Which means solving only those one won't be necessary nice, you need to be able to solve any "basic" nonogram : No multi-row - multi depth contradiction looking. Even contradiction shouldn't be necessary

5x5
[[[3],[2,2],[1,1,1],[2,2],[3]],[[3],[2,2],[1,1,1],[2,2],[3]]]

           1
         2 1 2
       3 2 1 2 3
     +-----------
    3|
  2 2|
1 1 1|
  2 2|
    3|

10x10

[[[3],[2,2],[1,1,1],[2,2],[3],[3,1],[2,7],[1,1,1,1],[2,2,2],[3,3]],[[3],[2,2],[1,1,1],[3,2,2],[2,2,3],[1,1,1,1],[2,4,1],[3,1,2],[4],[1]]]

                       1
             1         1 2
           2 1 2   3 2 1 2 3
         3 2 1 2 3 1 7 1 2 3
       +--------------------
      3|
    2 2|
  1 1 1|
  3 2 2|
  2 2 3|
1 1 1 1|
  2 4 1|
  3 1 2|
      4|
      1| 

30x30

[[[10,6,10],[9,8,9],[7,10,7],[7,14,6],[6,15,5],[6,15,5],[5,17,4],[5,19,4],[26,3],[4,2,10,2,3],[4,1,8,1,3],[3,12,3],[3,9,3],[3,16,3],[3,16,3][3,16,3][3,16,3][3,16,3],[3,9,3],[3,12,3],[3,1,8,1,3],[4,2,10,2,3],[4,25],[4,19,4],[5,17,5],[6,16,5],[6,12,7],[8,10,8],[8,8,10],[10,6,10]]

                                  4 4                   3 4
                                  2 1                   1 2
               10 9 7 7 6 6 5 5  10 8 3 3 3 3 3 3 3 3 3 810   4 5 6 6 8 810
                6 810141515171926 2 112 91616161616 912 1 2 41917161210 8 6
               10 9 7 6 5 5 4 4 3 3 3 3 3 3 3 3 3 3 3 3 3 325 4 5 5 7 81011 
              +------------------------------------------------------------
            30|
            30|
            30|
          11 9|
           9 6|
   6 3 1 1 3 5|
   4 3 1 1 3 3|
   2 3 2 2 4 3|
     2 6 5 4 1|
     1 6 5 5 1|
         7 5 6|
         9 7 8|
            30|
            30|
            30|
            30|
            30|
            30|
            28|
          26 1|
 1 7 1 5 1 6 2|
 2 6 1 3 1 4 2|
 2 5 1 3 1 4 3|
 3 3 1 1 1 3 4|
     4 3 1 3 4|
       6 3 3 6|
           8 8|
            30|
            30|
            30|

Solution

For those who are interested, here's the solution for the test cases.

 5x5

           1
         2 1 2
       3 2 1 2 3
     +----------
    3| . # # # .
  2 2| # # . # #
1 1 1| # . # . #
  2 2| # # . # #
    3| . # # # .

10x10
                       1
             1         1 2
           2 1 2   3 2 1 2 3
         3 2 1 2 3 1 7 1 2 3
       +--------------------
      3| . . . . . . # # # .
    2 2| . . . . . # # . # #
  1 1 1| . . . . . # . # . #
  3 2 2| . # # # . # # . # #
  2 2 3| # # . # # . # # # .
1 1 1 1| # . # . # . # . . .
  2 4 1| # # . # # # # . . #
  3 1 2| . # # # . # # . # #
      4| . . . . . . # # # #
      1| . . . . . . # . . .

30x30
Hope you'll like it, it took me a lot of time :)
                                  4 4                   3 4
                                  2 1                   1 2
               10 9 7 7 6 6 5 5  10 8 3 3 3 3 3 3 3 3 3 810   4 5 6 6 8 810
                6 810141515171926 2 112 91616161616 912 1 2 41917161210 8 6
               10 9 7 6 5 5 4 4 3 3 3 3 3 3 3 3 3 3 3 3 3 325 4 5 5 7 81011 
              +------------------------------------------------------------
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
          11 9| # # # # # # # # # # # . . . . . . . . . . # # # # # # # # #
           9 6| # # # # # # # # # . . . . . . . . . . . . . . . # # # # # #
   6 3 1 1 3 5| # # # # # # . . # # # . . # . . . # . . # # # . . # # # # #
   4 3 1 1 3 3| # # # # . . . # # # . . . # . . . # . . . # # # . . . # # #
   2 3 2 2 4 3| # # . . . . # # # . . . . # # . # # . . . . # # # # . # # #
     2 6 5 4 1| # # . # # # # # # . . . . # # # # # . . . . # # # # . . . #
     1 6 5 5 1| # . . # # # # # # . . . . # # # # # . . . . # # # # # . . #
         7 5 6| . . # # # # # # # . . . . # # # # # . . . . # # # # # # . .
         9 7 8| . # # # # # # # # # . . # # # # # # # . . # # # # # # # # .
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
            28| . # # # # # # # # # # # # # # # # # # # # # # # # # # # # .
          26 1| . . # # # # # # # # # # # # # # # # # # # # # # # # # # . #
 1 7 1 5 1 6 2| # . . # # # # # # # . # . # # # # # . # . # # # # # # . # #
 2 6 1 3 1 4 2| # # . # # # # # # . . # . . # # # . . # . . # # # # . . # #
 2 5 1 3 1 4 3| # # . . # # # # # . . # . . # # # . . # . . # # # # . # # #
 3 3 1 1 1 3 4| # # # . . . # # # . . # . . . # . . . # . . # # # . # # # #
     4 3 1 3 4| # # # # . . . # # # . . . . . # . . . . . # # # . . # # # #
       6 3 3 6| # # # # # # . . # # # . . . . . . . . . # # # . # # # # # #
           8 8| # # # # # # # # . . . . . . . . . . . . . . # # # # # # # #
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
            30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
60x60
Not completed, not tested

                              60| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
                     6 3 1 1 335| # # # # # # . . # # # . . # . . . # . . # # # . . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
             6 3 1 1 3 6 6 5 5 1| # # # # # # . . # # # . . # . . . # . . # # # . . # # # # # # . . # # # # # # . . . . # # # # # . . . . # # # # # . . #
                             647| . # # # # # # . . . . . . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
                   5 1 1 3 2 1 4| # # # # # . . . . . . . . . . . . . . . . # . . . . . . . . . . . . . . . . . . . . # . # # # . # # . # . . . . # # # #
                   1 2 1 2 2 1 4| . # . # # . . . . . . . . . . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . . # # . # # . # . . . . # # # #
                     1 2 1 2 1 3| # . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . # # . # . . . . . # # #
                       2 2 1 1 2| # # . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . # . . . . . . . . # #
                           3 2 2| # # # . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # #
                           3 2 1| # # # . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
                           3 3 1| . # # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
                             1 8| # . # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
                         1 4 4 1| # . # # # # . # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
                         1 3 2 2| # . # # # . . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # #
                         1 3 2 1| # . . # # # . . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
                         2 4 3 1| # # . # # # # . . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # .
                         4 3 3 2| # # # # . # # # . . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # #
                         3 4 3 1| . # # # . . # # # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
                           1 3 8| # . # # # . # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
                       1 3 1 5 1| # . # # # . # . # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
                         1 5 4 2| # . # # # # # . # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # #
                       2 4 2 3 2| # # . # # # # . # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # .
                   2 2 2 1 3 2 1| # # . # # . # # . # . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . #
                   1 2 2 1 3 2 2| . # . # # . # # . # . . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # #
                   3 1 2 2 4 2 2| # # # . # . # # . # # . # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # .
                 3 1 2 4 3 2 2 1| # # # . # . # # . # # # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # . #
               1 2 2 3 2 3 2 2 2| # . # # . # # . # # # . # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # . # #
               1 2 2 3 2 3 2 2 2| # . # # . # # . # # # . # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # . # # .
                 4 2 6 4 2 2 2 1| # # # # . # # . # # # # # # . # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # . # # . #
                   6 6 4 2 2 2 2| . # # # # # # . # # # # # # . # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # . # # . # #
               3 3 2 3 5 3 2 2 2| # # # . # # # . # # . # # # . # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # # . # # . # # . # #
             1 1 3 2 6 3 4 2 2 2| # . # . # # # . # # . # # # # # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . # # # # . # # . # # . # #
         1 5 2 2 1 1 3 2 2 2 2 1| # . # # # # # . # # . # # . # . # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . # # . . # # . # # . # # . #
         1 3 1 2 2 1 1 4 3 2 2 2| # . # # # . # . # # . # # . # . # . # # # # . . . . . . . . . . . . . . . . . . . . . . . # # # . . . # # . # # . # # .
           1 3 1 2 2 3 4 4 2 2 2| # . # # # . # . # # . # # . # # # . . # # # # . . . . . . . . . . . . . . . . . . . . . # # # # . . . . # # . # # . # #
       1 1 1 1 2 2 3 4 2 2 2 2 1| # . # . # . # . # # . # # . # # # . . # # # # . . . . . . . . . . . . . . . . . . . . # # . . # # . . . . # # . # # . #
             3 6 2 4 1 3 3 2 2 2| # # # . # # # # # # . # # . # # # # . # . # # # . . . . . . . . . . . . . . . . . . # # # . . . # # . . . . # # . # # .
           2 2 3 2 4 1 4 4 2 2 2| . # # . # # . # # # . # # . # # # # . # . # # # # . . . . . . . . . . . . . . . . # # # # . . . . # # . . . . # # . # #
       2 2 3 2 1 1 1 4 2 2 2 2 1| # # . . # # . # # # . # # . # . . # . # . # # # # . . . . . . . . . . . . . . . # # . . # # . . . . # # . . . . # # . #
         2 6 2 1 2 1 2 3 3 2 2 2| # # . . # # # # # # . # # . # . # # . # . # # . # # # . . . . . . . . . . . . # # # . . . # # . . . . # # . . . . # # .
           4 5 4 2 1 1 3 4 2 2 2| # # # # . # # # # # . # # # # . # # . # . # . . # # # . . . . . . . . . . . # # # # . . . . # # . . . . # # . . . . # #
         3 5 4 2 1 1 2 2 2 2 2 1| . # # # . # # # # # . # # # # . # # . # . # . . # # . . . . . . . . . . . # # . . # # . . . . # # . . . . # # . . . . #
           8 4 4 1 2 1 2 2 2 2 1| # # # # # # # # . # # # # . # # # # . # . # # . # . . . . . . . . . . . # # . . . . # # . . . . # # . . . . # # . . # .
         3 4 1 2 4 1 3 2 2 2 2 2| # # # . # # # # . # . # # . # # # # . # . # # # . . . . . . . . . . . # # . . . . . . # # . . . . # # . . . . # # . # #
           3 6 2 4 1 6 4 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # # # . . . . . # # # # . . . . . . . . # # . . . . # # . . . . # # . #
       3 6 2 4 1 4 2 2 2 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . # # . . . # # . # # . . . . . . . . # # . . . . # # . . . . # # . #
       3 6 2 4 1 5 1 1 3 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # # . # . . . # . # # # . . . . . . . . # # . . . . # # . . . . # # . #
           3 6 2 4 1 212 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # . # # # # # # # # # # # # . . . . . . . . # # . . . . # # . . . . # # . #
       3 6 2 4 1 2 1 1 3 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # . # . . . . # . . . . # # # . . . . . . . # # . . . . # # . . . . # # . #
           3 6 2 4 1 4 1 4 2 2 4| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # # # . . . . . . # # . . . . # # . . . . # # # #
         3 6 2 4 1 4 1 2 2 2 2 4| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # . # # . . . . . # # . . . . # # . . . . # # # #
         3 6 2 4 1 4 1 2 2 2 2 3| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # . . # # . . . . # # . . . . # # . . . . # # # .
         3 6 2 4 1 4 1 2 2 2 2 4| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # . . . # # . . . # # . . . . # # . . . . # # # #
       3 6 2 4 1 4 1 2 2 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # . . . # # . . . # # . . . . # # . . . . # # . #
       3 6 2 4 1 4 1 2 2 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # . . . # # . . . # # . . . . # # . . . . # # . #
       3 6 2 4 1 4 3 2 2 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . . . # # # . . . # # . . . # # . . . # # . . . . # # . . . . # # . #
   3 6 2 4 1 4 1 1 1 2 2 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . . # . # . # . . # # . . . # # . . . # # . . . . # # . . . . # # . #
 3 6 2 4 1 4 2 1 2 2 2 2 1 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . # # . # . # # . # # . . . # # . . . # # . . # . # # . . . . # # . #
   3 6 2 4 1 4 2 1 2 2 2 2 1 2 4| # # # . # # # # # # . # # . # # # # . # . # # # # . # # . # . # # . # # . . . # # . . . # # . . # . # # . . . # # # # .
         3 6 2 4 1 4 2 1 6 4 412| # # # . # # # # # # . # # . # # # # . # . # # # # . # # . # . # # # # # # . # # # # . # # # # . # # # # # # # # # # # #

Winning criteria

Puzzle solving might be long, who will find the best heuristics? Who will find the best implementation? Fastest code will win (code will be running on my computer, i5-4440, and must not use more than 4GB of RAM). You'll be scored using the 60*60 nonogram sandbox note : have to be added. Other test cases are here to help you while developing your submission. If there's a need of a Tie-breaker, i'll provide more complex test case (maybe a 90*90?)

Sandbox

I have two questions for the sandbox :

  • Do I need to put more explanations?

  • Is there too much grammar/others faults? (I'm not native, sorry :()

As suggested by @steveverrill, I changed it to a fastest-code contest, some basic things changed. It makes much more sense, thanks.

I added the first part of the 60x60 nonogram, still have to form the array, and do the columns. I know it is ugly, but I wasn't able to come with a nice one which would be viable AND long to solve. T

\$\endgroup\$
14
  • \$\begingroup\$ You really need some time limit on this, and for a specified size. "don't try to brute force it" is vague. The shortest-code way of solving this will be to try every possible combination of 0's and 1's and check. That will take less than a second for example 1, a lifetime for example 2, and something like the current age of the universe for example 3. There are other marginally less naive ways of doing it, like generating all possible rows then checking the colums, which will also take too long. I'd go as far as to say this might go better as fastest code (largest example solved in 1 minute.) \$\endgroup\$ Jun 16, 2015 at 13:55
  • \$\begingroup\$ Did you make that batman yourself? Are you sure it's the only valid solution? (doesn't matter so long as you specify that the program can terminate when it finds any valid solution.) Note that a human will immediately note the completely full rows and the (near) symmetry, which it will make it easier, while a computer will not. \$\endgroup\$ Jun 16, 2015 at 14:00
  • \$\begingroup\$ @steveverrill I was thinking of 2~3 minutes for the 30*30 one, I don't want it to take some billion years :). But I'll take your fastest code in consideration, as it may have more sense, and could be interesting to see what people will bring. \$\endgroup\$
    – Katenkyo
    Jun 16, 2015 at 14:25
  • \$\begingroup\$ @steveverrill Yes I did, and there shouldn't be any other solution. But as per the rules of a nonogram, any solution satisfying lines/columns is a good one, just less prettier than the intended one. Using symettry is useless to solve this one. I solved it only using the "30 is length of the row, I fill", "27 2 means w+27+x+2+y=30, 30- 27+2=29 so w=y=0 and x=1" plus an other strategie designed as "simple boxes" on the wikipedia page. This is the basic movement a beginner learn, and they shouldn't be hard to code them as they can be done line-by-line and column-by-column \$\endgroup\$
    – Katenkyo
    Jun 16, 2015 at 14:30
  • \$\begingroup\$ Are you sure your 30x30 has only one solution? \$\endgroup\$
    – Sparr
    Jun 16, 2015 at 15:15
  • \$\begingroup\$ @Sparr I'm still testing to find other ones, but I can't find an other one \$\endgroup\$
    – Katenkyo
    Jun 16, 2015 at 16:44
  • 1
    \$\begingroup\$ I see you're aware fastest code means you must take reponsibilty for running the code. Score should either be: 1. time to solve a given grid size, or 2. max (square?) grid size solved in a given time. simply "fastest code" is not enough. The trouble with 1 is you've no idea how long it will take (see meta.codegolf.stackexchange.com/q/5360/15599). The trouble with 2 is you may have to define additional grids, but I think that's preferable over 1. Users can time themselves on the test cases to give an idea of the winner - probably there will be vast differences in timing.. \$\endgroup\$ Jun 16, 2015 at 19:40
  • \$\begingroup\$ @steveverrill I'm going for 2., surely with a 60*60 or 70*70 grid (would be hard to design a greater one). I think it has enough cells to see who's the best. If not, i'll push myself into a 90*90 one. \$\endgroup\$
    – Katenkyo
    Jun 17, 2015 at 7:05
  • \$\begingroup\$ According to Wikipedia this problema is NP-hard. That means grid size will have a massive impact on time. It's not at all clear whether 30x30 will run in reasonable time. If you want to score by time to complete a certain grid, I suggest you start with the smallest grid, eliminate all entries that run a measurable time (say 1 second) slower than the leader, then proceed to do the same with larger and larger grids until only one entry remains. That way you can avoid the problem of timings that are ridiculously fast or ridiculously slow. It also means the entries get tested on a variety of grids \$\endgroup\$ Jun 17, 2015 at 9:07
  • \$\begingroup\$ Oops- just seen the new note about "solveable without any guess"! If anyone encodes an algorithm for that (I'm guessing a máximum of 2 people will do that, it's easy for a human to do but quite difficult to code) it should run very fast. If it is guaranteed that no guessing is required this becomes quite a different challenge. Is it guaranteed? \$\endgroup\$ Jun 17, 2015 at 9:16
  • \$\begingroup\$ @steveverrill I might try to code a submission, to see how much time it would take. It could be used by others as a scale to see how far they are from it. A real nonogram must be solved by logic only. It can be complicated logic (while you predict what 2+ boxes placed would do on the board(depth-reasoning)). I don't think I'll be able to prove that point, but I tried for those 3 every way I could to solve them, and each time no guesses were needed. That's the reason it is long to design one ^^'. \$\endgroup\$
    – Katenkyo
    Jun 17, 2015 at 9:23
  • \$\begingroup\$ The challenge is currently self-contradictory, asking "Who will find the best heuristics?" but promising "they are all solvable using basic techniques." If it is going to be a fastest-code and not a code golf, then the puzzles should be as difficult as possible. \$\endgroup\$
    – feersum
    Jun 18, 2015 at 22:26
  • \$\begingroup\$ @feersum The fact they are all solvable by basics is because it was initially a code-golf. The 60*60 I'm designing will be a bit more trickier to solve, and I might prepare a 40*40 as an intermediate tricky case. But yeah, thanks for denoting this fact, I might have forgotten. \$\endgroup\$
    – Katenkyo
    Jun 19, 2015 at 7:12
  • \$\begingroup\$ i know this game and i cant solve it another way aside bruteforce, sorry but i thnk this challenge wouldnt give desired results \$\endgroup\$
    – Abr001am
    Jun 25, 2015 at 10:50
1
\$\begingroup\$

4-Way Intersection Simulator

Consider an intersection as follows:

enter image description here

Cars will drive up any of the above Input lanes, and will exit out of any of the 3 other Output lanes. The goal is to take the list of cars, their arrival time, and their destination, and to return the times they will exit the intersection.

We will measure the time that it takes a car to cross an intersection as 1 Tick. We will assume that the time it takes for a car to approach and leave the intersection to be 0 ticks.

Each input acts as a queue of cars. Each tick, the car that has been at the front of its respective lane the longest will cross the intersection in his respective direction.

Priority

If multiple cars have been waiting for the same amount of time, the rightmost car has priority. If there are 2 cars that are on opposing sides, they will both cross at the same time (as described below), unless only one of them is turning left. If that is the case, the car not turning left will have priority. Two cars may turn left at the same time. If there are 4 cars that arrive at the same time, the car in Input 1 will have priority.

After the car to cross has been chosen, other cars may cross at the same time, assuming their paths don't cross. Priority is given to the lane directly across from the crossing car, then to the car to right, then to the car to his left.

Input/Output

Input will be a list of cars. Each car will be passed as a tuple containing the cars' unique ID, arrival time, arrival lane, and destination lane. The arrival lane will never be the destination lane.

Your program should output a list of cars, where each car is a tuple containing the cars' unique ID and the time it reaches its destination.

I don't care if the input format exactly matches the examples below. What I do care is that you input a list of tuples/lists and output a list of tuples/lists.

Examples

[(0, 5, 2, 3)] -> [(0, 6)] 
Car 0 arrives in lane 2 at tick 5.  He leaves in lane 3 at tick 6

[(0, 3, 1, 3), (1, 3, 3, 1)] -> [(0, 4), (1, 4)] 
Car 0 and 1 arrive in lanes 1 and 3 at tick 3.  They both leave at tick 4.

[(0, 0, 3, 1), (1, 0, 4, 2), (2, 1, 4, 2)] -> [(0, 2), (1, 1), (2, 3)]
Car 0 and 1 arrive in lanes 3 and 4.  Their paths intersect, so car 1 leaves first 
because it is the rightmost car.  The next tick, car 2 arrives, but car 0 has been 
waiting the longest, so car 0 leaves next.  Finally, car 2 leaves at time 3.

[(0, 0, 1, 2), (1, 0, 2, 3), (2, 0, 3, 4), (3, 0, 4, 2)] -> [(0, 1), (1, 3), (2, 1), (3, 2)]
All four cars arrive at the same time.  Car 0 has the priority as it is in Input 1.  
Car 2 is directly across from it, and both are turning left, so they cross at the same 
time.  Car 1 is turning left, so car 3 will cross next, followed by Car 1.

[(0, 0, 1, 4), (1, 0, 2, 1), (2, 0, 3, 2), (3, 0, 4, 3)] -> [(0, 1), (1, 1), (2, 1), (3, 1)]
All four cars arrive at the same time, all are turning right, so all leave at tick 1.

[(0, 0, 1, 3), (1, 0, 4, 2), (2, 0, 3, 2), (3, 1, 1, 4), (4, 1, 4, 1), (5, 1, 2, 1), (6, 2, 3, 4), (7, 2, 1, 3), (8, 3, 1, 4), (9, 3, 4, 2), (10, 3, 3, 2)] -> [(0, 1), (2, 1), (1, 2), (3, 2), (5, 2), (6, 3), (4, 4), (10, 4), (7, 5), (9, 6), (8, 6)]
Car 2 is the rightmost, and has priority.  Car 0 is also able to cross at Tick 0
Car 1 has now been waiting the longest, and has priority.  Both Car 3 and 5 are able to
cross as well.  Car 4 was waiting behind Car 1, and so Cars 4, 6, and 7 arrive at the
same time.  Car 6 is the rightmost, so he exits at tick 3 while cars 8-10 arrive.
Car 4 is the next rightmost, so he makes his turn next, while Car 10 makes his right turn.
Car 7 finally has his turn, and crosses.  Car 8 is behind Car 7, and Car 9 intersects with
Car 7, so neither cross at the same time, but both are able to cross the next tick.
\$\endgroup\$
2
1
\$\begingroup\$

Black and White Morphing

Given two black and white images, the goal is creating a animated black and white gif that transforms one image into the other and back.

The catch is, that for all frames the number of black pixels (as well as the number of white pixels, obviously) stays the same. You can assume that the two input images have the exact same size and the exact same number of black pixels.

Discussion

@PeterTaylor suggested making the restrictions that from one frame to the next you can only swap adjecent pixels. Otherwise this challenge would be almost the same as this one, so we need a further restriction.

My goal is enforcing a 'slow' transition that can produce nice effects. One way of picturing that was considering the white pixels as fluid or sand that has to be rearranged step by step into the other image.

@trichoplax suggested making the limit that e.g. only 5% of the pixels may change in each transition.

Test Cases

This is a first series of test cases, all 320x386px and 33844 white pixels.

enter image description here enter image description here enter image description here enter image description here enter image description here

\$\endgroup\$
11
  • \$\begingroup\$ Is the stark contrast how you want to the challenge to look, or just what you happen to have at the moment? How would you feel about including dithered images that use the same number of white pixels as these but give the impression of grayscale, and make more detail visible in the currently pure black and pure white regions? \$\endgroup\$ Jun 20, 2015 at 21:04
  • \$\begingroup\$ Would it provide more challenge and more variety to include more than one value for number of white pixels? Perhaps the same 5 images could be provided in 3 categories: black heavy, white heavy and balanced. Then the results for each category can be shown so we can judge whether a given technique gives good results across the board. \$\endgroup\$ Jun 20, 2015 at 21:07
  • \$\begingroup\$ Of course there should be more series, and I like your suggestion of black heavy, white heavy and balanced. My idea way that people should come up with creative transitions from one image to the other and back, I imagined something like the 'powerponit' slide transitions. The images are black and white only for making the challenge somewhat easier. \$\endgroup\$
    – flawr
    Jun 20, 2015 at 21:09
  • \$\begingroup\$ I like the restriction to black and white only. I don't necessarily think it makes it easier, but I think restriction is very important for popularity contests otherwise they get too open ended. It might be worth adding more restriction otherwise it risks being closed as too broad. For example, you might restrict how much difference there can be from one frame to the next. Maybe only 5% of pixels can change each frame (or whatever percentage you feel is best). You might feel that particular restriction detracts from some potential solutions so that's just an example. \$\endgroup\$ Jun 20, 2015 at 21:31
  • \$\begingroup\$ The answers to this question might have some useful code for creating nice dithered images for your sample images. It converts greyscale to strictly only black and white. \$\endgroup\$ Jun 20, 2015 at 21:55
  • \$\begingroup\$ It might be worth thinking up a few examples of transition effects and then adding restrictions that don't rule out any of the effects you thought of. To make it an interesting challenge but without losing potential answers. \$\endgroup\$ Jun 20, 2015 at 21:56
  • \$\begingroup\$ For example, the effect of paint running down from the top of the picture overwriting the old picture with the new. \$\endgroup\$ Jun 20, 2015 at 21:57
  • \$\begingroup\$ Or a simple slide across (with or without the old image moving too). \$\endgroup\$ Jun 20, 2015 at 21:58
  • \$\begingroup\$ Or "burn through" from a hole appearing in the centre, like old cinema projectors if left on one frame too long. \$\endgroup\$ Jun 20, 2015 at 21:59
  • 4
    \$\begingroup\$ Cf codegolf.stackexchange.com/q/33172/194 , although the morphs there don't preserve the number of pixels of each colour in the intermediate frames. At present I would vote to close this as too broad, and suggest adding a restriction that in each frame the changed pixels must pair up into adjacent pairs which swap with each other. \$\endgroup\$ Jun 20, 2015 at 22:01
  • \$\begingroup\$ @PeterTaylor I was aware of that challenge (I did even participate=), but I did not realize that this one would be so similar to the other one. I really like your idea of the swapping restriction, but I am not sure whether this is perhaps too restrictive. Another idea I had (very vague so far) is considering the white pixels as some kind of 'fluid' that can only move with a certain velocity (or another property) and your suggestion would really match that idea. The question is for each frame transition, should we limit the number of swaps? Or the number of swaps per pixel? \$\endgroup\$
    – flawr
    Jun 21, 2015 at 10:04
1
\$\begingroup\$

Find the maximum of ax+b

Find the maximum of ax+b online

You are given a list of (a,b), and a list of x. Compute the maximum ax+b for each x. You can assume a, b and x are non-negative integers.

But this time, items in the list are added dynamically. Your program should support the following operations (you can rename the operations if that's convenient):

  • Add a,b, to insert (a,b) into the list.
  • Query x, to find the maximum ax+b in the current list, with the given x.

Your program or function must run in expected (to the randomness if your code involves that, not the input) O(nlogn) time where n is the total input length (or total number of operations).

You can write a complete program, a function, a list of functions or methods doing each operation, or a function taking one operation each time. For the later two cases, you can either return or print the result after each operation, or add an "output" operation, or output automatically when the program ends.

Examples

(will be added later.)

This is code-golf. Shortest code wins.

Note about the complexity:

If you used a builtin having a good average-case complexity, and it can be randomized to get the expected complexity easily in theory, you can assume your language did that.

That means, if your program can be tested to be O(nlogn) (in theory), with edge cases for your code, but not the implementation of your language, we'll say it is O(nlogn).

\$\endgroup\$
7
  • \$\begingroup\$ Can we assume our language's built-in sorting is O(n lg n)? \$\endgroup\$
    – xnor
    Mar 5, 2015 at 2:58
  • \$\begingroup\$ @xnor Usually they are O(n lg n). But if you meant some language with a built-in sorting function not in O(n lg n) (or nobody is bothered to check the real complexity), I'm not sure. Strictly speaking they may be not in O(n lg n) and invalid. But it seems nobody is downvoting or deleting those answers. \$\endgroup\$
    – jimmy23013
    Mar 5, 2015 at 4:38
  • \$\begingroup\$ @user23013 They are very rarely O(n log n). Most languages implement quick sort, which is O(n log n) on average but has a worst case complexity of O(n^2). That being said, I'd always include a statement along the lines "you may assume that your language's built-in sorting function runs in O(n log n)". \$\endgroup\$ Mar 6, 2015 at 21:10
  • \$\begingroup\$ @MartinBüttner Allowed expected complexity. Is it better now? \$\endgroup\$
    – jimmy23013
    Mar 7, 2015 at 2:06
  • \$\begingroup\$ I don't know... it just seems unnecessarily complicated to me and puts some esolangs at a disadvantage that might have a naive sort implementation, but ultimately it's your call. \$\endgroup\$ Mar 7, 2015 at 2:09
  • \$\begingroup\$ @MartinBüttner Do you have ideas about the stronger version (allowing inserting (a,b) dynamically)? I'm trying to make it consistent. And esolangs can answer the convex hull question anyway. \$\endgroup\$
    – jimmy23013
    Mar 7, 2015 at 2:41
  • \$\begingroup\$ @user23013 I don't think I'm qualified to have an opinion about the stronger version. ;) \$\endgroup\$ Mar 7, 2015 at 3:02
1
\$\begingroup\$

Half-finished Idea:

Diffusion Battle


Overview

Players are all present on a toroidal grid. Each player has 16 particles to start with. The total number of particles is fixed but they can change colour. Each turn a player decides what type of action to take for each particle of their colour, but cannot control the direction, which is always random.

All players' particles then move in a random direction at the same time, possibly resulting in some of them changing colour. The player with the most particles of their colour at the end of the game is the winner.


Action types

A player chooses from the following actions for each particle:

  • Drift: do not attempt to change the colour of other particles
  • Eat: attempt to change the colour of other particles

Each of these actions is applied after all players' particles have aimed in a random direction. This may result in two particles aiming for the same cell. No cell will end up with more than one particle, but aiming for the same cell results in interaction, with no movement and the following rules being applied:

  • If both particles chose Drift, nothing happens.
  • If both particles chose Eat, nothing happens.
  • If one particle chose Eat, the particle that chose Drift will become the colour of the particle that chose Eat.

Clearly choosing Eat is always an advantage when two particles aim for the same destination. However, if a particle aims for a cell that no other particle is aiming for, it will move there, with the following rules being applied:

  • If the particle chose Drift it will move with no change.
  • If the particle chose Eat it will move and take on a random colour (which may be its own colour or that of any other player).

N particles colliding

The case where N particles are all aiming for the same destination cell is a generalisation of the case for 2 particles. None of them will move to the destination cell and the following rules will be applied:

  • If all of the N particles chose Drift, nothing happens.
  • If all of the N particles chose Eat, nothing happens.
  • If some chose Drift and some chose Eat, none will move and all those that chose Drift will change to a colour chosen randomly from those exhibited by those that chose Eat. If there is more than one particle of a given colour that chose Eat, that colour will have a correspondingly higher probability of being chosen.

When N = 2 this reduces to the case described for 2 particles.

It follows that if the N particles are of the same colour, then regardless of their individual choices none will move and they will all remain the same colour.

Collision with a particle that was unable to move

What happens to particles that were aiming for an empty cell but the cell is not empty because its occupant was unable to move?


Sandbox thoughts

EITHER

  • ALL THOSE THAT AIMED FOR THE SAME CELL AFFECT EACH OTHER

OR

  • THOSE THAT AIMED FOR THE SAME CELL DO NOT MOVE, ALL THOSE THAT END UP ADJACENT AFFECT EACH OTHER

I favour the second but I need to consider how it would work with large numbers of particles adjacent.

  • Zgarb pointed out in chat that it would be better to have a small probability of changing if failing to eat, so that the penalty for failure is not so extreme. I'm likely to use this as it is fine tunable.
\$\endgroup\$
1
\$\begingroup\$

Minimum? Vertex Cover

<insert definition of (minimum) vertex cover here>

Given a graph, you must output a valid vertex covering of that graph. The entry with the smallest total size (number of vertices) over five test cases (TBD) wins.

Input

Your program will be run with one argument given: a file name. For example:

python findacover.py graph_1.txt

Submissions will read the graph from the file specified. The format of the file will be:

5
0:1 2 3
1:0 3
2:0
3:0 1 4
4:3

The first line is simply the number of vertices in the graph (V). The next V lines are the list of vertices. Each line consists of the vertex number and a colon, followed by a space-separated list of vertices connected to that vertex by an edge.

Note that each edge will be listed twice, once for each vertex it connects. You can see in the example that the edge connecting 1 and 3 is present on the line for both vertices.

Output

Output is simply a list of vertices that represent a valid vertex covering of the input graph. Output should be written to STDOUT (so my validator can score it.

I will strip all non-digit, non-space characters ([^0-9 ]) from your output and interpret the remainder as a space-separated list. For example, outputs [0, 1, 2, 3] and 0 1 2 3 will be treated the same.

For the example graph above:

Valid:

0 1 2 3 4

or

0 3

among others.

Invalid:

0 1 2

This does not cover the graph, since the edge between 3 and 4 is not covered.

Rules

  • Submissions will be run once for each graph.
  • You have a time limit of five minutes for each graph. You cannot "roll over" unused time to the next graph. This time is clocked on my computer, an i7-3770K CPU with 16GB RAM, running Ubuntu 14.04. If you might bump against this limit, make sure you send a "best-yet" output before time is up.
  • Feel free to use multiple threads, but keep it on the CPU. My graphics card is not your playground.
  • Your submission must be deterministic. If you use a PRNG, seed it with a constant value.
  • You cannot use any built-in or third-party function designed to solve vertex covering problems.
  • Standard loopholes apply. This means (for example) that you cannot hardcode your submission to these test cases. If I choose five more test cases to run, you should get comparable (obviously not exact) results.

Scoring

Your score is the number of vertices in your cover. If you return anything except a valid covering, or do not return anything within the time allotted, your score for the graph will be 200000.

Score is summed over five test cases, each consisting of a graph with 20k to 100k vertices. The lowest total score wins.

<link to test cases here>
<insert generator/validator/scorekeeper here>

Sandbox

  • Does the "function designed to solve vertex covering problems" need to be better specified? If so, how could I word that?
  • Are the graph sizes and time limits reasonable? They are designed to prevent a straight brute-force attack, but I don't believe they are too large to prevent a good approximation. Are they too small?
\$\endgroup\$
1
  • \$\begingroup\$ "Function designed to solve NP-complete problems?" Not sure, but I'm assuming you also want to rule out equivalent things like independent set. \$\endgroup\$
    – Sp3000
    Jun 27, 2015 at 6:28
1
\$\begingroup\$

Be the shortest in your own standard

This was cops-and-robbers at the beginning. But I'm thinking of changing it to a user scored challenge instead, where each user can propose a limit number of regex, and for each regex, the shortest matched program gets one point.

Working in progress. More details to be added


Task

(To be added.)

How to answer

In each answer, you should write a program with length n for the above task, and optionally a regex with no more than n/2 bytes.

The regex should consist of only character literals (including escaped ones) and [...] (...) ? * + |. You cannot use other features such as specifying number of repetitions or the beginning/ending anchors.

If you choose to include a regex, you should also specify whether programs should be nearly-matched or nearly-unmatched by the regex, defined as following:

  • A regex nearly-matches a program, if there is a character C and a subset S of the set of all occurences of C in the program, that when everything in S is replaced by a character C', the program will be matched by the regex.
  • A regex nearly-unmatches a program, if for every character C and every subset S of all occurences of C in the program, that when everything in S is replaced by a character C', the program will not be matched by the regex.

If you choose to nearly-match, it must nearly-match your own program in the same answer. And this program must be shorter than any other answer nearly-matched by the regex. The same applies if you choose to nearly-unmatch, where your program must be shorter than anything nearly-unmatched.

The programs and regexes should only use printable ASCII, tabs and newlines.

Each user can write any number of programs, but can write at most 5 regexes at the beginning. You can write one extra regex for each 5 upvotes you get.

Scoring

For each regex, if one of your program is the first of the shortest of the programs nearly-matched/unmatched by the regex according to the specification, you get 2 points. If the regex is not your own, you get one extra point.

Each of your program can be scored more than one times if they are the shortest for more than one regex.

You should not post an answer that doesn't get any score at the time you post it. But you can leave it there if it loses all the score it had. And you can post an answer that is only the shortest for your own regex.

Rules about posting and editing answers

You can always edit regexes into an answer, if you are allowed to write more regex. But once a program is the shortest for a regex at the time you post the regex, you can't post another regex that makes this version of the program shortest.

You should not edit a program in a way that it loses scores from some regex. And if you edit, you should keep the version that is paired with a regex in your answer.

Regexes should not be modified after posting for any reason if they are valid.

You should not post programs/regexes that is the same as a previous submission.

\$\endgroup\$
4
  • \$\begingroup\$ @githubphagocyte It is the program + regexes. I left an m there when there was only one regex... \$\endgroup\$
    – jimmy23013
    Dec 27, 2014 at 1:58
  • \$\begingroup\$ This doesn't seem to prevent people from just writing the best-golfed program. Bowling doesn't seem to work either (and will be a duplicate of the bowler-golfer fraction war). I'll think about it later... Shouldn't post this when I'm sleepy... \$\endgroup\$
    – jimmy23013
    Dec 27, 2014 at 3:14
  • \$\begingroup\$ It seems to me that the two regexes will be one character each, or at worst three characters in total. \$\endgroup\$ Dec 27, 2014 at 19:27
  • \$\begingroup\$ @PeterTaylor You can comment out the string matching the regex. The rule about replacing a character literal is to make sure the comment character is always available. But I'm going to abandon this post anyway if I can't find a better winning criterion... \$\endgroup\$
    – jimmy23013
    Dec 28, 2014 at 5:33
1
\$\begingroup\$

Inspired by the last question asking for the masses of the elements, this challenge will be slightly more specific. In this challenge, you will find the molar mass of a sequence of amino acid peptides.

Amino acids, of which there are 21, are the units that combine into chains and then bend and change shape to form proteins, which serve widely varying functions in cells and in the body of most all living organisms. Scientists working with peptides, such as chemists and doctors, can easily synthesize a desired peptide chain in the lab thanks to the powers of modern technology. After some purifying and such, he will have the desired sequence in the form of a white powder/crystal like substance.

However, this is science! This means that he will eventually need to weigh out a desired amount of his sequence to perform some reactions or tests. To do this, he needs to know its molar mass.

Today, we know that there are 21 amino acids, and we have found their molar masses and given them names and symbols, just like the 118 elements on the periodic table. They are as follows:

Name           Symbol   Molar Mass
Alanine         A        89 
Cysteine        C        121
Aspartic acid   D        133
Glutamic acid   E        147
Phenylalanine   F        165
Glycine         G        75 
Histidine       H        155
Isoleucine      I        131
Lysine          K        146
Leucine         L        131
Methionine      M        149
Asparagine      N        132
Proline         P        115
Glutamine       Q        146
Arginine        R        174
Serine          S        105
Threonine       T        119
Selenocysteine  U        169
Valine          V        117
Tryptophan      W        204
Tyrosine        Y        181

BUT WAIT!! (how do I make this text bigger?)

But wait!!

But wait!!

But wait!!

Unlike the elements, the mass of a peptide sequence isn't just the sum of the masses of the constituent amino acids! Amino acids combine in a reaction called a hydrolysis reaction that forms a bond called a peptide bond. Take a look at this diagram:

enter image description here

A hydrolysis reaction is a reaction in which two large molecules combine to make a larger one, but in the process lose a small molecule. In this case, they lose a water molecule (hence the name hydrolysis). Since the mass of water is 18, when two peptides bond together in a chain they lose 18 molar mass units. So if our sequence was AC (Alanine-Cysteine), the mass would be 89 + 121 - 18 = 192.

The Challenge

Your job is to golf a program that computes the molar mass of a given peptide sequence. The sequence will be specified by their one letter symbols, in all caps.

Examples: A returns 89

AC returns 192

WAGAKRLVLRRE returns 1453

Shortest byte count wins, no loopholes. Weights must be hardcoded in the program somehow.

\$\endgroup\$
7
  • \$\begingroup\$ I would estimate a greater than 50% chance that this would be closed as a near-enough dupe of codegolf.stackexchange.com/q/35599/194 . (Although I thought the same of the elements one, and I was wrong about that). \$\endgroup\$ Jun 27, 2015 at 20:51
  • \$\begingroup\$ @PeterTaylor Do you know how to make the text bigger? \$\endgroup\$ Jun 28, 2015 at 3:44
  • \$\begingroup\$ No. I know how to create headers, but that's not the same thing. \$\endgroup\$ Jun 28, 2015 at 7:07
  • \$\begingroup\$ @FarazMasroor "(how do I make this text bigger?)" -- You mean as I did in my "mass of elements" post? Select the text you want to format as code and press CTRL+K. Alternatively, add 4 spaces before each line. \$\endgroup\$
    – Spikatrix
    Jun 28, 2015 at 11:42
  • \$\begingroup\$ The protein synthesis reaction you show is an example of condensation. Hydrolysis would be the reverse reaction (which incidentally occurs during digestion of proteins.) \$\endgroup\$ Jun 29, 2015 at 18:27
  • \$\begingroup\$ If it's the text "but wait!!" that you wanted to make bigger, I've edited to show the different header text sizes available - just delete the ones you don't want. \$\endgroup\$ Jul 3, 2015 at 16:52
  • \$\begingroup\$ I've also edited to make your table of molar masses a single block (without the white lines running across it). This is just to show you how - click "rollback" from the edit history if you don't like it. \$\endgroup\$ Jul 3, 2015 at 16:56
1
\$\begingroup\$

Fundamentals of City Planning

In this challenge, you are a city planner. You have been given an N by M rectangle to fill with residential lots of size K and roads of width 1. You know that money is made based on the number of residents in the city, so your goal is to maximize the number of lots in your rectangle. However, the following rules are enforced:

  • Roads have a width of 1 square, and all roads must be orthogonally connected to each other.
  • Every lot must share at least 1 side with a road
  • Lots must all be the same size K. They can be in the shape of any polyomino of size K.
  • There must be at least 1 road that touches the edge of the rectangle, as your residents need to be able to get in and out!

The winner of the challenge is the one that:

  1. Fits the most lots across all of the below examples. In the case of a tie:
  2. Fastest solution, unless multiple answers are running under a second. In that case:
  3. The earliest posted solution

Submitted answers must run in under a minute.

STDIO

You will be passed three integers, N, M, K. You need to output the generated grid. Roads should be represented by .. Lots should be ordered and numbered, and when printed should be represented by their number mod 10. The ordering can be arbitrary, and is simply used to distinguish lots on output. Empty squares are allowed and are represented by #.

Test Cases for correctness

Provided solutions can be numbered differently, rotated, and/or reflected

1 2 1 
.1

1 3 1
1.2

2 2 1
1.
2.

3 3 1
123
...
456

3 3 2
11#      11.      #11     
2..  or  2..  or  2..
233      233      233

Test cases used for scoring:

20 15 1
20 15 2
20 15 3
20 15 4
20 15 5
20 15 6
20 15 7
20 15 8
\$\endgroup\$
4
  • \$\begingroup\$ 1. I got to the bit about lots being the same size K and wondered why I would choose K to be anything other than 1. Only when I got to the input spec did I understand. Adding "of size K" to the end of the second sentence would probably avoid that confusion. 2. Do you have a reference implementation? I'm worried that "fastest solution" might not be a good tiebreaker because on the given test cases the answers may execute in under 200ms. \$\endgroup\$ Jul 4, 2015 at 6:52
  • \$\begingroup\$ I updated, tell me if it looks reasonable? \$\endgroup\$ Jul 4, 2015 at 11:45
  • \$\begingroup\$ Are answers required to be deterministic? \$\endgroup\$ Jul 4, 2015 at 13:53
  • \$\begingroup\$ @trichoplax no, but deterministic will probably lead to better results. Updated the description. \$\endgroup\$ Jul 4, 2015 at 14:46
1
\$\begingroup\$

Catch the robber

This is my first time making a KOTH. I (mostly) will not post this KoTH. Read the ReadMe file for more info.


Overview

A cop spots a robber and the robber runs and ends up in a basement. The cop then goes into the basement and locks the door.

Gameplay

The basement consist of 49 rooms with dimensions 7 x 7. The top-left room has coordinates [0,0] while the bottom-right room has coordinates [6,6]. The cop starts on the room with coordinates [6,3] while the robber starts on the room with coordinates [0,3].

Cop

The cop moves first. The cop can move in one of these directions:

  • Up
  • Right
  • Down
  • Left
  • Here

The direction here indicates that the cop will stay in the current room and will not move. The rest of the directions are self-explanatory. The cop can move in a particular direction if it is a valid one, i.e, the cop cannot move out of the grid or move into a room with a trap.

The cop can also put traps in a room. At the start of every match, the cop has 3 traps. Once a trap has been placed, the cop will not be able to move into the room where the trap is placed.

The cop also has 3 pressure sensors at the start of every match. The cop can move into a room where a pressure sensor has been placed.

If the robber moves into an adjacent room of the cop, the cop will be alerted.

Robber

The robber can move in the same directions as the cop does. The robber too cannot move outside the grid.

The robber has two TrapDetector5000 which can be used by the robber. It will detect if there is a trap in one of the adjacent rooms that the robber is in.

If the cop moves into an adjacent room of the robber, the robber will be alerted.

Goal

The cop must catch the robber as soon as possible. This can be done by moving into a room where the robber is. The cop will also catch the robber if the robber moves into the room where the cop is.

If the robber moves into a room where the cop has placed a trap or a pressure sensor, the cop will be alerted and the robber will not be able to move for 2 turns, if the room had a trap. However, the robber will be able to move if the room had a pressure sensor.

The robber will be alerted if the robber steps into a room with a pressure sensor.

Controller

The controller is written in java and can be found here. As a cop or a robber you each have to each complete implement a Java class.

You have to implement the Cop interface if you are writing a Cop Bot and implement the Robber interface if you are writing a Robber Bot.

There is an enum direction with 5 directions Here, Up, Right, Down, Left which you can use when building your Bot.

You can use the Grid.isValidMove(direction) to check if that direction is a valid move. This is for Cops.

You can use the Grid.isValidPosition(direction) to check if that direction is a valid move. This is for Robbers.

You also may write additional functions within that class. The controller comes with one working example of a simple cop and robber bot.

Please use java 7 and please do not exploit stuff in the controller and cheat.

Note that your bot needs to return an int from takeTurn within 200 milliseconds. Failure to do so will result in the disqualification of your Bot.

Scoring

Each cop plays 10 rounds against each robber and the number of moves each robber makes in each round will be added up and this is the score of that particular robber. The same goes for cops.

The robber with the highest score and the cop with the lowest score wins!

\$\endgroup\$
8
  • 2
    \$\begingroup\$ This KoTH has potential, I believe. I might expand the room to ensure that traps aren't an insta-catch. Also, if a cop moves into a room next to a robber, only the robber knows? (and vice versa)? If that is true, its going to hard to beat the robber strategy of "stand until a cop moves next to you" \$\endgroup\$ Jun 27, 2015 at 2:08
  • \$\begingroup\$ First of all. Thanks for reviewing this KoTH. What size should the grid be? And "if a cop moves into a room next to a robber, only the robber knows? (and vice versa)?" -- Yes. Because this is different from those KoTHs where a turn means movement of both the players. Any idea for making it more interesting? \$\endgroup\$
    – Spikatrix
    Jun 27, 2015 at 8:15
  • \$\begingroup\$ I'd say that a 7x7 would be sufficient. If I am caught in the center, it is still possible that the cop won't catch me if he is on the edge of the room. I'm not sure how to make it more interesting, but an idea I had would be to allow both the cop and robber to place "pressure sensors" instead of traps. Their party is informed when stepped on, but they don't know which sensor has been stepped on (unless there is only 1 they placed) \$\endgroup\$ Jun 27, 2015 at 11:52
  • \$\begingroup\$ "Their party is informed when stepped on" -- Party? There is just one cop. Should there be more than one cop? \$\endgroup\$
    – Spikatrix
    Jun 27, 2015 at 11:59
  • \$\begingroup\$ No. I just used party to refer to either cop or robber depending on who placed it. \$\endgroup\$ Jun 27, 2015 at 12:04
  • \$\begingroup\$ I was thinking of cops having 2 traps + 4(?) pressure sensors. Also, I've been thinking of giving robbers something... like a dummy (moves in a straight direction and tricks the cops will be alerted if it is in an adjacent room) or one trap-detector-5000 (which detects if there if there is a trap in an adjacent room and can be used only once). What do you think? \$\endgroup\$
    – Spikatrix
    Jun 27, 2015 at 12:28
  • \$\begingroup\$ I'm not sure about the dummy idea. I think that this challenge is about calculating probabilities of the enemy's location. I'd personally would prefer abilities to be purely knowledge granting, but that's my opinion. \$\endgroup\$ Jun 27, 2015 at 13:37
  • \$\begingroup\$ @NathanMerrill I've written some code, but I don't think I'll post this. See the answer for more info. \$\endgroup\$
    – Spikatrix
    Jul 7, 2015 at 9:01
1
\$\begingroup\$

Blackjack

How to Play

Blackjack is for any number of people, but there will be only one in this case. The goal is to get as close to 21 as possible without going over. Aces will be 1 for this program. All other face cards are worth 10.

To start, the player is dealt two cards. They can then choose to hit (take another card) or stand. This repeats until they go over 21 (bust) or decide to stay.

If the player busts, their score is 0. Otherwise, their score is the total of all the cards.

Input/Output

  1. The program should output 2 "cards" (randomly choose between 2, 3, 4, 5, 6, 7, 8, 9, 10, K, Q, J, and A).
  2. The player then inputs a move, stand or hit.
  3. If he/she stands, output Final Score: [total of cards].
  4. If he/she hits, output another "card". Output Bust! if the score is over 21.
  5. Repeat steps 2-4 until the player busts or stands.

Test Cases

Output: 5 K
Input:  hit
Output: 6
Input:  stand
Output: Final Score: 21



Output: A Q
Input:  hit
Output: 7
Input:  hit
Output: 6
Output: Bust!

Rules and Other Notes

  • Aces are always 1.
  • Each output/input should be on a new line.
  • Any trailing spaces and newlines are okay.
  • Assume that all input will be valid. You don't need to notify the player of invalid input.
  • You cannot read from a file or other source.

Scoring & Submissions

  • This is code golf. Shortest code in characters wins.
  • How to win: post the shortest working code within one week.
  • Please include the language, number of characters, and code. Explanations are appreciated, but not required.

Good luck!

Tags

, ,

Sandbox Questions

Anything I'm forgetting? Does anything need more clarification?

\$\endgroup\$
1
  • \$\begingroup\$ @TNT code-golf, game, card-games. I'll edit my post. \$\endgroup\$
    – Nick B.
    Jul 11, 2015 at 2:54
1
\$\begingroup\$

roll me back a game of hearts

Roll me back a game of hearts
given just a deck of cards
please.

So, I've been playing a game of hearts (https://en.wikipedia.org/wiki/Hearts) with three of my friends but I'm not entirely sure if all of them were playing perfectly according to the rules. So I'd like to replay the game with everyone's cards openly visible. And because you like algorithms, you offered me your help determining everyone's cards from the final deck after each hand. However, I can't quite remember if you promised me a full program or just a named function.

A card is represented with two characters. The first character represents its value and is one of 23456789TJQKA (2-10, jack, queen, king, ace). The second character represents its suit and is one of CDHS (clubs, diamonds, heards, spades).

The input is a list of 52 cards. It can either be a list (array, vector...) of two-character strings or a single space-separated string. You will be given the cards in the exact order they were played. The list represents a valid deck and 2C is the first card in the deck.

Output four sets of cards, each representing the starting hand of one player. The first set may correspond to any player but the rest must be ordered in the order of play (so if the first hand to be output is the third one to play, the rest must be in the order of fourth, first, second). The cards in each player's hand may be output in any order (it's a set). If you choose to output a single string, separate the cards in each hand with spaces and the hands with newlines.

Game rules:

Rules irrelevant to this challenge have been formatted in small font

  • There are variants for three to six players but the base variant is for four players so let's assume this one.
  • Before the main game each player passes three cards to another player. Since this is a lossy operation, let's just ask for the hands after this passing moment.
  • Each game consists of 13 tricks. Each trick consists of each player in clockwise order playing one card from their hand, then one player "taking" the trick.
  • The first trick starts by the two of club. Each subsequent trick is started by whichever player took the previous trick.
  • The first player in a trick can play any card. The first player cannot play hearts unless hearts have already been played in that game or he has no other cards, however. The other players have to play the same suit as the leading player if they have that suit, otherwise they can play any card. Scoring cards cannot be played in the first trick
  • The player that played the highest valued card of the same suit as the leading card of that trick takes that trick. E.G.: in 2C AD KC 5C, the king of clubs takes the first trick. In 2H KS AS QS the leading player takes the trick (and fourteen points).
  • The objective of the game is to end up with the fewest points possible. A player gets one point per each hearts taken, and 13 poins for the queen of spades.

You may assume that the deck of cards is valid (exactly one of each card) and that the two of clubs has been lead. You may also assume that the rules concerning the order of play and trick taking have been followed. You may not assume the rules concerning which cards can be played when have been followed. Heck, you don't even know that I haven't been cheating. Because a player may have been dealt nothing but hearts, you may not even assume only non-scoring cards have been played in the first trick (if everyone on the planet plays 100 games in their life, this may realistically happen to someone).


Should I loosen the I/O requirements? How much?
Formatting advice? Which parts (if any) should I trim down? What needs to be clarified?
Anything else?

\$\endgroup\$
2
  • \$\begingroup\$ So the program you're asking me to write can actually ignore most of the rules of Hearts and I can think purely in terms of a no-trump game in any whist-like game? \$\endgroup\$ Jul 13, 2015 at 12:13
  • \$\begingroup\$ @PeterTaylor Correct. Spades does have trumps, however, and hearts is the only other whist-like game I've played. \$\endgroup\$ Jul 13, 2015 at 12:17
1
\$\begingroup\$

How to Create a Dating Website

Dating websites make lots of money. You want lots of money, so you're going to make a dating website. However, we all know that the most important part of any dating website is the algorithm, so you need to build that first.

When your customers will sign up, they are going to fill out a short survey describing themselves*. On the survey, they filled out personal interests, personality traits, and other important data for you to process using your algorithm.

Your algorithm must then accept two things:

  1. A list of people, where each person has a list of traits
  2. A list of trait pairs (A, B), where each pair has a score S. A trait pair matches a couple if one of them has trait A, and the other has trait B. The score can be negative. If A and B are different, and both people have both of the traits, then the score is doubled.

Your algorithm must then output a list of couples. Each person must be included in a couple exactly once, and only two people is allowed in each couple**. Your score is the sum of each couple's score. A couple's score is the sum of each of the trait pairs they match.

Input/Output

Input is given as shown in the following example. Ignore the # comments

4         # Number of customers
1,3,5,7   # Customer 1's list of traits
1,2,4,5,6 # Customer 2's list of traits
1,6,7     # Customer 3's list of traits
1,2       # Customer 4's list of traits
4         # Number of trait pairs
1,2,-2    # Trait 1 and 2 give a score of -2
1,6,4     # Trait 1 and 6 give a score of 4
2,3,-4    # Trait 2 and 3 give a score of -4
6,6,5     # Trait 6 and 6 give a score of 5

Let's say you output:

2,3 1,4

Then that would match Customer 2 to 3 and 1 to 4.

If we look at 2,3, they match:

  • The first trait pair, because Customer 3 has Trait 1, and Customer 2 has Trait 2
  • The second trait pair, because they both have Traits 1 and 6. (This means double the score)
  • The fourth trait pair, because they both have trait 6. However, because the trait pair only references 1 trait, we don't double the score.

Adding it all up, we get -2 + 4*2 + 5 = 11. The other couple scores -2 + -4 = -6, so the final score is 11 + -6 = 5.

The person who generates the highest scoring pairing wins the challenge. In the case of a tie, the program that generates it the fastest wins. If programs are generating the answer in under a second, then the earliest posted answer wins.

Question: I'm planning on doing 10K people, 500 traits, an average of 50 traits per person, and 5K trait pairs. I'm doing large numbers because I want efficient algorithms, but I want to know if the numbers are feasible

*They clicked a check box saying that they didn't lie, so we know that the survey is accurate

**You can assume everybody is a hermaphrodite

\$\endgroup\$
8
  • \$\begingroup\$ FYI there's a well-known polynomial-time algorithm. \$\endgroup\$
    – feersum
    Jul 13, 2015 at 4:25
  • 1
    \$\begingroup\$ @feersum, that's for weighted matchings in bipartite graphs. This is maximum weight matching in a complete graph, for which the well-known polynomial-time algorithm is Edmond's blossom algorithm. PS Nathan, if you don't want a debate about your cover story, you should probably specify that this dating site is aimed specifically at bisexuals. \$\endgroup\$ Jul 13, 2015 at 6:08
  • \$\begingroup\$ ... or hermaphrodites. Poor snails, perpetually being asked about their gender and not being able to reply "both". \$\endgroup\$ Jul 13, 2015 at 8:31
  • \$\begingroup\$ stdio is a standard header file for input and output functions in the C language. Why is it mentioned in this problem? \$\endgroup\$ Jul 13, 2015 at 10:11
  • \$\begingroup\$ @aditsu STDIO stands for "Standard I/O" \$\endgroup\$ Jul 13, 2015 at 12:39
  • \$\begingroup\$ Yes, and that doesn't change anything I said. \$\endgroup\$ Jul 13, 2015 at 15:14
  • \$\begingroup\$ @aditsu then I don't see your point. I'm describing how to input/output (and giving an example at the same time) \$\endgroup\$ Jul 13, 2015 at 16:51
  • \$\begingroup\$ My point is STDIO specifically refers to the C header file. What you are then actually showing is example input. If it really was stdio, I would expect some C macros and declarations. \$\endgroup\$ Jul 13, 2015 at 17:54
1
\$\begingroup\$

LindenMASM

LindenMASM is an Assembly-like programming language which can be used to generate images from Lindenmayer systems. Lindenmayer systems are very interesting in the fact that they can provide a rudimentary method of generating fractals, such as a Sierpinski triangle. They are also interestingly able to mimic nature very closely for some reason, which can be seen in the below image. You will be implementing a LindenMASM interpreter in a language of your choice.

Understanding Lindenmayer Systems

You should check out the Wikipedia page for a more detailed overview of Lindenmayer systems, as I will simply describe the process of actually using a system. I will be referring to a turtle in this explanation. A turtle is simply the device by which an L-system is drawn. We will use a dragon curve L-system as an example.

Firstly, we need to consider the variables we will be using. In the case of an L-system, a variable is used to control evolution, and does not actually correspond to any movement. We will need two for this, so let's call X and Y our variables.

Next, we would define our constants. In most L-Systems, the character F refers to moving forward, - turns left and + turns right. We will follow these conventions here, and specify that - turns the turtle 90 degrees left and + turns the pointer 90 degrees right.

After this, the axiom needs to be defined. This is the starting point of the system, i.e. what it looks like after 0 iterations. In our case, we will set it to FX.

Finally, we need to define some rules. Rules are applied by going through each character of the axiom, and if one of them matches a rule, replace it with the defined set of instructions. Our rules are that X -> X+YF+ and Y -> -FX-Y. I will show a quick evolution of steps, so you can see how these rules are applied.

  • n=0 - FX
  • n=1 - FX+YF+
  • n=2 - FX+YF++-FX-YF+
  • n=3 - FX+YF++-FX-YF++-FX+YF+--FX-YF+
  • n=4 - FX+YF++-FX-YF++-FX+YF+--FX-YF++-FX+YF++-FX-YF+--FX+YF+--FX-YF+

When this is interpreted, however, since X and Y don't control movement, the interpreted steps for n=4 would look like this:

F+F++-F-F++-F+F+--F-F++-F+F++-F-F+--F+F+--F-F+

Simplified..

F+F+F-F+F+F-F-F+F+F+F-F-F+F-F-F+

Which would result in the following drawing:

n=4 Dragon Curve

Syntax

There are only a few keywords available in LindenMASM which you will need to implement.

  1. STT - Begins every LindenMASM file.
  2. AXI $ - Sets the axiom (initial state) of the system.
    • $ is a series of commands/variables/constants, ranging from the built-ins plus any user-defined functions.
  3. DEG $ - Sets the degree of which all turns will follow.
    • $ will be a integer or float between 0 and 359, inclusive. The default value is 90 otherwise.
  4. MOV $ - Sets the move distance of which all position adjustments will follow.
    • $ will be a integer or float between 1 and 100, inclusive. The default value is 10 otherwise.
  5. INC $ - Sets the number of iterations the generation should go through.
    • $ will be a number between 0 and 30, inclusive. The default value is 0 otherwise. (a value of 0 means just the axiom is displayed).
  6. SET $ # - Sets a constant $ to a specified command #
    • $ will be a letter between A and Z, inclusive, and will be uppercase.
    • # will either be a 0 or a 1, where a 0 corresponds to the constant being one that draws forward, and a 1 corresponds to the constant being one that moves fowards.
  7. RPL $ # - On every iteration, variable/constant $ will be replaced with the command/variable/constant string #.
    • $ will be a letter between A and Z, inclusive, and uppercase. It does not need to be SET to be replaced.
    • # is a string of commands/variables/constants that $ should be replaced with.
  8. END - Ends every LindenMASM file.

Each keyword should be placed on a new line. Your program should fail parsing if (a) The file does not start with STT or does not end with END. Your program should assume that the rest of the keywords will have proper arguments attached to them.

Below is a list of all of the regular commands that cannot be defined by the user:

  1. + - Rotates the pointer to the right DEG degrees.
  2. - - Rotates the pointer to the left DEG degrees.
  3. [ - Saves the pointer's coordinates and heading to a list.
  4. ] - Pops the last value of a list and sets the pointer's coordinates and heading to that.

Examples

I will give 5 examples, each of which will have detailed information on the pattern, plus a link to have it visualized online.

Fractal Tree - n=6, axiom=X, Θ=25, X->F-[[X]+X]+F[+FX]-X, F->FF (Test Online)

STT
AXI X
DEG 25
MOV 10
INC 6
SET F 0
RPL X F-[[X]+X]+F[+FX]-X
RPL F FF
END

Fractal Tree

Gosper Curve - n=4, axiom=F, Θ=60, F->F+G++G-F--FF-G+, G->-F+GG++G+F--F-G (Test Online)

STT
AXI F
DEG 60
INC 4
SET F 0
SET G 0
RPL F F+G++G-F--FF-G+
RPL G -F+GG++G+F--F-G
END

Gosper Curve

Koch Variant - n=4, axiom=F-F-F-F, Θ=90, F->FF-F--F-F (Test Online)

STT
INC 4
RPL F FF-F--F-F
SET F 0
AXI F-F-F-F
END

Koch Variant

Sierpinski Triangle - n=7, axiom=F-G-G, Θ=120, F->F-G+F+G-F, G->GG (Test Online)

STT
RPL G GG
RPL F F-G+F+G-F
DEG 120
AXI F-G-G
SET F 0
SET G 0
INC 7
END

Sierpinski Triangle

Dragon Curve - n=12, axiom=FX, =90, X->X+YF+, Y->-FX-Y (Test Online)

STT
INC 12
DEG 90
AXI FX
SET F 0
RPL X X+YF+
RPL Y -FX-Y
END

Dragon Curve

Input

Aside from the examples given above, your code should support the following test cases as well:

Input:

SET F 0
AXI FF
RPL F F-F+F
END

Output: Error: No STT at beginning.

Input:

STT
SET F 0
AXI FF
RPL F F-F+F

Output: Error: No END at ending.

Output

Your program should output the resulting image by outputting an image or by drawing to the screen (e.x. turtle graphics). If you would like to check out a Python 3 example, here is a Github link to pylasma.


This is , so least number of bytes wins.

\$\endgroup\$
6
  • \$\begingroup\$ Why is "turtle graphics" in particular mentioned? Why not any other method of drawing to the screen? \$\endgroup\$
    – feersum
    Jul 14, 2015 at 3:40
  • \$\begingroup\$ @feersum My intent was to say that, at the time of writing I didn't know how to word it, I was very tired :P \$\endgroup\$
    – Kade
    Jul 14, 2015 at 11:04
  • \$\begingroup\$ Do any of the commands accept floating-point arguments? \$\endgroup\$
    – feersum
    Jul 14, 2015 at 14:41
  • \$\begingroup\$ @feersum MOV and DEG are the only two which should support floating-point arguments. I'll update. \$\endgroup\$
    – Kade
    Jul 14, 2015 at 14:44
  • \$\begingroup\$ This is pretty close to codegolf.stackexchange.com/q/9341/194 . The bit that's different is parsing the input, so if you want to make an original question then you could restrict it to validating that a file obeys the structure rules (although I must say that I find "$ ... will be one of the variables within #" overly restrictive). \$\endgroup\$ Jul 14, 2015 at 18:42
  • \$\begingroup\$ @PeterTaylor Just my opinion, but validating a text file is much less exciting than the question I'm posing :P I'd rather just scrap this. \$\endgroup\$
    – Kade
    Jul 14, 2015 at 20:50
1
\$\begingroup\$

Print time of day using words

I'm not sure if this has been done before. I thought it must have but I could not find one using search. The idea is basically, given a number in seconds, e.g. the output from time(NULL). Return the current time in words using 12 hour clock, e.g.

HALF PAST FIVE PM
A QUARTER TO SIX PM
TEN TO SIX PM
SIX O'CLOCK PM
SIX TEN PM
TWELVE NOON
TWELVE O ONE AM

Has this challenge been done before?

One thing I cannot decide is when the "PAST" should be used. Should it be used only when there is less than 15 minutes left? Should it be FIVE FIFTY FIVE or FIVE TO SIX?

\$\endgroup\$
5
  • \$\begingroup\$ It doesn't matter too much which approach you choose as long as you define it clearly so there is no doubt which way is the correct way for your question. I'm guessing using PAST and TO would make it a slightly more challenging/interesting golf. \$\endgroup\$ Aug 4, 2015 at 0:43
  • \$\begingroup\$ Yes, I want it to be a 12 hour clock. As humanly as possible. I think I should add AM and PM to the answer. Possibly even NOON. \$\endgroup\$
    – some user
    Aug 4, 2015 at 0:49
  • \$\begingroup\$ Yes it's a tricky system. Just keep editing to clarify edge cases until the comments stop coming in :) \$\endgroup\$ Aug 4, 2015 at 0:55
  • \$\begingroup\$ This is essentially It's Spanish Time! in a different language. \$\endgroup\$
    – Dennis
    Aug 8, 2015 at 4:40
  • \$\begingroup\$ You have three options. 1. use only the digital times, like FIVE FIFTY FIVE (boring in my opinion) 2. use the word based system, TWENTY TO FIVE (the changeover occurs between 30 and 31 past the hour) 3. use word based system for the 15 minute intervals (half past, quarter past/to and o'clock.) Whatever you do, be very clear about what's required acceptable and what is not. For me 12 noon is PM. If you require NOON you should require MIDNIGHT also. Other things like the A in A QUARTER and the O in TWELVE O ONE AM should be spelt out in detail in the specification. \$\endgroup\$ Aug 10, 2015 at 0:41
1
\$\begingroup\$

Maze to regex

Suppose we have an ASCII maze like so:

#######
#s# # #
# # # #
#     #
# ### #
# #  e#
#######

The input maze will have the following properties:

  • One cell (marked s) will denote the start of the maze, and a separate cell (marked e) will denote the exit.

  • The walls will be denoted by hashes #, and empty corridors will be denoted by spaces.

  • The maze will be a perfect rectangle, have no cycles, and will consist of exactly one connected component (i.e. all cells will be reachable)

A single character from NSEW represents a move North, South, East or West respectively, and consists of moving two characters in the specified direction. For instance, the above example is a 3 by 3 maze where the following cells can be occupied:

#######
#x#x#x#
# # # #
#x x x#
# ### #
#x#x x#
#######

A string consisting of NSEW is said to solve a maze if applying each move in turn results in the exit being reached at some point in time, regardless of whether the string continues on afterward. If a move is blocked by a wall, the move is ignored and no movement occurs.

Example strings which solve the above maze are SEES, SENSES and SSSSSNENNNNNSENNNNNSSSSSSSSWW.

The challenge

Your task is to write a program or function which takes in an ASCII maze and outputs a regex. The regex must match a string of NSEW if and only if it solves the given input maze.

For instance, all solutions to the 2 by 2 maze

#####
#s#e#
# # #
#   #
#####

can be encapsulated by the regex

^(([NEW]|S[WS]*N)*S[WS]*E([ES]|W[WS]*E)*W[WS]*N)*([NEW]|S[WS]*N)*S[WS]*E([ES]|W[WS]*E)*N[NEWS]*$

(Try it online at Regex101)

Available features

You may only use the following regular expression features:

^$         Start and end anchors respectively
N|E        Alternation
NE         Concatenation
()         Grouping
*          Repetition (0+ times)
+          Repetition (1+ times)
?          Optional (0 or 1 times)
[NESW]     Character classes (but not negated classes)

In particular, recursion, wildcards, lookaheads and other unlisted features are not allowed.


Sandbox questions:

  • What would be better, (scoring by providing a few test mazes, and taking the sum of output regex lengths) or (any output regex is okay as long as it is finite and correct)?

  • I've chosen this ASCII representation because it looks the nicest, but I'm not sure if it's the most convenient. I'm open to suggestions for alternatives.

  • What is the best way to test submissions? I can write a bunch of test cases per maze, but it's impossible for me to test an infinite number of strings.

\$\endgroup\$
4
  • \$\begingroup\$ Is it guaranteed that there will never be a wall in a position that permits a move of only 1 step instead of 2? Or should such cases be simply treated as no move possible? \$\endgroup\$ Aug 10, 2015 at 17:02
  • \$\begingroup\$ What range of maze sizes must this work for? \$\endgroup\$ Aug 10, 2015 at 17:03
  • \$\begingroup\$ If you don't have an automated way of checking submissions, you could announce one of "innocent until proven guilty" or "guilty until proven innocent". Either answers require a proof, or answers are assumed to be valid until someone proves otherwise. \$\endgroup\$ Aug 10, 2015 at 17:06
  • \$\begingroup\$ @trichoplax I'll work on the maze definition later, but the input is guaranteed to be valid. Maze size would have to depend on if this is golf (which would probably have a larger limit) or metagolf \$\endgroup\$
    – Sp3000
    Aug 11, 2015 at 1:46
1
\$\begingroup\$

Be Rational! Finding Rational Roots of Polynomials


In this challenge you are to find all rational zeroes of a polynomial. The results have to be exact. I would suggest using The Rational Root Theorem.

Input


Input can be through function argument, command argument, or user input. Input will be a polynomial. The polynomial may have rational coefficients. If a term has a coefficient of zero, that term will not be included in the input. x^1 will be abbreviated as x.

Examples:

-x^7+4x^4/7-21x^2/2+5x+23/19
...//More to be added when posted

Output


Output will be a list of the rational roots of the input polynomial. Output can be through function return value or stdout. If output in string format, you will use improper fractions separated by commas. The output must be simplified as much as possible. Duplicate roots should not be printed more than once.

Examples:

4/5,2/3,-15/2
...//More to be added when posted.

Example Cases

> x^2-1
1,-1
...//More to be added when posted.

Just like all questions, the answer with the lowest byte count wins.

Questions:

Is this too much like Peter's earlier question?
Are there any points I haven't covered or are not clear?
Any grammar/spelling mistakes?
Any tips on improved formatting?

\$\endgroup\$
2
  • \$\begingroup\$ Somewhat related question \$\endgroup\$
    – Sp3000
    Aug 17, 2015 at 2:01
  • \$\begingroup\$ The title is one character shy of the minimum title length and "abbreviate" should be "abbreviated." Can the roots be listed in any order? Do they have to be fully reduced or could we, for example, use 2/4 in place of 1/2? I would also suggest rewording "fractional coefficients" to "rational coefficients." \$\endgroup\$
    – Alex A.
    Aug 17, 2015 at 2:38
1
\$\begingroup\$

Rec(ursion)less execution

We have a simple (non-Turing complete) language.

Each line of program is a set of terms separated by single space. Some of terms (ending with ()) are function calls. Some lines (whose first term ends with :) are function definitions. The lines that are not function definitions are called expressions.

This is a sample program:

funa: one two three
funb: funa() four oclock rock
here we go funb()

Here we have two function definition lines and one expression line.

And this is BNF for this language just for clarity:

literal ::= [any printable char other than ' ', ':', '(', ')']+
function_header ::= literal ':'
function_call ::= literal '()'
term ::= literal | function_call
expression ::= term | expression_list ' ' term
function_definition ::= function_header expression

program_line ::= function_definition | expression
program ::= [program_line '\n']+

The task is to write a program or function that validates the program P and performs EXECUTE(P) if the program adheres to validation rules.

Validation rules:

  1. EXECUTE(P) eventually stops (it's not Turing complete - enough to check if one of the called functions would eventually cause itself to be called - either being recursive itself or "mutually recursive" with other function it calls),

  2. while calling EXECUTE(P) -> EXECUTE_LINE(P,L), each function definition search succeedes (in other words - the program will not try to call undefined function).

If program does not pass validation rule 1 or 2, ERROR: RECURSIVE FUNCTION or ERROR: UNRECOGNIZED FUNCTION should be printed respectively.

When both rules seem to be violated, assume that search for undefined function causes the algorithm to fail (stop) instantly, so recursion that would occur later if the function was found, is not reported. We only report ERROR: UNRECOGNIZED FUNCTION in this case (see Example 5 below).

In similar way, if recursion prevents a call to function that would not be found otherwise, even though the function containing call to unrecognized function is called only ERROR: RECURSIVE FUNCTION is reported (see Example 4 below).

If validation does not report any of those two errors, EXECUTE(p) should be called.

Executing a program is defined like this:

EXECUTE(P)
  - for each line L in the program P:
     - if L is not a function definition EXECUTE_LINE(P,L)

EXECUTE_LINE(P,L)
  - for each term T in L:
      - if T is a literal
          print T followed by single space
        else
          FH = T without '()' + ':'
          FDL = find in P a line starting with term FH
          FD = all terms of FDL after FH
          EXECUTE_LINE(FD)
          

Example 1:

a: b()
b: a()
c: cucumber
other: nofun()
d: apple banana and c()
we have d()

Output:

we have apple banana and cucumber

Note, that in spite of existence of mutually recursive function definitions a and b and function definition other calling undefined function nofun error was not raised, because execution never goes to any to this functions.

Example 2:

other: nofun()
c: apple banana and cucumber
we have other()

Output:

ERROR: UNRECOGNIZED FUNCTION

Example 3:

a: b()
b: a()
c: apple banana and cucumber
we have b()

Output:

ERROR: RECURSIVE FUNCTION

Example 4:

a(): a() nofun()
hello a()

Output:

ERROR: RECURSIVE FUNCTION

We don't output ERROR: UNRECOGNIZED FUNCTION, because the program would never try to execute nofun, recurring infinitely into first term of definition of a.

Example 5.

a(): nofun() a()
hello a()

Output:

ERROR: UNRECOGNIZED FUNCTION

We don't output ERROR: RECURSIVE FUNCTION here, because the program would fail to find definition for nofun before even tring to recurse into a.

Accepted solution: a function or a program that takes a program in the above-defined language, validates and runs it. You can assume that program has already been split into single lines, however you can use raw input or accept program as single string when convenient.

This is code-golf, so the shortest submission in term of bytes will win. However, all working submissions in all languages will be appreciated.

\$\endgroup\$
2
  • \$\begingroup\$ The two rules seem to be inconsistent: the first one prohibits the recursive function f: f() even if f isn't called; and the second prohibits the function which calls an undefined function f: fail(), but only if f is called. It would be less confusing to make them both syntactic (based on the text of P) or both semantic (based on the execution of P). \$\endgroup\$ Aug 22, 2015 at 7:35
  • \$\begingroup\$ @PeterTaylor I didn't mean to prohibit existence of recursive functions that are not called, this was my description that was not precise enough. I clarified the description and added some more examples. So now, both rules are based on execution of P rather than text of P. \$\endgroup\$ Aug 22, 2015 at 8:57
1
\$\begingroup\$

Triple Triad Tournament!


(anything in italic parenthesis is a note for the sandbox)

About Triple Triad

Triple Triad is a card game from the Final Fantasy series. I've never played a FF game that included it, though, so I'm only familiar with the version in the Pokémon fangame Pokémon Insurgence. It may or may not be different than the original version, so apologies in advance if this isn't quite what you're expecting. :)

In Triple Triad, each card has 4 numerical stats that range from 1 to 10*: An "up" value, a "left" value, a "right" value, and a "down" value. Here's an example of a card with an "up" value of 1, a "left" value of 6, a "right" value of 3 and a "down" value of 2:

Triple Triad Rules

At the beginning of each game, players construct a "deck" of five cards, chosen from their entire collection. These cards are kept secret from the other player.

Triple Triad is played on a 3x3 grid. Players take turns choosing a card from their deck and placing it on an empty square of the grid. The goal of the game is to control the majority of the cards when the grid is filled. When the game is complete, one card is randomly selected from the loser's deck and given to the winner.

Control

When a card is placed on the grid, it is controlled by its owner. In order to come out of the game victorious, you must gain control of cards that the opponent played.

To gain control of an opponent's card, you must place a card of your own that "beats" it adjacent (not including diagonals) to the card you want to take control of. Whether or not your card beats the opponent's depends on their stats and which side you place your card on.

Imagine this board as the current game state and the blue card as a card in my deck:

If I want to take control of the opponent's Numel, I have to place my Mareep adjacent to it. This leaves only two options: The top middle square or the middle right square. If I were to place it on the top middle square, my card would be to the left of the opponent's. As a result, Mareep's "right" value of 2 would be contested against Numel's "left" value of 4. 2 is not greater than 4, so my opponent would retain control of Numel. Note that my value must be strictly greater; a tie would be the same as a loss.

If I were to place my card in the middle right corner, it would be below the opponent's card. As a result, Mareep's "up" value of 4 would be contested against Numel's "down" value of 3. 4 is greater than 3, so I would gain control of Numel (which would turn blue to indicate that).

This process is applied in all four directions at once. If there was a card below Mareep with an "up" value of 1 or 2, I would gain control of it as well. However, gaining control is not done passively or recursively. Control can only be contested at the exact moment a card is placed, and gaining control of a card does not count as "placing it".

Tournament Rules

Each bot is given a budget of (TBD) with which to purchase cards before the tournament (this will be done by the author, not the bot itself, and will be hardcoded into the bot). Here are the cards, along with their costs:

There - 1000
 will - 1500
   be - 1500
    a - 2500
 list - 3000
 here - 4000

The bots will play in a Round Robin tournament with Bo3 matches (subject to change. not sure if round robin will work well or if i should be using Bo5 or what). The bot that wins the most matches will be declared the winner.

Match Procedure

  1. Each bot chooses 5 cards from their collection to create a deck. (If they have less than five cards, they forfeit the match.)
  2. The game is played as described above, until the board is filled. (i'm not sure how to decide who should go first. alternate? winner of the last game? loser?)
  3. When the game is complete, a random card from the loser's deck is removed from their collection and inserted into the winner's collection. (At the end of the match, each bot's collection is reset to its original state.) (i'm not totally sure about choosing a random card. it's how the original game works, but it's not necessarily 100% fair. the idea is that over the course of a round robin tournament, any RNG variance will be smoothed out, but i don't know...)
  4. Repeat steps 1 through 3 until one bot has won 2 games.

Input / Output Specifications and Controller Details

(none yet lmao)


* The Insurgence variant has some nonsense regarding Pokémon types at higher difficulty levels, but this challenge will ignore that.

\$\endgroup\$
2
  • \$\begingroup\$ Your mention of excluding recursive moves makes me wonder what the game would be like including recursion, on a much larger board... (perhaps as a separate KotH) \$\endgroup\$ Sep 1, 2015 at 14:34
  • \$\begingroup\$ Choosing a random card for the winner will introduce unfair variation in a single round robin, but I think that's worth it for the increased variety of games that will test strategies more thoroughly. As long as you don't mind running the round robin multiple times until it converges on a fair score, I would keep the random element. \$\endgroup\$ Sep 3, 2015 at 7:23
1
\$\begingroup\$

Is a point inside a polygon?

Given the polygon with 2 < N < 11 sides, on 2D plane, find out if a given point is inside the polygon.

The input can be an array of points in x, y, each determining a vertex, or by a string in format X Y x1 y1 x2 y2 ... xN yN (you may choose other separator). The X and Y are the coordinates of the point to be tested. The list then contains N verices, and the last point is connected to the first point. All x and y are integers.

Using any built-in functions performing the test is prohibited (like this one)

You should consider that a point is inside a polygon also when it is one of its vertices or it lies on one of its edges.

Notes

  1. Tags would be and
  2. Should max x and y be determined?
  3. Should they be positive (uint) values only?
  4. Some questions of this type have already been asked on StackOverflow (example 1, example 2). Is it ok to ask this question here? (I didn't find it)
  5. Should the question also allow non-convex polygons? A non-convex (concave) is a polygon which has at least one of its angles larger than 180 deg., and can borders intersect? (I think it can be too complicated and in my opinion it should be for convex polygons only).
\$\endgroup\$
2
  • \$\begingroup\$ The question should definitely allow non-convex polygons, but if it allows self-intersection then you'll need to pick a winding rule and explain how it works. \$\endgroup\$ Sep 8, 2015 at 19:58
  • \$\begingroup\$ Be aware that some of the answers here generalize to polygons. \$\endgroup\$
    – xnor
    Sep 12, 2015 at 18:57
1
\$\begingroup\$

Literal Fourier Transform (or Fouriest Numbers?) Dupe

(inspired by this Saturday Morning Breakfast Cereal comic)

It's called a fourier tranform when you take a number and convert it to the base system where it will have more fours, thus making it "fourier". If you pick the base with the most fours, the number is said to be "fouriest."

Goal: Given a positive integer n in base 10:

$$ 4 \le n_{10} \le 2^{31} -1 $$

Write a function that displays its equivalent in another base in the format below that maximizes the number of 4s, i.e. the fouriest:

Base x; Fouriest y

Notes:

  1. If multiple bases tie on the number of 4s, any base will be accepted. E.g. if the input has the fouriest value already, it's fine to return/display the input.
  2. Numbers may not necessary yield a 4, see last example below.

Examples:

  • (from comic) 624 -> Base 5; Fouriest 4444
  • 2316780 -> Base 14; Fouriest 444444
  • 4 -> Base 10; Fouriest 4
  • 5 -> Base 10; Fouriest 5

Bonus:

  1. Have your function accept a second argument m for the input base: 1/4 reduction in submission size.

Winning:

Shortest code in bytes wins.

This is .

\$\endgroup\$
7
  • \$\begingroup\$ If two different bases give the same number of 4s, can either be chosen? \$\endgroup\$ Sep 8, 2015 at 7:18
  • \$\begingroup\$ @trichoplax yes, I think that'll be an extension of point 1 under "Notes". :) \$\endgroup\$
    – h.j.k.
    Sep 8, 2015 at 7:22
  • \$\begingroup\$ I'm not personally a fan of bonuses (I prefer just one well defined objective), but if you choose to have a bonus it might work better to make it a percentage reduction instead of a number of bytes. Otherwise the bonus has very different effect on different languages. \$\endgroup\$ Sep 8, 2015 at 7:38
  • \$\begingroup\$ P.S. With or without a bonus, I think this is a brilliant challenge. \$\endgroup\$ Sep 8, 2015 at 7:42
  • \$\begingroup\$ @trichoplax along the lines of everything-to-do-with-four, I was thinking of shaving 1/4 for the bonus component, but then I'm not too sure if that's too much. :p I guess I can still consider that... while awaiting for other suggestions. :D \$\endgroup\$
    – h.j.k.
    Sep 8, 2015 at 8:01
  • 1
    \$\begingroup\$ Dupe \$\endgroup\$ Sep 8, 2015 at 13:32
  • \$\begingroup\$ @PeterTaylor thanks for pointing that out! I wouldn't be posting this then. It didn't mention "fourier", which explains why it slipped through my search for posted questions. \$\endgroup\$
    – h.j.k.
    Sep 8, 2015 at 14:23
1
\$\begingroup\$

Find all matchings

Golf this SO question in any language. Fewest bytes wins.


Given two equal-size sets of positive integers,

A={3,1,5}
B={2,4,3}

a matching pairs up elements from each set, like:

{(5, 2), (1, 4), (3, 3)}

There's one matching for each permutation of n elements, where n is the size. Your goal is to print or return all the matchings.

{(3, 2), (1, 4), (5, 3)}
{(3, 2), (1, 3), (5, 4)}
{(1, 2), (3, 4), (5, 3)}
{(1, 2), (5, 4), (3, 3)}
{(5, 2), (3, 3), (1, 4)}
{(3, 4), (1, 3), (5, 2)}

Input: Two nonempty equal-size collections (lists, arrays, sets) of positive integers. Numbers won't repeat within a collection, but may overlap between them. If your collection is ordered, you may assume it to be sorted.

Output: Print or return all possible matchings.

Each matchings must appear exactly once, in any order. They must be somehow grouped or separated, so you can tell where each one beings and ends. These rules also apply to the pairs in each matching.

Banned: Built-ins that generate matchings or permutations.

\$\endgroup\$
1
\$\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\$
4
  • \$\begingroup\$ I think 10 is good, as it encourages users to be ever more creative with each function. \$\endgroup\$
    – mbomb007
    Sep 10, 2015 at 20:44
  • 2
    \$\begingroup\$ "Doing something meaningful" is very hard to make precise. \$\endgroup\$ Sep 10, 2015 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, 2015 at 21:29
  • \$\begingroup\$ @ThaddeusB Great idea. +1 \$\endgroup\$
    – user42643
    Sep 16, 2015 at 3:21
1
\$\begingroup\$

I have an idea for a challenge but I'm not sure if it would be best as a or , I'm also not sure what rules I should apply to make it more interesting.


"Convert an image to LEGO safe-colours"

The task is to convert the existing colours from a JPEG image into LEGO-safe colours.

What are LEGO-Safe colours?

For the purpose of this challenge, LEGO-Safe colours are defined as the seven oldest solid colours produced by LEGO that are still in production. (The exception being grey which has changed in recent years, for the purpose of this challenge, the original grey will be used).

The colours are hexadecimal approximations from this list.

White, #f2f3f2
Grey, #a1a5a2
Black, #000000
Bright Red, #c4281b
Bright Yellow, #f5cd2f
Dark Green, #287f46
Bright Blue, #0d69ab

Images

You may demonstrate your results using images provided by yourself or the ones shown below.

Lego Factory (Colour)

enter image description here

Lego and Duplo Bricks (Greyscale)

enter image description here

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Dupe \$\endgroup\$ Sep 18, 2015 at 14:27
  • \$\begingroup\$ @PeterTaylor Bummer \$\endgroup\$
    – Ambo100
    Sep 19, 2015 at 9:26
1
\$\begingroup\$

Another cake question - Share it fairly!

I'm having a party, and there were going to be 8 of us. As I like to cut the slices of cake fairly, I normally get a round cake and make the cuts with the help of a protractor (any code golfer would!) But this time I found the bakery were making octagonal cakes, so I bought one of these to help me with my cutting.

The problem is, now there are only 7 of us! Some people are so inconsiderate, dropping out at the last minute! How am I going to cut the cake fairly now?

Well it turns out that at https://puzzling.stackexchange.com/a/18244/4768 they have the answer. Although my protractor is no good, it's still true that if I start my cuts at evenly spaced points on the perimeter of the cake and end at the centre, all the slices will be of equal size and have an equal area of icing. This is very important. This is quite easy to prove for cakes in the shape of any regular polygon, using the fact that the area of a triangle is base*height/2.

I need you to write me a program or function to show me how to cut my cake.

The code will take 2 inputs: the number of edges on the cake (3 to 15) and the number of pieces to cut it into (3 to 40).

It will output a diagram showing the cake (a regular polygon) and the positions where the cuts are to be made (lines radiating out from the centre to equally spaced points on the perimeter.)

Some examples are shown below. Note for example that for the case 3,9 the slices are all equal size, but the angles at the centre of the cake are not.

You can orient the cake any way you like, but one of the cuts has to pass through a vertex for easy comparison of answers.

enter image description here

Scoring: this is code golf. Shortest code in bytes wins.

\$\endgroup\$
1
\$\begingroup\$

Strata

Strata is a puzzle game in which you lay coloured ribbons across a grid. When two ribbons intersect, the cell under the intersection takes on the colour of the uppermost ribbon. Here's an example puzzle, ready to solve:

After laying the first ribbon, no cells have been assigned a colour yet:

Empty example puzzle

Laying a perpendicular ribbon colours a cell in:

Example puzzle with one ribbon

Notice that, if the uppermost ribbon isn't the correct colour, the cell isn't filled in to let you know you've got it wrong. Also, if a cell doesn't have a target colour, it doesn't matter what colour ends up on top of it; the cell remains colourless when the second ribbon is laid across it:

Example puzzle with four ribbons

And a completed solution:

Completed example puzzle

The Challenge

The object of this challenge is to write a program or function that will provide a step-by-step solution for a Strata puzzle. Here is the layout for the example puzzle provided above, rotated 45 degrees clockwise and with letters a-c substituted for the cell colours:

 ba
ab 
a c

For ease of the following discussion, I've labelled the columns 1-3 and the rows A-C.

  ABC
 +---
1| ba
2|ab 
3|a c

The notation for the output commands will be a single character representing the row or column to lay a ribbon upon, and then another character representing the ribbon type. For example, the command Cb represents laying a ribbon of type b on the rightmost column of this layout.

One of a number of valid solutions for this puzzle is 3a, Cc, 1a, 2a, Bb, Aa. Another is Ca, 3c, 2a, 1a, Aa, Bb.

Input

Input will consist of the layout for a Strata puzzle. The puzzle will always form a square, with side length of 2-9 inclusive. Each character in the input will be one of the following:

  • a lower case letter, representing the ribbon type which should be laid on top of the intersection in the completed puzzle
  • a space, representing a cell where the type of the uppermost ribbon does not matter

Note that a puzzle can use between 2-26 (inclusive) ribbon types, and that the types will not necessarily a the first nth letters of the alphabet. Your program/function won't be provided these separately, and should be acquired from the puzzle layout if required.

Input may be provided in any reasonable form that is convenient for your chosen language. For example, you may accept input as single newline-delimited string, as an array or list of strings, etc. Please provide a description of how your submission will expect its input for testing purposes.

Similarly, input can be provided in any appropriate manner. For example, as command line arguments, function arguments, as a stream via STDIN, etc. You should only specify this if it is not immediately obvious.

Output

Output should consist of a valid solution for the given puzzle. It should consist of an ordered series of instructions, each consisting of two characters:

  • The first character should be a number or upper case letter; a number represents a row, starting with 1 for the uppermost row, a letter represents a column, starting with A for the leftmost column (e.g., in the puzzle above, the instruction 4a would be invalid as there are only 3 rows)
  • The second character should be the type of the ribbon to lay on the grid; this should be a lower case character, corresponding to one of the types provided on the input (e.g., in the example puzzle above, the instruction Az would be invalid as z is not one of the types used in the grid)

Your program/function can provide the output pairs in any reasonable form, and on any reasonable medium. For example, as a series of comma, space, or newline separated values on STDOUT, as an array for return from a function, written to a file with specified name, etc.

Other Rules

  • A puzzle is only considered complete when all rows and columns have had a single ribbon laid across them, and no row or column can have more than one ribbon laid on it. This means that your output will consist of 2 * (side length) instructions.
  • This is code golf, so the winner is the shortest solution in bytes. In the event of a tie, the earliest submission wins.

Test Cases

Input:

 ba
ab 
a c

Possible output:
3a, Cc, 1a, 2a, Bb, Aa

Sandbox comments:

This is my first PPCG question, so I tried to make sure every angle was covered. I think I may have gone overboard though, do you think I should get rid of any sections?

As this isn't a puzzle of my own invention, would there be any problems with posting in-game screenshots?

This puzzle is actually pretty easy to work out if you employ a backtracking technique - find a row or column consisting of a single colour, ignoring spaces and cells which have been crossed once. Add this instruction pair to the end of the prototype solution, then mark all the cells as having been crossed once (or twice). Repeat this 2 * (side length) times and you'll have a solution, if there is one to be found.

I want to discourage brute force solutions, so I'm going to come up with a 9x9 test case with more than 10 different types. My stats skills aren't up to much, but I think that, for a puzzle with side length n and number of ribbon types t, the total number of possible ways to lay ribbons on the grid is:

(2n)! * (2n)^t

Could anyone double check that for me? Also, if I were to put in a 9x9, 10-type test case, would that be big enough to rule out a brute force solution? Should I impose some form of computation time limit, and if so, how long on what sort of machine?

\$\endgroup\$
3
  • \$\begingroup\$ @trichoplax There is indeed a solution which is significantly faster than brute force, which is as described in my comments. For a puzzle of side length n, it requires exactly 2n iterations to find a solution if one exists, and requires a maximum of [the (2n)th triangle number] row/column inspections in the worst case scenario. I can add a discussion of this to the main body of the challenge, but I'm worried that it's already too long! \$\endgroup\$
    – Sok
    Sep 22, 2015 at 11:32
  • \$\begingroup\$ I misread that part and thought that was the brute force solution - but I can see now that it is much faster - I'll delete my irrelevent comment... \$\endgroup\$ Sep 22, 2015 at 11:37
  • \$\begingroup\$ I confirm your count for a really brute force solution. It's possible to optimise slightly by observing that if there's a sequence of parallel ribbons then the order in which they're placed is irrelevant. \$\endgroup\$ Sep 23, 2015 at 20:26
1
50 51
52
53 54
152

You must log in to answer this question.

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