What is the Sandbox?

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

To post to the Sandbox scroll to the bottom of this page and click "Answer This Question". Give the details of your challenge just as you would when actually 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 mark it as posted here.

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

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

Submission Directory

This is a community-maintained list of the most active Sandbox submissions, sorted by major contest type. Add an entry to the top of this list if you add a new submission or update an old one. If you don't have enough reputation to edit questions you can ask in chat for a higher-rep user to add your submission for you. You may include a [status] indicator and tags to categorize your submission.

If this list grows too long you may remove entries that have been inactive for several days. It's best to remove submissions from this list once they've been posted to the main page.

code-golf

king-of-the-hill

Others

share

528 Answers 528

Nonogram it

Nonograms are one of my favorite types of puzzles, but sometimes there are not enough of them to solve!

The challenge here is to write a program that would take an image and output the values for the columns and rows of the puzzle.

INPUT: black and white PNG on STDIN

OUTPUT: two lines with the values to create the puzzle. First line is the columns, second the rows. The format of both lines is: [a,b,c...],[d,...],... (lists of integers separated with commas delimited with [], with each list separated by commas, ending in a newline. No dangling commas allowed inside the lists or at line end)

The squares on the image should be of 5x5px. The thereshold for determining if a square is filled is if it has at least 30% black inside it.

(3 sample images will be added later)


I'm not sure about the scoring for this challenge, most likely it should be a .

Additional scoring criteria I can think of:

  • allowing to enter square size or cols*rows of the puzzle.
  • accepting non black and white images
  • reading other image types
  • providing a solver
share
1  
wait, is the PNG itself in the STDIN, or a file path to it? I assume the latter, but it's currently formulated as if it's the former. Also, the threshold needs to be clarified. Also, why is the image scaled up in the first place? –  Jan Dvorak Mar 26 at 19:59
1  
Also, I'd prefer an ascii-art input (a grid of hashes and spaces) than having the challenge complicated by looking up and interfacing an image manipulation API. –  Jan Dvorak Mar 26 at 20:02
1  
I don't think a PNG library showoff is a good challenge for this site. There's no thinking present, just having to learn an API and hope it has short enough names. –  Jan Dvorak Mar 27 at 15:45
1  
I don't understand the 5x5 rule. Is it that there are 5x5 pixels in the image, and 5x5 pixels in the grid? 5x5s are no puzzles. –  Jan Dvorak Mar 27 at 15:46
1  
Seeing that you prescribe exactly how black and white cells are to be determined, unique solubility of the resulting nonogram is no criterion? –  Martin Büttner Mar 31 at 11:28
1  
@Einacio well, uniqueness could be checked with a solver (there might be easier ways). I suppose you just have to decide whether you want soluble or comparable answers. If you are going for soluble, you can make this a "code challenge" and determine the score based on both code length and similarity to input image. –  Martin Büttner Mar 31 at 14:58

Solve the Global Debt! {POSTED}

share

Find words in word square solver

On social media I often see images with letters and in them are some positive words for people to find. I challenge you to write a program that finds all words in the puzzle that matches a input dictionary. An example of such puzzle is this one:

A letter square

An ASCII representation I made of this:

XCUALOVEYKBWSNG
DUAWKCBEAUTYRJV
YOUTHFSMGNEZLPR
MHJREYWDKZLUSTJ
FSUCCESSDHEALTH
ENMQXPTIMELMSAQ
VEXPERIENCEGHBW
GHUMOURLOYMONEY
SYZPOPULARITYNA
AMKCFUNBXHUZYIX
CWIHYSHAPPINESS
HONESTYCFRIENDS
KPYJAETWPOWERQC
BTYACFREEDOMJMO
RIWINTELLIGENCE

Now I imagine we can find words horizontally, vertical and diagonal and all of the mentioned in reverse. The program must be able to take a square and a dictionary like this one and print all the matching words.

As a test case I give custom dictionary:

bar
bid
dir
dog
fad
fed
foo
god
man
mod
set
sun

And a test square:

OGFIR
DOMAN
ODBID
OPGES
OGFIR

Your code should be able to print all but the two last words in the dictionary. For diversity you should specify how the cube and the dictionary is bo be entered.

This is so shortest code wins.

share
3  
Cube? I'm only seeing two dimensions. On a more general note, perhaps for questions of this sort it would be OK to assume the availability of a standard dictionary file like /usr/share/dict, and discount the characters used to access this file? What do people think? –  squeamish ossifrage Apr 3 at 15:55

Code-Golf: Creating a Befunge-93 interpreter

EDIT: There already is a challenge like this. I'll not post my challenge because there already exists one.

share
1  
BF93 bootloader = nested loop with file input, some simple logistics and a single BF98-only command. I still want to see it done, and I'm willing to try. –  Jan Dvorak Dec 21 '13 at 11:14

Collatz ...something

The Collatz conjecture states that every natural number n leads to the number 1 if the recursive function f(n) is applied to it defined as

f(n)=n/2    if n is even
    =3n+1   if n is odd

Let "ai" be the value of f applied to n recursively i times so that a0 = n , a1 = f(n) , a2 = f(f(n)) ... ai = f(ai-1)

Let A be the set {a0, a1, ..., 1}

Thus, for n=10, we get the sequence

a0 = 10 --> a1 = 5 --> a2 = 16 --> a3 = 8 --> a4 = 4 --> a5 = 2 --> a6 = 1

and the set A as A = {10,5,16,8,4,2,1}

Your task is to write a function/program that will accept a set of naturals say I. You must output a set of numbers say C such that I is a subset of the union of the sets A for all numbers in C.

Rules

  • Network access is forbidden
  • Any of the standard loopholes are forbidden
  • Your program must end in less than 200 seconds. You may assume that all the input terms are less than 2^(45); however note that the individual terms of the collatz sequence can go higher.

Input

  • List/array of naturals in I as an argument to a function
  • , or space or \n separated naturals in I on STDIN

Output

  • return a list/array/set of all naturals in C
  • print all the naturals in C separated by \n

Scoring

Your score is calculated as

( ( (10)^(number of elements in C) ) * (sum of all elements in C) ) + ceil( 100*log(total number of bytes of your code) )

log() is the natural logarithm

Lowest score wins.

Examples

Input:

I = { 16 , 32 , 40 }

Possible outputs along with the score

C=                   Score

{ 16 , 32 , 40 }     ((10)^(3))*(16 + 32 + 40) = 8000   + constant
{ 32 , 40 }          ((10)^(2))*(32 + 40)      = 7200   + constant
{ 32 , 13 }          ((10)^(2))*(32 + 13)      = 4500   + constant --> most optimal         
{ 1024 , 320 }       ((10)^(2))*(1024 + 320)   = 134400 + constant
... Infinitely many higher numbers    

where constant is ceil(100*log(code length))

In this case, the answer { 32 , 13 } is the most optimal.


Note: This is NOT code-golf even though the length of your program is considered. Please also provide a readable version.

I'm being flexible with the I/O so that the more verbose languages might get some benefit. You can write a complete program or a function or a lambda function. It is not required that your function(if you choose to write one) returns. Using a function for input while printing the output is fine if that makes the code shorter.


This will be tagged as


Sandbox feedback

  • Can anyone suggest a better title?

TODO

  • Scoring needs specific test cases. Perhaps the final score could be the average of all scores of the test cases.

  • Needs a proper title.

share
2  
The timing constraint is not reasonable unless you also provide constraints on the number and size of the inputs. For any input for which the constraint is reasonable at all, I think that the first point of the spec is unnecessary: if a counterexample exists, it's right at the edge of what fits in a 64-bit number. The second point of the spec is currently quite difficult to understand. –  Peter Taylor Apr 3 at 9:47
2  
Looking around a bit at the standard terminology, I think that it might be best introduced with something like "Each positive integer n generates a Collatz sequence by repetition of the map f(n) = n % 2 == 0 ? n/2 : 3*n+1. Define the orbit of n as the set containing the integers in its Collatz sequence, and the orbit of a set {n_i} as the union of the individual elements' orbits. Your task is to find an optimal set under the constraint that its orbit contain a specified subset." That then leads into the example. –  Peter Taylor Apr 4 at 16:48
2  
I'm not sure that it's justifiable to claim that for your example {I2, C5, C10} is "(not the most ideal)". Whether or not it is depends on which arrows are /2 and which are *3+1, which isn't shown in the example. It's also occurred to me, which I missed earlier, that your scoring system requires a bit more of a test suite: at present, you have no way of distinguishing between answers which get the optimal solution to one test case. And I suggest a title, based on my previous comment: "Optimal Collatz orbits". –  Peter Taylor Apr 4 at 16:52
1  
I suggest you to add a link describing what is a collatz sequence. As a non-mathematician, I find it hard to understand. There is extra whitespaces after `` in your first code block. –  A.L Apr 4 at 17:12
1  
It occurs 4 times in the Wikipedia page on the Collatz conjecture, and Google gives over 6 million hits for collatz orbit. –  Peter Taylor Apr 6 at 22:08

ASCII ART edge detection

As the title says, I was thinking to contest in which one must detect edges of an ASCII art.

The code should accept a B/W ASCII art as input. A B/W ASCII art is defined as (by me) an ASCII art with only one kind of non-white-spaces character (in our case: an asteriks *). And as output produce a standard ASCII art (all ASCII characters are accepted) which should remember the contourn of the first.

The purpose of using more than one character in the output is to make some edges ssmoother. For instance, one could let this input

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

could became:

      ___
    _/   ) 
  _/    /
 /      |
|      /
|      \
 \      |
  `\     |
     \___)

The input \n separated string as input. Each line has a maximum of 80 characters. The number of rows is not specified.

I'd put it as a popularity-contest since, beside my simple code, I'd like to see more "round" edge detections which use more than one character in smooth edges.

Also, I don't want to tag it as code-golf since I'm quite sure one can do this job using aplay (with ASCII art renderer) and command line GIMP (to apply edge detection).

As a popularity contest, there are no strict rules on how the output should be..just use your fantasy!

This is my sample program:

import fileinput as f
import re as r
import copy as c
a,s,p='*',' ','+'
def read(n):
    s=[list(' '*n)]
    for l in f.input():
        if(len(l)>n):l=l[:n]
        k=list(r.sub('[^ ^\%c]'%a,'',' '+l+' '))
        s.append(k+[' ']*(n-len(k)))
    s.append([' ']*n)
    return s
def np(s):
    s=c.deepcopy(s)
    for l in s[1:-1]:
        for w in l[1:-1]: print(w,end='')
        print()
def grow(i):
    o=c.deepcopy(i)
    for x in range(1,len(o)-1):
        for y in range(1,len(o[x])-1):
            if(i[x][y]==a): o[x-1][y-1]=o[x-1][y+1]=o[x-1][y]=o[x+1][y]=o[x+1][y-1]=o[x+1][y+1]=o[x][y+1]=o[x][y-1]=a

    return o
def diff(i,o):
    c=[]
    for x in range(0,len(i)):
        l=[]
        for y in range(0,len(i[x])):
            if(i[x][y]==a and o[x][y]==s): l.append(p)
            else: l.append(s)
        c.append(l)
    return c
I=read(80)
np(diff(grow(I),I))

Here below I put both input of the programs. It is an 80x70 ASCII ART. It means it has 70 lines of 80 characters, each separated by \n.

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

A possible output could be:

                                         +++++             ++++
                                    ++++++     ++++++++++     +++
                                   ++      +++++        +++++   +++++
                            ++++++++   +++++                ++++    ++
                         ++++         ++                       ++++  ++
                    ++++++           ++                           ++  ++
                +++++      +++       +   +++++                     ++  ++
             ++++     +++++++       ++  ++   ++                     ++  ++
            ++    +++++   ++        +   +     +                  +++++++ ++
          +++  ++++      ++         +  ++     ++                ++     ++ ++
         ++   ++        ++         ++  +       +                +      ++  ++
        ++  +++         +          +  ++       +               ++      +++  +
       ++  ++          ++          + ++       ++               +        +++ +
      ++ +++          ++           + +      +++                +        + + ++
      +  +            +            + +     ++                  +        ++++ +
     ++ ++           ++            + ++   ++                   ++        + + +
    ++ ++            +             +  +++++                     ++      ++ + +
   ++ ++             +             +                             +++   ++  + +
   +  +             ++             +                               +++++   + +
  ++ ++             +              +                                      ++ +
  +  +              +             ++                                      +  +
 ++ ++             ++             +                                       +  ++
++  +              +             ++                                       +   ++
+   +              +             +                                        +    +
+  ++             ++            ++                                        +    +
+  +              +             +         +++++++                         +    +
+  +              +             +        ++     ++        ++++            +    +
+  +              +             +        +  +++  +       ++  +++          +    +
+  +              ++            +        + ++ ++ +      ++  +  ++         +    +
+ ++               +            ++      ++  +++  +      +  +++  ++        +    +
+ +                +             +      +       ++      +  +++   +        +    +
+ +                +            ++      ++     ++       ++       +        +    +
+ +   +++          ++            ++      +   +++         +++     +       ++    +
  +  ++ ++          +             ++     +++++             +    ++      ++     +
  + ++   ++         +              +                       ++++++      ++     ++
 ++++     +         ++             +++                                ++      +
  +       +          ++              ++            +++              +++       +
          +           +               ++++        ++ ++           +++         +
          ++          ++                 ++++     +   +        ++++           +
           +           ++                   +++++ +++++    +++++              +
           ++           ++                      +++   ++++++                  +
            ++           +                 +++++  +++++                       +
             ++          +                  +  +++    +++++                   +
              +++        +                  ++   ++++++  +                    +
                +        ++                  +           ++                   +
               ++        +                   +            +                   +
                +++      ++                  +           ++                  ++
                  ++      +                  +           +                   +
                   +++    ++                 +         +++                   +
                     ++++++                  +        ++                    ++
                                             ++     +++                     +
                                              +    ++                       +
                        +++++                 ++++++                        +
+                      ++   ++                   +                          +
+                     ++     +                                             ++
+                     +      +                            ++               +
+                    ++      +                          ++++               +
+                    +       +                     ++++++ ++               +
+                   ++       +                    ++      +                +
+                  ++        +                 ++++       +                +
+                 ++         ++                +          +               ++
+                 +           +                ++         +               +
+                 +           +                 +         +               +
++                +           +                 ++        +               +
 ++              ++           +                  +        +               ++
  ++++++++++++++++            +++                +        +                +
                                ++              ++        ++               +
                                 ++++++++++++++++          ++              +
                                                            ++            ++
                                                             ++++++++++++++

This is also the output produced by the script above. Of course it is not the best output and I'm sure one can easily produce a smoother one.

share
1  
It would be useful to be more precise about which characters should be non-blank in the output: characters which were non-blank in the input but adjacent to blanks, or characters which were blank in the input but adjacent to non-blanks? –  Peter Taylor Apr 4 at 9:50
1  
one could let this input (…) could became → try something like "this input (…) could become" outpuit → output –  user2428118 Apr 7 at 13:31

Regular expression parser

This task is a classic programming task: Implement a regular expression parser. That is, write a program or function which takes a string describing a regular expression and a candidate string, and test whether the complete candidate string matches the regular expression. You may assume that the regular expression passed is valid.

If your programming language offers regular expression matching or string parsing, you are not allowed to use that. Also you are not allowed to use libraries other than the standard library of your programming language. Also forbidden is to access an external tool to do the work (e.g. accessing a web server, or calling another executable).

This is an atomic code golf contest, it's not the character count that has to be minimized, but a modified token count (for details, see below).

Input

The regular expression is not enclosed in slashes (/), any slashes appearing in the regular expression string are part of the regular expression itself (that is, the string /.*/ denotes not the regular expression .*, but the regular expression /.*/ which will match the string /abc/, but not the string abc).

Both the regular expression string and the candidate string will consist solely of ASCII characters in the range 32 (space) to 126 (tilde).

The regular expression syntax

Your program only needs to parse the following minimal regular expression syntax:

  • Anything except the letters ., *, |, (, ) and \ matches literally.
  • A backslash (\) followed by any of the above characters literally matches the second character.
  • A dot (.) matches any character.
  • The star (*) matches zero or more consecutive strings each matching the regular expression preceding it. It cannot appear at the beginning.
  • The pipe (|) matches either the regular expression before it, or the regular expression following it.
  • Parentheses ((, )) themselves don't match anything, but are used to group expressions (e.g. ab* matches abbbbb, while (ab)* matches abababab).

Output

Your program or function must give one of two results, one indicating that the complete candidate string matches, one indicating that it doesn't. How the output is given (function return variable, global variable setting, text output, program status code, ...) is up to you (and the capabilities of your chosen programming language). Explain how the output is to be interpreted.

Scoring

Of course, this being a code golf, the minimal score wins. The score is calculated as follows:

  • Start with score 0.

  • Comments and whitespace characters that are not part of a token are ignored.

Rationale: I don't want to penalize pretty formatting. The token exception covers both spaces inside string and character constants, and special cases like the Whitespace language where each single whitespace character constitutes a token (so writing a program in Whitespace won't give you a score of 0).

  • For any statement/declaration/etc. which makes available a standard library component to the code (like #include in C, use in Perl or import in Java), add 5 point per imported standard library package.

Rationale: I don't want to make the scoring dependent on how verbose the import syntax of a language is. Also, there shall be a slight (but not too strong) discourage of using library components (direct code is preferred, unless the library makes a big difference; however note the restrictions on library use outlines above). The "per standard library package" part is so that you cannot reduce your point by combining several imports by one (e.g. in Turbo Pascal, you could write uses dos, crt; instead of uses dos; uses crt;. With the rule as given, both would add 10 points. (Of course, both dos and crt would be pointless for the given task.)

  • For any string, add one mode than the number of characters in the string (that is, the empty string gets 1 point, a one character string gets 2 points, etc.)

Rationale: This is mainly to prevent tricks like eval("long program code") which is four tokens. With this rule, doing such a trick actually penalizes your code, because you're back to character counting instead of token counting.

  • For any number, add as many points as the minimal number of bytes needed to represent the number as either signed or unsigned two's-complement number. That is, numbers from -128 to 255 (including both values) get 1 point, otherwise numbers in the range -32768 to 65535 get 2 points, otherwise numbers in the range -8388608 to 16777215 get 3 points, and so on.

Rationale: This is to prevent similar tricks in languages supporting arbitrary large numbers, where the whole program might be encoded in a number that is then reinterpreted as a string and passed to eval or an equivalent function.

  • Any token not covered in the list above gives 1 point.

Rationale: This is to avoid penalizing verbose languages (e.g. Pascal with begin/end vs. C with {/}), and especially to avoid giving esoteric languages (Golfscript!) an advantage just for having one-character tokens. Also, it allows meaningful variable names without being penalized.

share

Am I a Matroid?

Input:

A list I that is a subset of the powerset of E={1,2,...,n} which represents the independent sets of elements of the purported matroid M=(E,I). Note that the cardinality of the ground set may be for the purposes of this question ignored. Any elements of E that appear in none of the elements of I cannot contribute (i.e. if M=(E,I) is a matroid then M=(E union K,I) is a matroid for any set K.

Input may be in whatever list format you desire, be it as simple as no separators but spaces (using 0 for the empty set): 0 1 2 3 12 13 or as complicated as whatever list literals are in your favorite language (such as python's: [[],[1],[2],[3],[1,2],[1,3]]).

Output:

A variation on 1/0, true/false, yes/no answering the question: is M a matroid?

Definition:

M=(E,I) is a matroid if:

  1. I is not the empty set
  2. If J is in I and K is a subset of J, then K is in I
  3. If J,K are in I and |K|<|J| then there exists an element x that is in the set difference J-K such that K union {x} is in I.

There are equivalent formulations of condition 1 and 3, also there are conditions on the bases (maximal elements of I w.r.t. cardinality) that are equivalent to these. If people want I can post those too or leave them as optional research.

Examples:

I={{},{1},{2},{1,2}} is a matroid.

I={} is not a matroid because it is empty (by axiom 1).

I={{},{1},{1,3}} is not a matroid because if it has {1,3} independent then it must have {3} independent (by axiom 2).

I={{},{1},{2},{3},{1,2}} is not a matroid because if it has {1,2} and {3} independent then it must have either {1,3} or {2,3} independent (by axiom 3).

I={{}} is always a matroid, as is I=powerset([1,2,...,n]) for any n>0 as they both trivially satisfy the axioms.

Specs:

Submission is either a program taking input from standard input or command line argument or a function that takes I as input (as a string) and returns the specified binary answer. No upperbound on the size of input should be hardcoded.

I would intend for this to be a code-golf challenge.

share
1  
Rather than provide alternative definitions, just link the first mention of the word matroid to the Wikipedia page. –  Peter Taylor May 5 at 11:59

Prove Your Language is Turing Complete

Write the shortest code possible to prove that your language is Turing Complete. However, if the programming language is not Turing Complete because of something like limited access to memory, just state so.

You can prove your language is Turing Complete in several ways. The easiest would be to write an interpreter for a Turing Complete language. For example:

Note that IO is not necessary for a language to be Turing Complete.

Note: Programs that interpret themselves are not valid because that would be circular logic. You would be saying that your language is Turing Complete because it is Turing Complete.


Meta:

  • I'm reluctant to tag as because some languages may have very short ways of proving this. Is there a better scoring method that wouldn't discourage people from writing concise programs?
  • The truth is, this is sort of a by-language challenge. It is a challenge to do this in every language.
  • This seems too broad: it basically says "write an interpreter for a turing-complete language".
share
1  
I think that practically all languages that don't require a class wrapper for the main function/method (if it exists) would be able to do this rather concisely. On the other hand, I'm pretty sure you won't get 1-character submissions from APL or GolfScript. I wouldn't be as worried about this being a code golf. –  impinball Apr 26 at 0:33
1  
I think that if a contestant is to make an interpreter for a turing-complete language, they should include a reference showing that the interpreted language is turing complete. –  kitcar2000 Apr 28 at 17:06

Design and Solve a Maze

(this question on hold while the details are ironed out)


Your task is to play the roles of both characters in this scene from Inception. In it, Cobb gives Ariadne a challenge:

You have two minutes to design a maze that takes one minute to solve.

Some liberties will be taken on that description. Most importantly, this challenge is not time-based, rather scores are based on the effectiveness of your mazes and maze-solvers.

I apologize for the many edits to this challenge as we iterate towards an easy and fair format..

Part I: Maze format

All mazes are square. A cell in the maze is represented as a zero-indexed tuple row column.

Walls are represented by two binary strings: one for horizontal walls (which block movement between rows) and vertical walls (vice versa). On an NxN maze, there are Nx(N-1) possible walls of each type. Let's take a 3x3 example where the cells are labelled:

A   B | C
   ---
D | E   F
   ---
G   H | I

all possible vertical walls are: AB BC DE EF GH HI. Translated into a string, the walls shown are 011001 for vertical walls and 010010 for horizontal walls. Also, by "binary string" I mean "the characters '0' and '1'".

The full maze format is a string which contains, in this order:

  • width
  • start cell tuple
  • end cell tuple
  • horizontal walls
  • vertical walls

For example, this maze:

   0 1 2 3 4
   _________
0 | |  E|  _|
1 |  _|_|_  |
2 |_ _ _  | |
3 |  _ _  | |
4 |____S|___|
start:(4,2)
end:(0,2)

is formatted to this:

5
4 2
0 2
00001011101110001100
10100110000100010010

Part II: The Architect

The Architect program creates the maze. It must play by the rules and provide a valid maze (one where a solution exists, and the end is not on top of the start).

input via stdin: Two positive integers:

size [random seed]

Where size will be in [15, 50]. You are encouraged to make use of the random seed so that matches can be replayed, although it is not required.

output to stdout: A valid size x size (square) maze using the format described in Part I. "valid" means that a solution exists, and the start cell is not equal to the end cell.

The score of an Architect on a given maze is

   # steps taken to solve
------------------------------
max(dist(start,end),(# walls))

So architects are rewarded for complex mazes, but penalized for each wall built (this is a substitute for Ariadne's time restriction). The dist() function ensures that a maze with no walls does not get an infinite score. The outside borders of the maze do not contribute to the wall count.

Part III: The Solver

The Solver attempts to solve mazes generated by others' architects. There is a sort of fog-of-war: only walls adjacent to visited cells are included (all others are replaced with '?')

input via stdin: the same maze format, but with '?' where walls are unknown, an extra line for the current location, and a comma-separated list of valid choices from this location. (This is a big edit that is meant to make it simpler to write a maze-parsing function)

example (same as the above 5x5 maze after taking one step left)

5
4 2
0 2
???????????????011??
????????????????001?
4 1
4 0,4 2

Which corresponds something like this, where ? is fog:

   0 1 2 3 4
   _________
0 |????E????|
1 |?????????|
2 |?????????|
3 | ?_?_????|
4 |__C_S|_?_|

output to stdout: One of the tuples from the list of valid choices

Each Solver's score is the inverse of the Architect's score.

Part IV: King of the Hill

Architects and Solvers are given separate scores, so there could potentially be two winners.

Each pair of architects and solvers will have many chances to outwit each other. Scores will be averaged over all tests and opponents. Contrary to code golf conventions, highest average score wins!

I intend for this to be ongoing, but I can't guarantee continued testing forever! Let's say for now that a winner will be declared in one week.

Part V: Testing

I have written a Python testing kit which includes a Maze class for parsing and writing in the proper formats, as well as an example architect/solver pair: Daedalus and the Minotaur

Available on both Dropbox and GitHub

Part VI: Submitting

  • I maintain veto power over all submissions - cleverness is encouraged, but not if it breaks the competition or my computer! (If I can't tell what your code does, I will probably veto it)
  • Come up with a name for your Architect/Solver pair. Post your code along with instructions on how to run it.
share

md5sum Rainbow Table

This is my first code golf challenge; critiquing welcome.

Your task is to create a rainbow table of md5sum'ed integers. You need to output to STDOUT the integer, a space or a tab character, the md5sum, then a new line. The spec for an md5sum can be found here, thanks to the IETF. For example:

1 c4ca4238a0b923820dcc509a6f75849b
2 c81e728d9d4c2f636f067f89cc14862c
... 
//hashes generated on http://www.md5.cz/
  • You need to write the full program, not just the function.
  • You may use existing libraries so long as you are not directly calling an md5sum function from within that library.
  • Output is not case sensitive (A is the same as a when it comes to an md5sum).
  • You need to get all positive unsigned 32-bit integers from 1 to 4,294,967,295. You may load the numbers however you want into the program. You should input the integer as a string (i.e. using the ASCII code for each digit)
  • No downloading data from the Internet.
  • Code Golf, so the shortest answer wins!
share
1  
what should the output file be called? isn't it easier to use STDOUT? and should the character separating the number and its md5 be a tab or a space or the correct number of spaces? –  professorfish May 30 at 6:40

Recover a bzip2 file

Posted

share

Find the mines!

Tags:

You are a mine remover. Your job is to find all mines on a field, without a mine explodes. So, you write an application that can find the mines carefully.

The input

The input can either be provided through command line arguments or through STDIN (tell what you use in your submission). The input items are separated by commas.

The input looks like this:

<current step (zero-based)>,<mine count>,<field width>,<field height>,<field data>

The field data is like a Minesweeper field. Rows in the field data are separated by semicolons, columns are separated by nothing, as each column is just one character. Here are the characters you can get:

  • X This means that you don't yet know what's there, the real data is still hidden. At the start, you get a field full of Xs.
  • / This means that there is nothing on that location.
  • <number> Specifies the count of mines around the location of the number.
  • F This is marked by a flag by you.
  • ? This got a question mark from you. There might be a mine on it, but you are not sure. This is just used as a reminder for you, it doesn't mean something specific to the controller.

Example input:

2,1,3,3,XX1;X1X;XXX

That input means that it's currently your third step, there is one mine, the field is 3x3, and the field looks like:

X X 1
X 1 X
X X X

The output

The output consists of 4 parts: the X of which you want to see the data (like a click in Minesweeper), the location on which you want to put a flag mark, the location on which you want to put a question mark and a sign, used to let the controller know whether you are finished or not (0 for not finished, 1 for finished). Locations are written as X;Y, zero-based. If there is something you don't want to do, output -1. You can also remove flags/question marks using the same way.

Example output:

4;3,-1,3;3

Specifications

  • If your first output data is the location of a mine, you hit the mine and you die, but you'll still get a score.
  • If you select a X which hides an empty location (/), all adjacent empty fields (and their borders, which are numbers) will be revealed.
  • For every step, your program is executed again with the updated arguments.
  • When looking for mines, you are allowed to have more flags than the amount of mines. Only if you finish, the amount of flags must not be more than the amount of mines. If the amount of flags is greater than the amount of mines, your submission is disqualified (for every test!) and excluded from the scoreboard.

Testing

When I test your submission, I'll run 100 tests on every submission, with randomly generated fields, which I created using a program that I'll write after I got some feedback. Every submission gets the same test fields, so it's fair. Test fields look like this:

  • 10 tests with a 10x10 field and 10 mines.
  • 10 tests with a 10x10 field and 12 mines.
  • 10 tests with a 12x12 field and 14 mines.
  • 10 tests with a 15x10 field and 16 mines.
  • 10 tests with a 15x15 field and 35 mines.
  • 10 tests with a 20x20 field and 40 mines.
  • 10 tests with a 25x25 field and 50 mines.
  • 10 tests with a 25x25 field and 60 mines.
  • 10 tests with a 50x50 field and 100 mines.
  • 10 tests with a 50x50 field and 125 mines.

Scoring

You get 10 points for every mine you find, you lose 5 points if you think there is a mine somewhere when there is none and you lose 2 points for every mine you missed. The scoring is always the same, it doesn't matter whether you finish or die. The highest score wins.

In case of a tie, the count of steps is a tie breaker.

Controller

I'll start working on this after I got some feedback.

share
1  
You say "like Minesweeper" a couple of times, but on a cursory read I didn't see anything which differentiates it from Minesweeper. Why is this not a dupe of codegolf.stackexchange.com/q/24118/194 ? –  Peter Taylor Jul 24 at 14:58

Inspired by lifecompetes.com

Multiplayer Game of Life (GOL)

There are n players that play the Game of Life (standard rules) on an 50 x 50 grid. (Size, border conditions? Toroidal, Absorbing, Mirroring?)

Before first GOL-Step

When the game starts, each player has 12 cells that he can place anywhere he want as long as they do not overlap. Before the first GOL-step occures every player has to place 6 cells. If two players place their cell on the same spot no cell wil be placed an thei cells will remain in each players bank.

During game

In each GOL-Step, each player can place as many new cell on the grid as he has in his bank. If two or more players want to place a cell on the same spot, no cell will be placed there (the cells will remain in each players bank). Every six GOL-steps all the players who have less that 12 cells in their bank will get a new cell in their bank.

Goal

The goal is achieving the maximum number of cells on the grid during 1000 GOL-steps.

How to participate

Each participant has to write a javascript function of the following form (multiple return statements allowed.)

function my_bots_name(field, bank, golstep){
  /* your code */
  return p;
}

Where p is a 2d array of points [[x1,y1],[x2,y2],[x3,y3],...] that the player wants to set. field contains a 2d array of the GOL grid, bank indicates the number of cells in the player's bank, and golstep is the index of the current GOL step (golstep == 0 before the first GOL-step occurs). The function may not the global variables and cannot access Math.random() or Date(). In field the empty cells will be set to 0, the own cells will be set to 2 and the other player's cells will be set to 1. (You will not be able to distinguish between various other players.)

The winner will be determined with a game that contains all valid submissions after one week after the first submission.

TODO

The exact environment will be provided so everyone can test the own function before the official runs.

  • What size of the grid is appropriate? (dependent on number of players?)
  • How many steps should be computed?
  • What border conditions should be chosen?
  • Is the restriction of Math.random() and Date() apropriate? (The idea was that the games will be the same no matter of who/when they will be run. (Deterministic) )
share

Code with largest MD5 hash of output

Your code will output to STDOUT or save to a file. The output's MD5 hash will be taken and treated as an integer expressed in hexadecimal. If another answer posted before you gives the same MD5 hash then your answer is invalid.

The answer with the highest MD5 hash wins.

You can use whatever method you wish to prepare the output. Note that brute force might not be the only approach since MD5 is broken.

You will not use any hardcoded range narrowing unless based on a previous answer. That is, you can start a search from zero or you can start a search from a point determined from analysing a previous answer, which you will credit with a link to the answer. You are not restricted to lexicographic order of outputs when searching. For example you might choose to test all strings of the letter "a" up to a given length, followed by all strings of a letter "b". However, you cannot hardcode a string of length more than 1 to start the search from.

Your code must be deterministic. The output must be reproducible.

If you wish to use something from an answer posted after yours, you will have to post a new answer, so that the genealogy is clear.

To avoid portability problems, the output may not contain newlines of any type.

share
1  
This is just a kolmogorov-complexity question which changes as people find better outputs, and since the output is unlikely to have any nice structure there's a reasonable chance that the programs posted will just emit a literal string. It might be more interesting to add constraints that the first person to post a particular output has exclusive rights to it and to require the search program to be included in the answer. –  Peter Taylor Aug 15 at 16:34

Text Adventure Game

Objective

Your goal is to develop a complete text-based adventure game with the shortest code possible. The player navigates in a dungeon composed of rooms. The game objectives are to find the treasure, slain the dragon and rescue the princess.

Rules

A room description is as follows:

You are in <description>.
You can go <exits>
You see <object>      (optional)
  • exits can be "north", "east", "west", "south".
  • description can be "a adjective cavern", "a adjective room", "a adjective corridor", "a adjective hall", "a cell", "the dragon's lair".
  • adjective can be "dark", "murky", "small", "large", "narrow", "gloomy", "huge", "strange", "tiny", "broad", "old".
  • object can be "the princess", "the dragon", "a troll", "a goblin", "a sword", "gold", "a key", "a trunk".

Exit list must be comma-separated and end with "and". If there is no object in the room, the last line is omitted.

Example of valid description:

You are in a murky room.
You can go north, east and south.
You see a goblin.

The game accepts the following commands (case is ignored) :

  • GO direction : direction can be NORTH, EAST, WEST, SOUTH
  • TAKE item : item can be SWORD, GOLD, KEY
  • KILL monster : monster can be DRAGON, TROLL, GOBLIN. The DRAGON and the TROLL can be killed only if the user has the SWORD. If he hasn't, he loses the game. The weak GOBLIN can be killed with bare hands. When a monster dies, he disappears from the room. When the GOBLIN dies, he drops a SWORD. When the TROLL dies, he drops a KEY.
  • KISS person : person can be PRINCESS, DRAGON, TROLL, GOBLIN. Kissing the princess validates one of the objective of the game, and the princess disappears from the room. Kissing a monster results in player death.
  • OPEN object : object can be TRUNK. If the player has the KEY, the TRUNK object disappears and is replaced with GOLD.

OBJECTS
The player can perform an action on an object only if the object is in current room. A room can contain only one object ; a given object can be found in only one room. At the beginning of the game, only the following objects are placed in the map : PRINCESS, DRAGON, TROLL, GOBLIN, TRUNK. Other objects are not yet created.

ACTIONS

  • If an action cannot be performed (e.g. GO NORTH where there is no exit to the north, or TAKE DRAGON, or DANCE GANGNAM STYLE), the message "Sorry, I can't do that" must be displayed.
  • If an action can be performed, the message "OK" and the current room description should be displayed.
  • You can read game commands from console or as a program parameter, as you wish.

MAP
The dungeon should have at least 30 rooms. The dungeon should not contains a series of more than 5 exits in the same direction. The exits between rooms must be consistent, e.g. if you go north from room #1 to room #2, there must a south exit in room #2 leading back to room #1. Every room name should be unique. There must be at least one room of each kind (hall, cavern, corridor...)

  • A hall has at least 3 exits.
  • A corridor can have only 2 exits.
  • The cell has only one exit.
  • There is only one dragon's lair and only one cell, containing respectively the dragon and the princess.

GAME END
The game ends when the player has been killed, or when he has taken the gold, slain the dragon and kissed the princess.

  • If the player dies, the message "You have been killed by X !" is displayed, with X being the name of the monster.
  • If the player wins, the message "Well done adventurer ! you've conquered the dungeon." is displayed.

Player should not be able to win the game in less than 40 turns.

Example

You are in a murky room.
You can go north, east and south.
You see a goblin.
> KILL GOBLIN
Ok.
You are in a murky room.
You can go north, east and south.
You see a sword.
> TAKE SWORD
Ok.
You are in a murky room.
You can go north, east and south.
> GO NORTH
Ok.
You are in a narrow corridor.
You can go south and east.  

Scoring

The shortest code wins.

share

Render the Utah Teapot

[Hasty first posting.] [Revised and Posted]

The Utah Teapot, originally created by Martin Newell, is a convenient object for testing 3D graphics programs. Using the dataset available here (direct link, just the teapot), render a 3D view of the teapot (a perspective projection to 2D) with a simple lighting model (single light-source).

"Beige"

Requirements

snip! (see revisions for example postscript code).
I'm snipping for brevity, but I'm keeping the picture. :P and this note explaining it. And some other stuff up there.

share
1  
Bézier patches can be polygonised with the bounding box property and the de Casteljau algorithm. –  Peter Taylor Jan 28 '13 at 14:12

Display a Magic Square

Edit: Now proposing to instead add bounty to Magic Square Generator, which this is a dupe of. Please see comment and give feedback.


Your challenge is to display an n*n magic square of a given odd size n. A magic square is a grid of numbers in which each number 1,..,n^2 appears exactly once, and in which every row, column, and diagonal has the same sum.

A 5x5 Magic Square

Your program should be able to produce a magic square for any given odd number n with 2<n<32. Think of the parameter n as an input. Your may have your program get this value pre-initialized in a variable, as function input, passed from stdin, or starting on the stack.

Fewest bytes wins.

Any magic square that fits the conditions is fine. You don't have to find or verify that it's a magic square. See the Wikipedia article and Mathworld page for structured methods to make magic squares.

The program should display or print a magic square when run. Just returning it from a function or storing it in a variable is not sufficient.

The result must look like a 2D array of numbers. A list of entries printed on a single is not acceptable, nor is each entries on its own line. You can't rely on a fixed line width, but assume it's large enough to fit the square. The numbers must be somehow separated, since otherwise digits blend together, but any delimiter is fine.

There's no time limit to generate the output. If you want to brute-force search every grid until you find a magic square, that's fine even if won't output this century.

Standard loopholes apply. Functions that specifically generate magic squares are not allowed.

Example output with n=7:

1 2 47 46 33 30 16
11 45 35 18 24 14 28
44 38 9 13 19 23 29
42 7 10 25 40 43 8
21 27 31 37 41 12 6
22 36 26 32 15 5 39
34 20 17 4 3 48 49

Example output with n=13:

[[12, 169, 144, 132, 120, 108, 96, 84, 72, 60, 48, 36, 24],
 [27, 15, 3, 160, 148, 136, 124, 112, 100, 88, 76, 64, 52],
 [55, 43, 31, 19, 7, 164, 152, 140, 128, 116, 104, 79, 67],
 [83, 71, 59, 47, 35, 23, 11, 168, 156, 131, 119, 107, 95],
 [111, 99, 87, 75, 63, 51, 39, 14, 2, 159, 147, 135, 123],
 [139, 127, 115, 103, 91, 66, 54, 42, 30, 18, 6, 163, 151],
 [167, 155, 143, 118, 106, 94, 82, 70, 58, 46, 34, 22, 10],
 [26, 1, 158, 146, 134, 122, 110, 98, 86, 74, 62, 50, 38],
 [41, 29, 17, 5, 162, 150, 138, 126, 114, 102, 90, 78, 53],
 [69, 57, 45, 33, 21, 9, 166, 154, 142, 130, 105, 93, 81],
 [97, 85, 73, 61, 49, 37, 25, 13, 157, 145, 133, 121, 109],
 [125, 113, 101, 89, 77, 65, 40, 28, 16, 4, 161, 149, 137],
 [153, 141, 129, 117, 92, 80, 68, 56, 44, 32, 20, 8, 165]]
share
1  
@Geobits Hmm, that's too bad, that's what I get for not searching. Though the question is old and got few answers -- maybe I can justify reviving it? –  xnor Aug 23 at 2:26

Old fashioned intelligence gathering

As we've heard in the news, some intelligence agencies have decided to go back to typewriters due to the security hazards of the Internet. You are a spy. In spite of this change in policy to make messages more secure, one of your contacts scores an intelligence treasure trove: rolls of spent typewriter tape from your enemy.

The only problem? Whomever your enemy spy agency hired was a really bad typist. In fact, they tended to hit as many wrong keys as they did write. So when you read out the first bit of tape, you see

DQSIRINKSFIJATOAPQFFOUSJAR

Yikes. That's some attrocious typing. Seriously, there's training tools for that. Anyways, you're in luck. You also scored the correction tape:

QSIFIJOAPQFSJA

After racking your brain for hours, you realize someone just wanted some booze:

DQSIRINKSFIJATOAPQFFOUSJAR  (ink tape)
-QSI-----FIJ--OAPQF---SJA-  (correction tape)
D---RINKS---AT-----FOU---R  
DRINKS AT FOUR              (message)

There's a lot of tape though, and you know there's some good intelligence information here, so you write an program to determine the original messages after filtering out the massive amounts of typos.

Rules

Input

  • a return-delimited dictionary file
  • ink tape letters (all caps)
  • correction tape letters (all caps)

Output

  • all possible original messages ordered from fewest to most words in message; there shall be no specified ordered for messages with the same number of words. If the intended message were MY GRANDMOTHER HAS A LIFELONG PASSPORT, the output should generate the following (going from 6 words to 9 words):
    • MY GRANDMOTHER HAS A LIFELONG PASSPORT
      MY GRAND MOTHER HAS A LIFELONG PASSPORT
      MY GRANDMOTHER HAS A LIFE LONG PASSPORT
      MY GRANDMOTHER HAS A LIFELONG PASS PORT
      MY GRAND MOTHER HAS A LIFE LONG PASSPORT
      MY GRAND MOTHER HAS A LIFELONG PASS PORT
      MY GRANDMOTHER HAS A LIFE LONG PASS PORT
      MY GRAND MOTHER HAS A LIFE LONG PASS PORT

Other notes

  • all words in the original message will be spelled correctly (the typist was terrible, but they worked hard to eventually craft a correct sentence).
  • you may precapitalize your dictionary
  • all messages are alpha only (no numbers or punctuation)

Scoring:

  • Code golf, shortest code wins.

Additional sample tapes your assistant decoded to use to test your algorithm:

NUAFCLEAIEOJRWARWESHEADAJIOWGUNDSUIVHERCSNZXAPITASAOIDLBUIJOVEMOLDINGIAS (ink tape)
AFIEOJWESAJIOWGSUIVHSNZXSAOIDJOVEMOIAS (correction tape)
NUCLEAR WARHEAD UNDER CAPITAL BUILDING  (decoded messages)
NUCLEAR WAR HEAD UNDER CAPITAL BUILDING 

ASSLEDELPERIWECERSPDLLSACFSPTIVVOXATEIQPTREOIOSJFNMORROAIOW (ink tape)
ASDLIWERSPDFSPVOXIQPREOISJFNOAI (correction tape)
SLEEPER CELLS ACTIVATE TOMORROW (decoded messages)
SLEEPER CELLS ACTIVATE TO MORROW

ASOIIJHAWQRATEMSDQPOYJKWEOABS (ink tape)
ASOIJWQRASDQPOKWEAS (correction tape)
I HATE MY JOB (decoded message)
share

You must log in to answer this question.

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