490
\$\begingroup\$

What is the Sandbox?

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

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

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

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

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

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

| |
\$\endgroup\$

2976 Answers 2976

1
6 7
8
9 10
100
4
\$\begingroup\$

Is it a Happy Number?

A repost of this challenge (if I got the policy right).

Given a single positive integer (which can also be taken as a list of digits or a string), output whether the number terminates at 1 . Truthy/falsy follows the language's convention, or you can choose exactly one value for truthy and another for falsy. (This sequence is A007770.)

Your program should theoretically support all non-negative integers; however, if your language doesn't support unbounded integers, you may only support integers up to 2147483647.

Procedure

Suppose you have the number 193.

  • Square every individual digit in the number. Therefore the number's individual digits becomes:
[1] [81] [9]
  • Sum all these individual digits:
92
  • Repeat this procedure until it stabilizes at 1 or a 37-cycle like the following:
37-58-89-145-42-20-4-16-37

It has been shown that the procedure will always produce either one of these two outputs.

Test cases

Here is a sample program generating the test cases. Here is a step by step reduction of all input between 1 and 100.

1 -> true
2 -> false
3 -> false
4 -> false
5 -> false
6 -> false
7 -> true
8 -> false
9 -> false
10 -> true
11 -> false
12 -> false
13 -> true
14 -> false
15 -> false
16 -> false
17 -> false
18 -> false
19 -> true
20 -> false
21 -> false
22 -> false
23 -> true
24 -> false
25 -> false
26 -> false
27 -> false
28 -> true
29 -> false
30 -> false
31 -> true
32 -> true
33 -> false
34 -> false
35 -> false
36 -> false
37 -> false
38 -> false
39 -> false
40 -> false
41 -> false
42 -> false
43 -> false
44 -> true
45 -> false
46 -> false
47 -> false
48 -> false
49 -> true
50 -> false
51 -> false
52 -> false
53 -> false
54 -> false
55 -> false
56 -> false
57 -> false
58 -> false
59 -> false
60 -> false
61 -> false
62 -> false
63 -> false
64 -> false
65 -> false
66 -> false
67 -> false
68 -> true
69 -> false
70 -> true
71 -> false
72 -> false
73 -> false
74 -> false
75 -> false
76 -> false
77 -> false
78 -> false
79 -> true
80 -> false
81 -> false
82 -> true
83 -> false
84 -> false
85 -> false
86 -> true
87 -> false
88 -> false
89 -> false
90 -> false
91 -> true
92 -> false
93 -> false
94 -> true
95 -> false
96 -> false
97 -> true
98 -> false
99 -> false
| |
\$\endgroup\$
  • \$\begingroup\$ Is there an upper bound for inputs? I think one thing to consider is whether you want answers to implement the square-summing operation, or to try to compress or overfit some heuristic that works for say, 1 to 100. \$\endgroup\$ – xnor Mar 28 at 10:46
  • \$\begingroup\$ Falsy numbers belong to A007770. \$\endgroup\$ – Arnauld Mar 29 at 22:49
  • \$\begingroup\$ @Arnauld Nice catch + Title suggestion! \$\endgroup\$ – user92069 Mar 30 at 0:25
  • 2
    \$\begingroup\$ With the term "happy number" in hand, I found a probable duplicate. \$\endgroup\$ – xnor Mar 30 at 8:37
  • \$\begingroup\$ Ugh, why do I always have duplicate ideas recently... \$\endgroup\$ – user92069 Mar 30 at 9:01
  • \$\begingroup\$ @xnor This is a dupe indeed, but the other challenge is very old and it seems like it requires a full program with a cumbersome output format. So maybe we should rather close the old challenge as a dupe of this one instead? (I'm not sure about the right policy here.) \$\endgroup\$ – Arnauld Mar 30 at 10:38
  • 3
    \$\begingroup\$ We did once repost Kolakoski one and closed the old one as dupe (with relevant meta discussion). But this case is a bit different because the author of the old challenge is no longer active. \$\endgroup\$ – Bubbler Mar 30 at 23:00
  • \$\begingroup\$ @Arnauld Good point, that old challenge is sure showing its rust. \$\endgroup\$ – xnor Mar 30 at 23:14
4
\$\begingroup\$

Posted

Solve a Picross Row

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I don't think it is a dupe of full nonogram solver. I recommend allowing flexible I/O formats though (e.g. values other than 0,1,2 to mark each cell state). \$\endgroup\$ – Bubbler May 6 at 7:54
  • 1
    \$\begingroup\$ To make the challenge more self-contained, consider adding a brief introduction to picross/nonogram and its rules. \$\endgroup\$ – Bubbler May 6 at 9:18
4
\$\begingroup\$

Implement an HTML renderer

Note: This challenge explaination is very much incomplete - it merely contains ideas that will require revising to form a proper challenge post.

The premise of the challenge is to write a program that take an HTML document as an input, and outputs an ASCII equivalent. Obviously, working with real HTML is not possible, so this challenge will use a very limited and modified subset of HTML.

Here is an example of a potential input:

<body>
    <h1>A Document</h1>
    <div>
        <span>Hello, this is some text</span>
        <img> 8 2 </img>
    </div>
</body>

Which would yield the following output:

+--------------------+
|A DOCUMENT          |
|                    |
|+------------------+|
||Hello, this is som||
||e text            ||
||+--------+        ||
|||@~@~@~@~|        ||
|||~@~@~@~@|        ||
||+--------+        ||
|+------------------+|
+--------------------+

HTML elements that will be implemented:

<span> - Renders text between the tags, wrapping when necessary.

Example:

<body>
<span>
    This is a span element.
    You can write text in here.
</span>
</body>

Output:

+--------------------+
|This is a span eleme|
|nt. You can write te|
|xt in here.         |
|                    |
|                    |
|                    |
|                    |
|                    |
|                    |
|                    |
+--------------------+

(Extra explanation needed to clarify whitespace and character set issues)

<p> (Explanations are omitted to save space)

<h1> - <h6>

<div>

<img>

Sandbox questions/remakrs

  • I believe it is possible to write an unambiguous and specific set of rules for how an "HTML document" should be rendered
  • It will require lots of careful explanation, wording, and ample examples
  • However this challenge seems very long and complicated and it seems like it might not be in the spirit of a code golf challenge

What do you guys think?

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ "I believe it is possible" -- Yes, rewriting a subset of the HTML Spec for ASCII is possible. However, successful challenges tend to keep it simple. I'd suggest using just span and div and using no attributes. In addition, parsing has probably been done before and is cumbersome, so I'd suggest allowing input as a pre-parsed AST to focus on the key challenge of ASCII-art generation \$\endgroup\$ – fireflame241 Jul 9 at 6:16
  • \$\begingroup\$ Personally I would keep only body, div, span and img, altho img should follow a set pattern inside of it. I would also suggest making height and width attributes mandatory, in all tags. \$\endgroup\$ – Dion Jul 20 at 6:08
4
\$\begingroup\$

Solve a 2xN Maze (posted)

| |
\$\endgroup\$
4
\$\begingroup\$

Does the naïve fill suffice?

A bot is positioned in a rectangular grid. By preference it will paint in a west direction, but if it cannot it will paint in a south, east or if all else fails north direction. Sometimes this can lead it to fill the grid, but other times it gets stuck. The following examples show how the path (indicated by ascending digits) of the bot on a given grid varies depending on its starting position:

1

The bot is always able to fill a 1×1 grid, since simply by existing it has already painted the grid.

14    21    43    34
23    34    12    21

The bot is always able to fill a 2×2 grid. As a consequence of its painting direction preferences it normally traverses anticlockwise except when it starts in the bottom right corner when it traverses clockwise.

16    21    65    ..    56    65    165    216    321    654     345    456
25    36    14    21    43    34    234    345    456    123     216    321
34    45    23    34    12    21

The bot usually fills a 2×3 grid, except when it starts in the middle right square. On the other hand, it always fills a 3×2 grid; its painting direction preferences cause it to paint clockwise if it starts in the bottom middle or bottom right cell, otherwise anticlockwise.

189    21.    321    87.    987    ...    987    ...    987
276    387    498    165    216    321    236    345    456
345    456    567    234    345    456    145    216    321

The bot is able to fill a 3×3 grid when it starts in one of the even squares. It's mathematically impossible for the bot to fill it when it starts in an odd square, but I have included these positions for completeness.

Your task is to solve the of whether the bot is able to fill a given grid from a given starting point. You can assume that the grid size is a positive integer and that the starting point lies within the grid. You can take the grid size and starting point in any consistent order, as separate inputs, a pair of pairs or a list of 4 elements, or any other reasonable input format. The starting point can be 0-indexed or 1-indexed. You can use any two consistent outputs, or you can output using any values that your language considers truthy or falsy, but not both. Please include your input and output format in your answer.

The directions west, south, east or north correspond to decrementing the x-coordinate, incrementing the y-coordinate, incrementing the x-coordinate and decrementing the y-coordinate respectively.

This is , so the shortest program or function that breaks no standard loopholes wins!

Test cases (0-indexed, width height x y):

4 4 0 0 -> True
4 4 1 1 -> False
4 4 2 2 -> True
4 4 3 3 -> True
4 7 1 3 -> False
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ What's the "naive fill" algorithm exactly? \$\endgroup\$ – user202729 Jul 12 at 11:24
  • 1
    \$\begingroup\$ Comment: it's hard for me to figure out that each "column" (separated by space) represents a x*y board. Consider clarifying that. \$\endgroup\$ – user202729 Jul 12 at 11:25
  • \$\begingroup\$ @user202729 The very first two sentences are supposed to describe it, just move in the first available preferred direction until you can't move any more and paint as you go. \$\endgroup\$ – Neil Jul 12 at 14:11
  • \$\begingroup\$ Some comments: (1) You don't seem to define that "naïve fill" is. (2) It took me a while to undersdtand the meaning of the numbers 14, 21` etc mean the 2nd example, and similarly in others. After a while I realized that each "code section" contains several examples stacked horizontally. You should make thast more obvious (maybe increasing horizontal space, or explaining it in the text) \$\endgroup\$ – Luis Mendo Jul 12 at 15:47
  • \$\begingroup\$ (3) "It normally traverses anticlockwise except when it starts in the bottom right corner when it traverses clockwise": what does "normally" mean here? How do we know/choose the direction the robot follows? Or maybe this is the definition of "naïve fill"? (4) Why can't the robot fill the 2×3 case when it starts in the middle right square? That is, why doesn't start by moving up instead of left? (5) In general, but I find it all quite confusing... maybe it's me, but consider explaining the challenge with more detail \$\endgroup\$ – Luis Mendo Jul 12 at 15:47
  • \$\begingroup\$ @LuisMendo (1) The bot paints as it goes. It prefers to go west, but when it can't go west tries south, then east, then north. That's all there is to it. (2) I've added some more text and spacing. (3) "normally" means "most of the time it ends up doing this". (4) Because its first preferred direction is west so it ends up painting itself into a corner. \$\endgroup\$ – Neil Jul 12 at 16:53
  • \$\begingroup\$ (1) It prefers to go west, but when it can't go west tries south, then east, then north. That phrasing makes it much totally clear. (Now I see that's probably what you meant with by preference) Include it in the text? (3) I still find the word normally confusing there, as if that were an additional degree of freedom. Also, I see now that except when it starts in the bottom right corner when it traverses clockwise is a consequence of (1). I suggest you explicitly state something like "As a consequence of the rule for direction choice, ..." \$\endgroup\$ – Luis Mendo Jul 12 at 17:03
  • \$\begingroup\$ @LuisMendo Fair enough; I've tweaked the text again now. \$\endgroup\$ – Neil Jul 12 at 17:35
  • \$\begingroup\$ I really like this challenge, but I wonder whether the title could be a little more descriptive/catchy - perhaps 'Can the bot fill the grid?' or similar? \$\endgroup\$ – Dingus Jul 14 at 15:00
  • \$\begingroup\$ @Dingus "Can the naïve bot fill the grid?" counts as similar, right? \$\endgroup\$ – Neil Jul 14 at 17:23
  • \$\begingroup\$ Ooh, that's even better. Immediately makes me curious to find out what the naïve bot is. \$\endgroup\$ – Dingus Jul 15 at 0:35
4
\$\begingroup\$

Posted

| |
\$\endgroup\$
  • \$\begingroup\$ I assume this is more clearly stated as "square root of largest square number dividing n" oeis.org/A000188 \$\endgroup\$ – qwr Jul 9 at 22:16
4
\$\begingroup\$

Evaluate left-or-right

Left-or-right is a very simple language I made up. Its expression are made of arrows < (left), > (right), and parentheses. The goal is to evaluate an expression to either < or >.

An expression A<B picks the left item A, while picks the right one B. Think of < and > as arrows pointing to the item we want, not as comparison operators.

Take, for example, ><>. The operator in the middle is <, and confusingly, the items on each side A and B are also arrows. Since the operator tells us to take the left one A, which is >. So, ><> equals >.

Expressions also nest. We can replace the expression with its value. So, for example, (><>)<< equals ><< equals >. And, >(><>)< equals >>< equals <. For another example, (><>)(<<<)(>><) equals ><< equals >.

In the input, you'll be given a well-formed expression consisting of either a trio of arrows like ><> or the result of repeatedly replacing some arrow by a trio of arrows in parens like ><(><>) . You can assume the input won't already be a lone arrow. You may alternately accept the whole inputs encased in parens like (><>) or (<(><>)>).

The input is given as a flat string of using symbols <>(). You may not take it an a pre-parsed form like a tree.

TODO: Test cases

| |
\$\endgroup\$
  • \$\begingroup\$ +1 for ><> (15chars) \$\endgroup\$ – null Jul 25 at 4:02
4
\$\begingroup\$

A Spherical Die

Inspiration

I have a spherical die, but it's a cheap one so it doesn't work properly. When I roll it, it doesn't always land directly on a "face" marking, but instead can result in an ambiguous result ("is that a 6, a 4 or a 2?")

Assumptions

Assume the die is a perfect, evenly-weighted Unit Sphere (i.e. all points on the surface are radius 1cm from the center) , such that a "roll" can result in any point on the sphere being the uppermost point (the "roll value").

Assume that, if the die is placed or rolled such that 1 is at the "north pole", the conventions of a normal die will follow, i.e:

  • 6 will be at the "south pole"
  • 4, 5, 3, 2 will be on the "equator", clockwise in that order, equidistant around the sphere.

So, before it's rolled, the die looks like this:

image of die

The Challenge

Given a simulated roll of the die (i.e. coordinates representing the top of the die after it's rolled) with the conditions above, identify the closest value (1-6) to that point (i.e. what the roll value should resolve to).

Input

A co-ordinate on the sphere.

There are a few co-ordinate systems used for spheres, the two I'm familiar with (and so will provide examples in) are as follows:

  • P(1, φ, Θ) where φ is the "azimuth angle" (0..360), Θ is the "polar angle" (0..180)

  • P(x,y,z) where \$x^2+y^2+z^2=1\$

(note: the conversion between the two is: x = cos(φ)·sin(Θ); y = sin(φ)·sin(Θ); z = cos(Θ))

for clarity:

  • roll "1" is at P(1,n,0)
  • roll "2" is at P(1,270,90)
  • roll "3" is at P(1,180,90)
  • roll "4" is at P(1,0,90)
  • roll "5" is at P(1,90,90)
  • roll "6" is at P(1,n,180)

Output

The nearest value (1-6) to that point. If the point is equidistant to two or more points, output any one of them.

Usual exclusions etc. apply.

| |
\$\endgroup\$
  • \$\begingroup\$ Does anyone know the maths for this? Feel free to edit it in! \$\endgroup\$ – simonalexander2005 Nov 22 '19 at 9:40
  • \$\begingroup\$ I'm not sure I understand: You want us to generate a random point on a sphere and output the face of the die it corresponds to? \$\endgroup\$ – flawr Nov 22 '19 at 9:57
  • \$\begingroup\$ yeah, so generate a random point on the sphere, then find the nearest "face" - i.e. the nearest of the 6 points (top, bottom, 4 points on opposite sides around middle) \$\endgroup\$ – simonalexander2005 Nov 22 '19 at 11:11
  • \$\begingroup\$ This will be exactly equivalent to a uniform distribution over 6 values, just based on the symmetry of the situation. \$\endgroup\$ – AlienAtSystem Nov 22 '19 at 12:33
  • \$\begingroup\$ @AlienAtSystem yes, all outcomes are equally likely; but the challenge is determining which number any given point on the face of the sphere is closest to \$\endgroup\$ – simonalexander2005 Nov 22 '19 at 13:04
  • 4
    \$\begingroup\$ That's not the challenge as posted. Right now, it's "Takes no input, returns the number the (internally generated) random point is closest to" which is, under the consensus of no unobservable requirements simply equal to "Takes no input, returns uniform random value from 1-6". If you want the challenge to be "Input is point on sphere, output is number it's closest to", then write that. \$\endgroup\$ – AlienAtSystem Nov 22 '19 at 13:09
  • \$\begingroup\$ @AlienAtSystem I've edited to try and make it clearer what I'm looking for. Is it clearer now? \$\endgroup\$ – simonalexander2005 Nov 22 '19 at 13:15
  • \$\begingroup\$ It's clearer that my point still stands. Look, "Make Voronoi cells on sphere" and "Generate uniformly random points on sphere" are both good challenges. But when put together like that, they annihilate each other and give you an extremely quick shortcut right from Input (None) to output (a die roll) that doesn't require calculation of either part. \$\endgroup\$ – AlienAtSystem Nov 22 '19 at 13:21
  • 2
    \$\begingroup\$ @AlienAtSystem thanks for the feedback, I'd never heard of a Voronoi cell before. What I'm asking, then, is "generate a random point on a sphere and say which Voronoi cell that point is in". Can you explain why that doesn't work? Note that I'm asking for both the point and the cell to be output, not just the cell - otherwise I agree, given the "no unobservable requirements" rule it would be possible to just generate a random number and pretend you'd done it properly (although that would be against the spirit of it) \$\endgroup\$ – simonalexander2005 Nov 22 '19 at 13:24
  • \$\begingroup\$ Would it be better for the point on the sphere to be the input, then? \$\endgroup\$ – simonalexander2005 Nov 22 '19 at 13:27
  • \$\begingroup\$ If you want the challenge to be about finding the points it's closest to, yes. \$\endgroup\$ – AlienAtSystem Nov 22 '19 at 13:31
  • \$\begingroup\$ I want it to be a good challenge on this theme, whatever that would look like :) \$\endgroup\$ – simonalexander2005 Nov 22 '19 at 13:33
  • \$\begingroup\$ Although I don't think the current challenge is bad, it's usually best to not have multiple challenges into one nor multiple outputs (since some languages aren't able to output more than once very easily). The two challenges are: 1. Generate a random coordinate on a sphere (in whichever coordinate system you want); 2. Given a (random) coordinate on a sphere, output the dice-value closest to it. No. 1 already is a challenge, so I agree it might be better to rewrite it to challenge No. 2. I do like the general idea though, so +1 from me. \$\endgroup\$ – Kevin Cruijssen Nov 22 '19 at 14:36
  • \$\begingroup\$ It would also need some info about the size of the sphere, and what to do when the coordinate is exactly in the center between two or three poles. \$\endgroup\$ – Kevin Cruijssen Nov 22 '19 at 14:39
  • 1
    \$\begingroup\$ Note that the actual implementation is very simple, as explained in chat. \$\endgroup\$ – user202729 Jul 15 at 2:43
4
\$\begingroup\$

Posted

Shift Tac Toe

Shift Tac Toe is a game that combines Tic Tac Toe and Connect 4 together. In this game, you start with a 3 by 3 board, and each row is connected to a slider that you can move left and right. At the start, the sliders all start to the very right(this means that you can't move the slider to the right on the first turn). Each slider can hold a total of 5 pieces. Each turn, the player can drop an O or a X in one of the 3 columns of the Tic Tac Toe grid depending on which turn it is, or the player can move one of the sliders one spot to the left or to the right. All pieces fall to the bottom most space that is unoccupied. The pieces can also fall from one slider to another outside the 3 by 3 grid. If a piece is outside the 3 by 3 grid and doesn't fall into the bottom slider, then the piece is taken out. If it does reach the bottom slider, it will stay in play. A notable example of this is shown in the following grid:

     --- --- --- --- ---
    |   |   |   |   - O -
 --- --- --- --- --- ---
-   |   |   |   |   -
 --- --- --- --- --- ---
    |   |   |   |   -   -
     --- --- --- --- ---
In the grid above, the dashes(-) indicate the part of the sliders that are outside of the 3 by 3 grid and the vertical bars(|) indicate the 3 by 3 grid.
As you can see, this is the starting board except that the middle slider is one spot over to the left, and that there is an O at the very top right. 
What happens in this scenario? There is nothing immediately underneath it, so does it go out of play? 
No. This is because it still falls into the bottom slider, which means that it is still in play.

The final grid is this:
     --- --- --- --- ---
    |   |   |   |   -   -
 --- --- --- --- --- ---
-   |   |   |   |   -
 --- --- --- --- --- ---
    |   |   |   |   - O -
     --- --- --- --- --- 

Pieces can also stack outside of the 3 by 3 grid. Players will alternate between O and X, with the O player going first.

Example game:

Start with 3 by 3 grid with sliders all the way to the right:

 --- --- --- --- ---
|   |   |   |   -   -
 --- --- --- --- ---
|   |   |   |   -   -
 --- --- --- --- --- 
|   |   |   |   -   -
 --- --- --- --- ---

The O player places an O in the middle column of the 3 by 3 grid and it falls to the bottom:

 --- --- --- --- ---
|   |   |   |   -   -
 --- --- --- --- ---
|   |   |   |   -   -
 --- --- --- --- --- 
|   | O |   |   -   -
 --- --- --- --- ---

The X player then places an X in the middle column:

 --- --- --- --- ---
|   |   |   |   -   -
 --- --- --- --- ---
|   | X |   |   -   -
 --- --- --- --- --- 
|   | O |   |   -   -
 --- --- --- --- ---

The O player then pushes the middle row slider one space to the left. 
Notice that after the slider moves, there is nothing under the X anymore, so it falls down. 
Also note that the slider has moved one space to the right as indicated below:

     --- --- --- --- ---
    |   |   |   |   -   -
 --- --- --- --- --- ---
-   |   |   |   |   -
 --- --- --- --- --- ---
    | X | O |   |   -   -
     --- --- --- --- ---

The X player places a X in the rightmost column:

     --- --- --- --- ---
    |   |   |   |   -   -
 --- --- --- --- --- ---
-   |   |   |   |   -
 --- --- --- --- --- ---
    | X | O | X |   -   -
     --- --- --- --- --- 

The O player then moves the bottom slider one spot to the left.
Notice that all the pieces shift one place to the left, and the leftmost X is now out of the playing field:

     --- --- --- --- ---
    |   |   |   |   -   -
 --- --- --- --- --- ---
-   |   |   |   |   -
 --- --- --- --- --- 
- X | O | X |   |   -
 --- --- --- --- --- 

The X player places a X in the leftmost column:

     --- --- --- --- ---
    |   |   |   |   -   -
 --- --- --- --- --- ---
-   | X |   |   |   -
 --- --- --- --- --- 
- X | O | X |   |   -
 --- --- --- --- --- 

The O player places an O in the leftmost column:

     --- --- --- --- ---
    | O |   |   |   -   -
 --- --- --- --- --- ---
-   | X |   |   |   -
 --- --- --- --- --- 
- X | O | X |   |   -
 --- --- --- --- --- 

The X player shifts the top slider one place to the left. Notice that the O falls one place down because there is nothing beneath it:

 --- --- --- --- ---
-   |   |   |   |   -
 --- --- --- --- ---
- O | X |   |   |   -
 --- --- --- --- --- 
- X | O | X |   |   -
 --- --- --- --- --- 

The O player is not very good at this game, so he shifts the middle slider one place to the right. 
This shifts all the pieces in the middle row one place to the right:

 --- --- --- --- ---
-   |   |   |   |   -
 --- --- --- --- --- ---
    | O | X |   |   -   -
 --- --- --- --- --- ---
- X | O | X |   |   -
 --- --- --- --- --- 

The X player wins the game by placing a X in the middle column:

 --- --- --- --- ---
-   |   | X |   |   -
 --- --- --- --- --- ---
    | O | X |   |   -   -
 --- --- --- --- --- ---
- X | O | X |   |   -
 --- --- --- --- --- 

Your job is to take in a string or array of any length that only consists of 9 unique characters(you choose the characters). Three of the characters will choose which column you place the X or O(depending on whose turn it is), three of them will choose which slider to move right, and the last three will choose which slider to move left. You can assume that the input only has these 9 characters. The output should be a 3 by 3 matrix or some kind of list/string that clearly shows the final position of the grid upon following the instructions of the input. You can assume that all inputs are valid. Each character takes up a turn. Also, if any move results in a winning move(forms 3 in a row in the 3 by 3 grid like regular Tic-Tac-Toe), then ignore the rest of the input. Note that the pieces that form the winning 3 in a row all have to be in the 3 by 3 grid. The two example grids below are NOT winning positions:

Grid #1:
 --- --- --- --- ---
|   |   |   |   -   -
 --- --- --- --- ---
|   |   |   |   -   -
 --- --- --- --- --- 
|   |   | O | O - O -
 --- --- --- --- ---
This is not a winning move because two of the O's are outside the playing field, despite the fact that it forms a 3 in a row.
Using the character assignment stated below, this grid pattern can be achieved with 99372467643.

Grid #2:
 --- --- --- --- ---
|   |   |   |   - O -
 --- --- --- --- ---
|   |   |   | O - X -
 --- --- --- --- --- 
|   |   | O | X - X -
 --- --- --- --- ---
This is not a winning position because two of the O's are outside the playing field.
Using the character assignment below, this grid pattern can be achieved with 939318836537734654

In the examples below, 1, 2, and 3 mean drop in the leftmost, middle, and rightmost column respectively. 4, 5, and 6 mean to move the top, middle, and bottom slider to the right respectively, and 7, 8, and 9 mean to move the top, middle, and bottom slider to the left respectively.

Examples

Input will be in the form of a string
Output will be a list of lists, with each sub-list representing a row(I'm Python programmer so this list format might not be compatible with all languages). 
The first, second, and third sub-list correspond to the top, middle, and bottom row of the 3 by 3 grid respectively. 
The output will have 'O' for the O pieces, 'X' for the X pieces, and an empty string for empty spaces.

Input: 123332
Output:
[['','','O'],
 ['','X','X'],
 ['O','X','O']] 

Input: 33387741347
Output:
[['','',''],
 ['','','O'],
 ['X','O','X']]

Input: 2283911752
Output:
[['','X',''],
 ['O','X',''],
 ['O','X','']]

Input: 228374739
Output:
[['','',''],
 ['','',''],
 ['X','X','X']]

Input: 8873334917349
Output:
[['','',''],
 ['','','O'],
 ['X','X','O']]

Input: 799333466
Output:
[['','',''],
 ['','',''],
 ['','','']]

Input: 99372467643
Output:
[['','',''],
 ['','',''],
 ['','','O']]

Input: 939318836537734654
Output:
[['','',''],
 ['','',''],
 ['','','O']]

This is , so shortest code wins!

My concerns about this challenge:

Are the rules of this game explained enough? Do you understand this game?

Is this a good challenge overall?

Are the examples correct(if you understand the rules)?

Should I put more examples(or if you understand the rules, could you supply me with some)?

What other tags can this challenge fit into?

| |
\$\endgroup\$
  • \$\begingroup\$ Welcome to the site! Generally it's a good idea to leave challenges in the Sandbox for at least a few days to give people time to review. Even more so if you have questions/concerns about your challenge. \$\endgroup\$ – Dingus Aug 2 at 4:51
  • \$\begingroup\$ @Dingus The problem is I already posted it so what do I do now? \$\endgroup\$ – Aiden Chow Aug 2 at 7:01
  • \$\begingroup\$ Actually I was referring to future challenges. For this one, there are probably two options: 1. Leave it on main, responding to feedback in the comments. 2. Delete the main post, wait a while (maybe a week) for more feedback here, then repost/undelete on main. The choice really depends on how much needs to be done to iron out the kinks. \$\endgroup\$ – Dingus Aug 3 at 0:11
  • 1
    \$\begingroup\$ If the moves result in any unpermitted moves, then output any falsey value challenges usually assume only valid input unless the challenge itself is to determine only if the input is valid or not. \$\endgroup\$ – Noodle9 Aug 4 at 19:30
  • \$\begingroup\$ @Noodle9 Ok so should I take that out? \$\endgroup\$ – Aiden Chow Aug 5 at 2:04
  • \$\begingroup\$ Make it one or the other, either assume valid input and output grid. Or determine whether or not input is valid as the challenge. \$\endgroup\$ – Noodle9 Aug 5 at 9:30
  • \$\begingroup\$ @Noodle9 Ok edited. \$\endgroup\$ – Aiden Chow Aug 5 at 18:02
4
\$\begingroup\$

Note: this challenge is a work-in-progress, so suggestions would be appreciated

Questions for meta:

  • How can I prevent people from just using SHA or MD5 one-way compression?
  • are these language restrictions fair?
  • is this scoring system fair?
  • are there any obvious cheap answers?
  • what other tags should be added?
  • what should the challenge title be?
  • will these restrictions adequately prevent people trying to cheat their way through?
  • should a limit be put on a password length? Should I limit passwords to ASCII printable characters?

The challenge

Your challenge is to first choose a "password" (please do not use your actual password). Then, you will create a program which will output a truthy value if and only if this password is given as input, falsy otherwise. Your goal will be to make it so others are unable to reverse-engineer this password (and you will keep this password secret for now).

Scoring

The scoring for this challenge is somewhat different than regular . During the first two weeks from when an answer is posted, other users will have the opportunity to try to crack your password by reverse-engineering your code. If anyone gets your password correct during this two week period, your answer will be marked as cracked. If two weeks pass without users finding the password, your answer can be marked as safe once you share the password (again, please do not use your actual password, you should make up a new one that you don't use anywhere).

Note that you may use any tools at your disposal (online tools, brute-force attacks, modified code, etc) to extract someone else's password from their code.

Of all the safe answers, the one with the shortest source code (i.e. ) wins!

Rules

To make things fair for everyone, you may only use languages that appear on TIO, or languages that have well-written documentation and are used somewhat widely. You must also provide a link to try your code online that anyone can access (as such, you may not use languages behind paywalls like MATLAB but Octave is still on the table because it's free).

Even if you don't want to post an answer, feel free to try to crack any of the existing answer's passwords! If you get a password, you can simply leave a comment on that answer and that answer will be cracked.

Note

If you edit the code in your answer, the two week period will reset! You may edit any explanations in your answer freely (I will verify that any answers marked safe did not cheat).

tags: code-golf

| |
\$\endgroup\$
  • \$\begingroup\$ Example answer \$\endgroup\$ – Daniel H. Aug 19 at 12:38
  • \$\begingroup\$ Surely any cryptographic hash function (which are implemented in many languages) will make it easy to generate an impossible-to-crack answer? For instance, in R I can write test=scan(,'');if(digest::digest(test,"md5")=="b6778692586dc649267723ccc3356fad")TRUE else FALSE and I'll be pretty confident that nobody will crack my password... \$\endgroup\$ – Dominic van Essen Aug 19 at 15:10
  • 1
    \$\begingroup\$ That is a good point. It seems like this challenge is similar to just writing a hash function. You might want to add other ideas to make the challenge more interesting \$\endgroup\$ – thesilican Aug 19 at 16:06
  • \$\begingroup\$ That's what I was about to write, any hash function with a hidden default salt depending on the language, or anything like that, could be hiding the password easily enough. \$\endgroup\$ – V. Courtois Aug 19 at 16:06
  • \$\begingroup\$ @DominicvanEssen is this an actual MD5 hash? I was unable to reverse it (note that a lot of MD5 hashes can be reversed with online tools like this). Note that for this challenge people would be allowed any and all tools at their disposal to crack passwords. This means people are very much allowed to reverse-engineer code in any ways they please \$\endgroup\$ – Daniel H. Aug 19 at 16:06
  • \$\begingroup\$ Answering in many esolangs could hide the password easily enough, too. If I answer in Lenguage, Unary, Mariolang,... \$\endgroup\$ – V. Courtois Aug 19 at 16:07
  • \$\begingroup\$ @V.Courtois this is true, but the point is not to read the password in the source code. The point of the challenge would be to reverse-engineer their code to crack a password (so documentation and online tools are all fair game). Also, Unary will likely be an invalid language because people must be able to actually run the program online (and Unary programs are usually way too big to run online) \$\endgroup\$ – Daniel H. Aug 19 at 16:08
  • \$\begingroup\$ Now that I think about it, any type of loop could hide the password easily enough, too. But even with what I said before and what I'm saying now, I think this challenge has to exist (if not existing already), because having many valid answers is not a problem (not to me, at least). \$\endgroup\$ – V. Courtois Aug 19 at 16:09
  • \$\begingroup\$ @DominicvanEssen also, even if nobody can reverse your password, that's still fine - the winner of this challenge is whoever has the shortest code out of all the uncracked passwords. In other words, this is still a codegolf challenge, but answers can be disqualified if anyone finds the password. So, if you want to win but you don't have the shortest code, you simply have to crack other people's passwords! \$\endgroup\$ – Daniel H. Aug 19 at 16:15
  • \$\begingroup\$ @DanielH. Yes, my example was an actual MD5 hash (the password was mypassword). You're right that some hash functions can be reversed, but there are many cryptographically-secure ones for which this is difficult. \$\endgroup\$ – Dominic van Essen Aug 19 at 16:17
  • \$\begingroup\$ @DominicvanEssen I'm unfamiliar with MD5 hashes, but when I converted mypassword to an MD5 hash using three different online tools I got 34819d7beeabb9260a5c854bc85b3e44 every time instead of the hash in your answer. Could you please provide a TIO link for the R code (when I copy-pasted it into TIO it didn't work for me and I'm unfamiliar with R)? I'd like to try experimenting with MD5 \$\endgroup\$ – Daniel H. Aug 19 at 16:22
  • \$\begingroup\$ I'm afraid that the R 'digest' library is not installed on TIO (making a link was the first thing I tried). \$\endgroup\$ – Dominic van Essen Aug 19 at 16:25
  • \$\begingroup\$ But, after some research, it turns-out that R adds some (consistent) extra characters to the string by default before applying MD5. This behaviour can be switched off, at which point mypassword indeed hashes to 34819d7beeabb9260a5c854bc85b3e44. \$\endgroup\$ – Dominic van Essen Aug 19 at 16:46
  • \$\begingroup\$ how many letters are the passowrds capped at? Are unprintables allowed? \$\endgroup\$ – Razetime Aug 20 at 3:30
  • \$\begingroup\$ @Razetime I might add a restriction of 16 characters, ASCII printables only. I will have to try to balance this cap though - if it's too short, passwords can easily be brute-forced. If it's too long, everyone will just use one-way compression and passwords will never be cracked \$\endgroup\$ – Daniel H. Aug 20 at 11:24
4
\$\begingroup\$

Substandard deviation - Posted

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Innovation is the key to make CGCC live. This is what we (at least, I) want to see on main page. I might not know enough languages, but there might be one (maybe Jelly?) able to compute standard deviation of input stack in 1 byte, therefore getting an unbeatable score of 0. (I don't know if it is a problem, though.) \$\endgroup\$ – V. Courtois Aug 21 at 9:42
  • \$\begingroup\$ You could add a rule on accuracy of expected output (I see you put two digits in test cases, but saying it explicitly could be nice). \$\endgroup\$ – V. Courtois Aug 21 at 9:46
  • \$\begingroup\$ Related. \$\endgroup\$ – V. Courtois Aug 21 at 9:47
  • 1
    \$\begingroup\$ @V.Courtois Thanks for the nice comment! Indeed, a score of 0 might be attainable by certain golfing languages. I don't see that as an issue. It would also be attainable by Unary or Lenguage, but if somebody writes code to compute the standard deviation in Unary or Lenguage, they deserve my upvote! \$\endgroup\$ – Robin Ryder Aug 21 at 9:48
  • 1
    \$\begingroup\$ Challenge accepted. :D \$\endgroup\$ – V. Courtois Aug 21 at 9:49
  • \$\begingroup\$ @V.Courtois I have added the expected accuracy, thanks. Also, Re: built-ins: most language with a built-in for the standard deviation use the corrected standard deviation, which has a denominator of \$n-1\$ instead of \$n\$ (e.g. R's sd, Matlab's std...) \$\endgroup\$ – Robin Ryder Aug 21 at 10:09
4
\$\begingroup\$

Stroke Count of a Chinese Numeral Posted

| |
\$\endgroup\$
  • \$\begingroup\$ Related (not dupe). Stroke count is actually good idea because it avoids the need to hardcode Chinese characters. The description looks clear enough to me. \$\endgroup\$ – Bubbler Aug 5 at 3:11
  • \$\begingroup\$ Might be useful: tio.run/… \$\endgroup\$ – user202729 Aug 5 at 11:45
  • \$\begingroup\$ (to read the test cases) \$\endgroup\$ – user202729 Aug 5 at 11:45
  • \$\begingroup\$ Has it been posted to main? I can't seem to find it. \$\endgroup\$ – V. Courtois Aug 21 at 10:02
  • 1
    \$\begingroup\$ @V.Courtois posted. \$\endgroup\$ – att Aug 25 at 4:54
3
\$\begingroup\$

Metagolf: Catlike Piet

The goal of this is to write a catlike program, which would be executed (in a Unix environment, though you needn't stick to that) by the following:

yourprogram < file > output
piet output

where piet output writes the contents of file to stdout. That is, you're to generate a Piet program which prints the input to yourprogram.

One-liners

Straight line programs can be written in Piet... in straight lines. If you're willing to take a hit to your score, your output can take the form of a string of commands:

=  none (continue color block)
|  push
^  pop
+  add
-  subtract
*  multiply
/  divide
%  mod
~  not
>  greater
.  pointer
\  switch
:  duplicate
@  roll
$  input number
?  input character
#  output number
!  output character

which is trivial to convert to a Piet program with the following (partially golfed) Python code:

def P(s):
 h=v=0;l=len(s)+1;R="P3 %i 2 255 192 0 0 "%(l+2)
 C=[1,3,2,6,4,5];V=[0,192,192,255,0,255]
 for x in map("=|^+-*/%~>.,:@$?#!".find,s):
  C=C[x//3:]+C[:x//3];V=V[x%3*2:]+V[:x%3*2]
  for i in [1,2,4]:R+="%i "%V[(C[0]//i)%2]
 return R+"255 "*4+"0 0 "+"255 "*l*3+"255 0 0 "*2

The dimension of said program is (n+3) x 2 if there are n characters in the string.

Scoring

Your code will be judged on the maximum dimension of the images that it outputs.

  • Part 1: Take the maximum score taken over all ascii codes (that is, single-character inputs), discounting EOF.

  • Part 2: Take the score for the input "Hello. My name is Inigo Montoya. You killed my father. Prepare to die."

Your score is the product of the scores in part 1 and part 2.

Punishment: Double your score if you write one-liners as above (that is, if you don't output an image).

Bonus: If your program is written in Piet, take the square root of your score above.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ It took me a while to understand the task as "Write a program taking INPUT which produces as output a piet program that takes no input but produces INPUT." I think it is a interesting and challenging, but it's reception will depend entirely on how many people are willing to learn/futz-around-in/deal-with piet. And I have no feel for how many that is. \$\endgroup\$ – dmckee --- ex-moderator kitten Jul 7 '11 at 3:12
  • \$\begingroup\$ @dmckee; would it be better if I just used a reduced instruction set, and only ask for the instruction stream? I think this is still challenging with {push 1,duplicate,add,subtract,multiply,output}. Come to think of it, if I restrict to {push 1,duplicate,add,output}, there's a reduction to some awesome algorithms. \$\endgroup\$ – boothby Jul 7 '11 at 4:48
  • \$\begingroup\$ I did this in piet some time ago: craigoclock.blogspot.com/2011/05/metaprogramming-in-piet.html \$\endgroup\$ – captncraig May 21 '12 at 18:31
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) \$\endgroup\$ – programmer5000 Jun 9 '17 at 15:22
3
\$\begingroup\$

Chess move

The Challenge

Write a program that gets a string containing a chessmove and a chessboard as input, and then outputs the chessboard.

Requirements

The chess move will have this format:

<from square><to square>[<promoted to>]

Examples:

d2d4
f8g7
a7a8R

The chessboard format is not fixed, but there must be a 1 to 1 relation between the board and the string to represent the board. Also the format of the input must bet the same as the format of the output. Two suggestions of what it could look like:

rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR

rnbqkbnr pppppppp 00000000 00000000  00000000  00000000 PPPPPPPP RNBQKBNR

It is not required to store anything except the location of the pieces, and validity of moves can be assumed.

Scoring

Base score is character count (assuming your program can move pieces for all moves)

Bonus multipliers:

  • If the program updates the promoted piece, divide by 2
  • If the program also moves the rook when castling, divide by 2
  • If the program also removes the pawn when capturing en passent, divide by 2

The moves, and castling & en passent in particular are explaned on Wikipedia.

So basically writing a 100 character solution for the base problem gives the same score as an 800 character solution with all bonus multipliers.

Examples

If you would choose to use one of the board formats above, your input would look like one of these strings:

e2e4 rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR

e2e4 rnbqkbnr pppppppp 00000000 00000000  00000000  00000000 PPPPPPPP RNBQKBNR

Your corresponding output string would then be one of these:

rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR

rnbqkbnr pppppppp 00000000 00000000  0000P000  00000000 PPPP0PPP RNBQKBNR
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Before I get on to more specific criticisms: as presented, without the bonus this is too trivial to be interesting. I suggest removing some flexibility: require Fen notation for the board position and algebraic notation for the move, and making the current bonus options mandatory. On specifics: it's not clear why you talk about storage; and the board position notations you suggest don't include enough information to know whether en passant is possible. \$\endgroup\$ – Peter Taylor Dec 22 '13 at 23:56
  • \$\begingroup\$ @PeterTaylor I agree that compared to chess programs this may be trivial, but I would like to make it a golf challenge. Compared to the hot code golf questions this is quite elaborate already in its basic form. (For a good solution the board design may need to be changed drastically). It is true that there is no attention to the legality of moves (whether it is possible to capture en passent) but for a mere viewer this is not required so I am not too worried about this. So far the chess questions seem to get very few answers as they tend to be complex and I hope to offer relatively easy entry. \$\endgroup\$ – Dennis Jaheruddin Dec 30 '13 at 11:02
  • 2
    \$\begingroup\$ Your point about en passant is valid - you had said in the spec to not worry about legality. I'll try to convince you of my first point: without the bonus, this reduces to: a) parse first four characters into (col 1, row 1, col 2, row 2); b) take board as a 64-char string; c) board[8*row_2+col_2] := board[8*row_1+col_1]; board[8*row_1+col_1] := ' '; print board. This is trivial compared to any good golf question. (Note that the hot questions at the moment are neither golf questions nor good questions). \$\endgroup\$ – Peter Taylor Dec 30 '13 at 12:14
  • \$\begingroup\$ This sandbox post has had little activity in a while. Please improve / edit it or delete it to help us clean up the sandbox. Due to community guidelines, if you don't respond to this comment in 7 days I have permission to vote to delete this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 15:40
3
\$\begingroup\$

Black Box

Your task is to analyze a given situation for the game Black Box. Given a sequence of guesses and answers, your program is to either print the solution or suggest the next move.

The game

The board consists of 8×8 cells, with edges labeled like this:

I'll probably create nice images here, particularly to make sure that the squares of the board are really square.

 abcdefgh
i        I
j        J
k        K
l        L
m        M
n        N
o        O
p        P
 ABCDEFGH

The player shoots rays into the interior of the box, where they might get deflected, reflected or absorbed. He is told the position where the ray leaves the black box again, and from that has to deduce the positions of 4 atoms inside the black box.

I'll have to include more of the game rules here, but for now see Wikipedia.

Input and output

Input is a sequence of line, each consisting of two characters. The first denotes the point where the ray of light enters the black box, the second the place where it comes out again. In the case of a reflection, both characters will be equal. In the case of a hit, the second character will be -.

If the input is enough to fully determine the locations of the atoms, then output should be four lines giving the coordinates of each atom. The lines should be two lower case characters each, the first giving the row and the second giving the column of the found solution. The atom positions must be printed in lexicographical order.

If the input is consistent with more than one set of atom positions, then the output should consist of a single line containing a single character, which is the location where the next ray should be shot. That location has to be chosen in such a way that it can help find the solution. This is the case unless all of the atom positions consistent with the input so far would produce the same output for this next ray as well.

Your output has to be terminated by a newline character.

Examples

Let's take the atom configuration the Wikipedia article uses as an example as well:

 abcdefgh
i        I
j        J
k O    O K
l        L
m        M
n   O    N
o        O
p      O P
 ABCDEFGH

If the input were

cf
D-
Em
HH
Co

then the output should be

kb
kg
nd
pg

but if the input were only

Em
HH

then the output might be for example

K

Scoring

This is code golf, so shortest answer wins. However, I'll only accept answers which are practical in so far as they compute their result in reasonable time. I'd say no more than five minutes on my system where I'll evaluate the answers, and I'll simply hope that correct solutions will be much faster and incorrect ones much slower, so that the speed of my system doesn't make a difference. A submission which gives a wrong answer for one of my test cases will be disqualified until it gets fixed. I will probably point out the problem in a comment to that post.

| |
\$\endgroup\$
3
\$\begingroup\$

Create a program with "exact repetition" in its source code

The task is to create a program, with the following restrictions placed on the printable ASCII characters in the source code: choose some k > 0.

  • Every non-alphabetic character has to appear exactly k times.
  • Every alphabetic character has to appear at most k times.
    • This rule differs from the former in order to avoid boring dummy identifiers while still making it a challenge to choose good library functions to call.

Character set definitions used:

  • Non-alphabetic characters are !"#$%&'()*+,-./0123456789:;<=>?@[\]^_{|}~ and '`' (backtick).
  • Alphabetic characters are ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.

Note that no restriction is placed on characters outside of the range of printable ASCII characters (including control codes, tabs, newlines, higher unicode codepoints, etc).

What the program does is up to you; be creative. Some general guidelines:

  • Programs that do something interesting might have better chances, although more impressive code structure (i.e. fewer comments) is also beneficial.
  • Stuffing excess characters in comments is boring, and should be avoided/is discouraged.
  • Dead/no-op code isn't terribly interesting either, but is probably unavoidable and at least has to conform to the language's grammar.

This is : whatever has the most upvotes at Feb 1, 2014 gets accepted as the winner.


Example answer (C)

#
#
/*$$@``*/_[]={9.};main() {printf("He%clo \
world!%c\
",2^7&!8.&~1|~-1?4|5?0x6C:48:6<3>2>=3<++_[0],'@'^79-5);}

Prints "Hello world!" (adapted from an answer to another question). Probably wouldn't score a lot (since what it does isn't terribly interesting). Each of the non-alphabetic characters appear exactly twice, and no alphabetic character appears more than twice.


For meta: I want to post this, but I'm worrying that "do something interesting" might give too little guidance and the question won't receive many answers.. thoughts? Is it good as-is, or should I come up with some task that one should be required to implement (and possibly change the ruling to code-challenge, with length + 2^(characters-in-comments) as the score)?

| |
\$\endgroup\$
3
\$\begingroup\$

4 and 20 baked in a π

While some might describe π as a string of seemingly random numbers, one can also look at it in a way similar to a monkey with a typewriter. Eventually, it should calculate out to something more interesting. For example, the sequence 1337 shows up 4,814 places to the right of the decimal. At 700,731 places right of the decimal, you'll find the sequence 160151, which is "pi" represented as ASCII (although you'll find a 'pointer' to it much faster, as the sequence 700731 begins at 29,830 digits to the right).

So, your task is to make a program to find things in π. Your program will accept a positive integer and output the number of places right of the decimal point that number appears. To keep the run times down, input can be limited to numbers in the range of 0 to 1000 (without leading zeros).

Example: Using 415 as the input, the output should be 2:

3.14159
   ^

Rules:

  • You can not use any precalculated values of π, including language constants, built in functions that return π or digits of π, or any resource outside the code itself (such as files or websites).
  • You can not use any trig functions to calculate π.

Bonus points if you find the sequence 072 101 108 108 111 044 032 087 111 114 108 100 033.

This is code golf, so lowest score wins.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ It's not clear to me whether you require answers to support leading zeroes. Also: program, named function or snippet? And how indexed? (Giving 415 as a test case would be a good way to answer the last question) \$\endgroup\$ – Peter Taylor Mar 11 '14 at 6:58
  • 3
    \$\begingroup\$ Isn't this just Calculate 500 digits of pi with a search function tagged on at the end? By the way, your bonus points are quite safe — even if you searched a trillion trillion trillion digits of pi, your chance of finding an arbitrary 39-digit sequence would still be less than 0.1%. \$\endgroup\$ – r3mainer Mar 11 '14 at 14:59
  • \$\begingroup\$ Edited to clarify leading zeros and indexing. @squeamishossifrage - Yes and no. The number of digits to find the answer depends on the input, which both limits the choice of algorithm to generate the search space and gives more ample room to golf the integration of the search function. The worst case is under 10000 digits for n between 0 and 1000. I suppose I could put in a time limit of a couple minutes and expand the range of n to 10000 (worst case is just under 390k), but that seems obnoxious. Thoughts? \$\endgroup\$ – Comintern Mar 11 '14 at 17:20
  • 1
    \$\begingroup\$ @AlexA. - Not a drug reference. \$\endgroup\$ – Comintern Apr 1 '15 at 22:34
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) Due to community guidelines, if you don't respond to this comment in 7 days I have permission to adopt this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:15
3
\$\begingroup\$

Create a calendar

We all know HDD-space is precious and bandwidth is expensive, therefore it is best to reduce the size of your executables. Let's start with your calendar:

Your task is to build a calendar app in at most 512 bytes. The calendar must at least support the following features, but additional features may gain you additional upvotes:

  • It must be able to show the current month with the current day highlighted
  • The user must be able to find out the week day of each day

Rules:

  • Maximum code length is 512 bytes (counted as UTF-8 without BOM)
  • You may subtract the bootstrapping code (i.e. int main(int argc, char **argv) in C or <?php in PHP) and imports from the final size to allow for more verbose languages to be in
  • You may use standard time / date functions of your programming language, as long as they don't allow you to output a ready to use calendar
  • No network access (I said bandwidth is expensive!)
  • Voters decide on the amount of features / look and feel / creativity

This needs a tag for the size restriction, any suggestions?

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ "bandwidth is expensive" <sup>[citation needed]</sup> \$\endgroup\$ – John Dvorak Mar 22 '14 at 5:27
  • 1
    \$\begingroup\$ Seems rather close to Output: Calendar Month \$\endgroup\$ – Peter Taylor Mar 22 '14 at 5:33
  • \$\begingroup\$ Who decides what counts as bootstrapping code? It seems odd to arbitrarily exclude code like that, and the examples you gave can be golfed a lot: they're more or less equivalent to main(){ and <? respectively. \$\endgroup\$ – Wander Nauta Mar 24 '14 at 20:49
  • \$\begingroup\$ @WanderNauta Bootstrapping code is the code that's essentiell to get a working noop program. \$\endgroup\$ – TimWolla Mar 24 '14 at 21:00
  • \$\begingroup\$ @TimWolla That definition won't fly. A zero-byte file is a working noop PHP script, for example. \$\endgroup\$ – Wander Nauta Mar 24 '14 at 21:01
  • 1
    \$\begingroup\$ @WanderNauta A zero byte file is a working noop in every language. \$\endgroup\$ – TimWolla Mar 24 '14 at 22:12
  • \$\begingroup\$ So what's bootstrapping code then? :) \$\endgroup\$ – Wander Nauta Mar 24 '14 at 22:53
  • 1
    \$\begingroup\$ for the limit I'd say code-shuffleboard or restricted-source \$\endgroup\$ – Einacio Mar 26 '14 at 15:57
  • \$\begingroup\$ This sandbox post has had little activity in a while. Please improve / edit it or delete it to help us clean up the sandbox. Due to community guidelines, if you don't respond to this comment in 7 days I have permission to vote to delete this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:28
3
\$\begingroup\$

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.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ 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? \$\endgroup\$ – Peter Taylor Apr 4 '14 at 9:50
  • \$\begingroup\$ Thanks for pointing. I re-written the phrase in the answer. You can use every ASCII character in the output (as usual ASCII art). E.g. I used only + symbol, but one could makes round edges using symbols like \ or / etc.. \$\endgroup\$ – Antonio Ragagnin Apr 4 '14 at 9:55
  • \$\begingroup\$ edited again... \$\endgroup\$ – Antonio Ragagnin Apr 4 '14 at 10:09
  • \$\begingroup\$ Can you define the input that will be used by all the participants? It's necessary to have only one input to compare the outputs of the different answers. The first example is too simple and the last one is too long. So I suggest to use something between these 2 examples. \$\endgroup\$ – A.L Apr 4 '14 at 17:29
  • \$\begingroup\$ Thanks, I chosen a cute panda as input. \$\endgroup\$ – Antonio Ragagnin Apr 6 '14 at 8:09
  • 1
    \$\begingroup\$ one could let this input (…) could became → try something like "this input (…) could become" outpuit → output \$\endgroup\$ – user2428118 Apr 7 '14 at 13:31
  • \$\begingroup\$ I edited it now, so do you people thinks it is a good question? \$\endgroup\$ – Antonio Ragagnin Apr 9 '14 at 17:15
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) Due to community guidelines, if you don't respond to this comment in 7 days I have permission to adopt this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:32
  • \$\begingroup\$ Hi @programmer5000 , I already asked such a question. Do you mean to re-use it again? See: codegolf.stackexchange.com/questions/26139/… \$\endgroup\$ – Antonio Ragagnin Jun 12 '17 at 13:39
3
\$\begingroup\$

Hi, first time golf questioner, hopefully I'm doing it right!

Maths Trade Calculator

A maths trade (or "math" trade if you prefer) is a way of calculating complex trades of arbitrary items in a circle of participants where not all participants want all items.

X participants have an item they would like to trade. Each participant is assigned a unique number, and provides a list of (numbers identifying) the items they would willingly trade their item for. They may provide an empty list (i.e. they would rather not trade).

Input

X lines, one for each participant, comprising a unique number identifying them, followed by a colon, then a comma-separated-list of numbers identifying other items that they would trade for. e.g.:

1:2,3,4
2:
3:1,4
4:2

The numbers identifying the participants will not necessary be in order, nor will they necessarily be 1 to X. You may assume that they will be numeric.

This string can be in STDIN, or an argument to a function, or similar and can be followed by a new-line or not, whatever the coder prefers.

Output

One or more trade loops in which all participants are making trades they're happy with. Each loop should be on a new line and comprise a participant number, followed by "->", followed by the participant they should give their item to, then another "->", and another participant number etc, until the loop is closed and the last participant number matches the first one. Another line is added with the number of completed trades. e.g.:

1->3->1
2

Participants for which no valid trade is possible are omitted.

Output can be via STDOUT, or returned as a string, or something else, with an optional final new-line.

Trade rules

  1. A participant may not be involved in more than one trade
  2. A participant may not receive an item that they didn't want
  3. All loops must be closed
  4. Maximum number of possible trades should be completed (i.e. no submitting a zero-trade output and claiming it's valid). If there are multiple permutations, pick whichever you prefer.

This is a code golf challenge, so shortest working code wins.

Some more example inputs and possible outputs

1

1:2,3,4,5
2:3,5,7,9
3:1,2,5,6,10
4:
5:1,2,3,4,10
6:5,7,9
7:3,6,9,10
8:1,2,4,10
9:1
10:9

1->9->10->3->1
7->2->5->6->7
8

For instance, in this trade: 9 stated that he would accept 1's item in a trade, 10 stated that he would accept 9's item, 3 would accept 10's and 1 would accept 3's. In the second loop, 2 receives 7's item, 5 receives 2's, 6 receives 5 and 7 receives 6's. (Other outputs are possible from this input.)

2

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

0

3

1:5,9
5:1
9:1

1->5->1
2

1->9->1 is also valid in this case, but both cannot be completed. Either is acceptable.

Thanks for reading guys! Let me know if there are any improvements I can make.

| |
\$\endgroup\$
  • \$\begingroup\$ "can be followed by a new-line or not, whatever the coder prefers." How flexible is this? For instance, can I use trailing commas, like 1:2,4,7, if it makes my code shorter? \$\endgroup\$ – Martin Ender May 2 '14 at 17:28
  • 2
    \$\begingroup\$ Will the participants always be numbered 1 to n and their input lines provided in order? If so, state it. If not, include a test case which fails if an implementation decides to ignore everything before the : in each input line. \$\endgroup\$ – Peter Taylor May 5 '14 at 10:02
  • \$\begingroup\$ @m.buettner I would say a trailing comma is not acceptable, on the end of any line, or the end of the input/output. \$\endgroup\$ – Johno May 6 '14 at 8:55
  • \$\begingroup\$ @PeterTaylor Good tip. I'll correct the question to state that you can't assume that the numbers will be 1 to n, in order. \$\endgroup\$ – Johno May 6 '14 at 8:57
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) Due to community guidelines, if you don't respond to this comment in 7 days I have permission to adopt this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:39
3
\$\begingroup\$

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.
| |
\$\endgroup\$
  • \$\begingroup\$ I suppose input is via STDIN? You might want to mention that explicitly, because at least the architect could just as well take the input via command-line arguments. \$\endgroup\$ – Martin Ender May 15 '14 at 15:34
  • \$\begingroup\$ updated. I have a driver/referee program which will handle I/O; I'll update it to use stdin/stdout since that will no doubt be the easiest standard. \$\endgroup\$ – wrongu May 15 '14 at 16:04
  • \$\begingroup\$ @m.buettner before de-sandboxing this, would you be willing to try the test kit? \$\endgroup\$ – wrongu May 15 '14 at 18:20
  • \$\begingroup\$ I'd love to, but I'm afraid I'm too busy this week. Try ask for help in the chatroom. \$\endgroup\$ – Martin Ender May 15 '14 at 18:35
  • \$\begingroup\$ Possible architect issue: With this scoring method (steps/walls), you can get a minimum score of 3 by simply putting the start/finish right next to each other with a single wall between. It takes three steps to go around. Most actual mazes I've seen have too many walls to make a score of 3 likely, much less guaranteed. \$\endgroup\$ – Geobits May 16 '14 at 13:51
  • \$\begingroup\$ Thats a problem. What if the dist function was shortest path? Then only mazes which cause detours could get a score > 1 \$\endgroup\$ – wrongu May 16 '14 at 15:09
  • \$\begingroup\$ That would probably be better. That way it's scored on best vs actual. It would take away the incentive to figure out how to build hard mazes with few walls, though, which was interesting itself. \$\endgroup\$ – Geobits May 17 '14 at 3:01
  • \$\begingroup\$ Hey rangu... not sure if you're still planning to do this thing, but overactor just said something in chat which reminded me of your challenge and might be a neat way to avoid the combined score: split this up into two code-challenges, one for maze generation and one for maze solving. Each code-challenge's benchmark set (to determine the scores) would be the outputs of the other challenge's participants. Then you could just pick a best solver and a best generator independently. \$\endgroup\$ – Martin Ender Aug 1 '14 at 11:18
3
\$\begingroup\$

Author note: I was thinking about new genres today, and I had an idea. What if there could be a challenge that encourages people to write good code, instead of the code-golf gibberish we all know? Here's a challenge that attempts to do that. (This could even possibly be a , which would be great because it would bring in a greater high quality question volume to the site, but I'm terrible at coming up with names. Feel free to suggest something in the comments.)


Build your own image editor

(?)

For this challenge, you will create the best GUI image editor that can perform the most tasks that you possibly can... from scratch.

Tasks and scoring

Here are the features / tasks used to score your program. Each task is worth a certain amount of points, which is specified in brackets before the task description. For convenience, each task will also be prefixed by an ID string so that you can refer to them when describing your program.

  • [1 A] Brush tool: Simple, click and drag the mouse to draw freestyle doodles. Must draw a contiguous path.
    • [1 A1] Ability to change the brush size.
  • {TODO: etc., add more}

Requirements

Your editor must conform to the following requirements:

  • Must accept input via the mouse. Tools (brush, flood fill, etc.) can be switched and configured with keyboard shortcuts, by clicking icons with the mouse, through a menu, or however you would like.
  • You may not use a single built-in function to accomplish one or more of the tasks. For example, if your language has a built-in image flood fill function, you may not use it and must build your flood fill from scratch.

Final score and voting

This is the syntax you should use to describe your score in your answer:

# {language}, {your score} score
<sup>(features implemented: {A, A1, ...})</sup>

    {your code here}

{description, comments, other notes, etc. here}

The amount of votes your post has (upvotes minus downvotes) will be multiplied by {TODO: figure out a good number} and added to your score. (Do not add this to the score in your post, since votes change constantly; I will add them manually.) Voters, please vote according to the following criteria:

  • elegance and readability of the source code
  • ease of use of the image editor and how powerful it is
  • remember to sort by "active" so that you're voting for new answers too, and not just the top voted ones!
| |
\$\endgroup\$
  • 3
    \$\begingroup\$ Your questions should be reasonably scoped. If you can imagine an entire book that answers your question, you’re asking too much. A really good answer to this would run into millions of lines of code. \$\endgroup\$ – Peter Taylor Jun 4 '14 at 15:52
  • \$\begingroup\$ @PeterTaylor Yes, I was a little worried about that, but if it's not broad enough, it will be easy to just implement all the features. Any suggestions for fixing this? I was thinking of adding a "brevity" criterion in the voting section, but that doesn't seem like an ideal solution. \$\endgroup\$ – Doorknob Jun 4 '14 at 16:00
  • 3
    \$\begingroup\$ To be honest, the site for good code is Code Review. They already have a monthly challenge, for which they post snippets for review. I don't see a need to copy them. \$\endgroup\$ – Peter Taylor Jun 4 '14 at 16:12
  • \$\begingroup\$ @PeterTaylor Wait, isn't Code Review for questions and answers, not challenges and contests? In any case, is there any reason for that to prevent us from posting challenges like we always have? \$\endgroup\$ – Doorknob Jun 4 '14 at 16:17
  • \$\begingroup\$ meta.codereview.stackexchange.com/questions/tagged/… . Surprised you don't know about it, given how dedicated you are to spying on them ;) In general, if a question is on topic for multiple stacks then there's no obligation to do the sensible thing and post it on the one which it best fits, but you should expect people to ask why you're not doing the sensible thing. I think you're going to have to work hard to turn this into a question which fits this site, whereas it's already a good fit for CR's challenge programme. \$\endgroup\$ – Peter Taylor Jun 4 '14 at 16:31
  • \$\begingroup\$ @PeterTaylor Hmm, that's strange. Wouldn't that be more on-topic here? (And I only occasionally pop in to their chat/meta to see what they're up to. :-P) \$\endgroup\$ – Doorknob Jun 4 '14 at 16:32
3
\$\begingroup\$

Help Joe Bloggs with his password hash

Joe was confidently using "password1" as his main password to all his accounts until one day he received an e-mail from fBay. His account has been compromised and he must change his password immediately. Yet worse, the attacker had access to all Joe's accounts. Being an engineer, Joe thought: What if I could hash somehow my password using a keyword? I wouldn't need to remember any passwords and I would have a different one for each account.

Joe then creates an algorithm - he takes the domain name as a key and creates the password for each of his account consisting of:

1. (<consonants><vowels>)(alternating case: lower, capital, lower...)
2. <number of consonants><number of vowels>
3. <sum of consonants and vowels numbers converted to a character on US Qwerty Keyboard>

Joe then opens an account on SO to create a new code golf challenge. He uses stackoverflow as a key to generate password:

1. sTcKvRfLwAoEo - consonants and vowels in alternating case
2. 94 - 9 consonants, 4 vowels
3. 9+4=13, 1+3=4, Shift+4=$

Therefore, Joe's password for stackoverflow is: sTcKvRfLwAoEo94$

Challenge

Create a shortest function to generate a password given the rules above. The code should accept a string type parameter d and return/display the generated password.

Rules

  1. Only Latin letters from the input should be used. Any other characters should be ignored.
  2. Minimum input length is 1 letter. (guys at q.com need passwords as well!)
  3. Assume Y is a vowel
  4. If vowels or consonants are missing, use 0 accordingly. E.g. input a would result in a01!
  5. Shortest code wins

List of vowels and consonants

US qwerty keyboard

| |
\$\endgroup\$
  • \$\begingroup\$ Thanks for the feedback @m.buettner. I meant to say, without using any libraries. The problem is, that people become lazy to think sometimes and just dive straight away to use Linq where a bit of thought will do \$\endgroup\$ – mai May 28 '14 at 13:14
  • \$\begingroup\$ Well actually you can, I'm just checking now. You can do a lot of manipulations on strings without libraries. \$\endgroup\$ – mai May 28 '14 at 13:18
  • \$\begingroup\$ Looping over string characters, concatenation work perfectly. Nevertheless, I've updated the challenge. If a function to depend on a library, it must be included in the character count. \$\endgroup\$ – mai May 28 '14 at 13:21
  • 3
    \$\begingroup\$ 1. Strictly speaking, in .Net you don't have strings without libraries. The string keyword is syntactic sugar for a class in mscorlib. 2. As things currently stand, your rule 1 strictly prohibits something and then says what to do if you ignore that prohibition. This is illogical. It's also unclear what "that" in "please inlcude that in characters count" means. Does it mean that each submission should be a program as opposed to a code snippet? If so, state it explicitly. \$\endgroup\$ – Peter Taylor May 28 '14 at 13:32
  • \$\begingroup\$ Hmm.. I don't know how to write it the best way. mscorlib is included by default so that is permissible. I don't want the code to use other libraries as Linq as it's less fun. \$\endgroup\$ – mai May 28 '14 at 13:47
  • \$\begingroup\$ @m.buettner I agree with you. Nevertheless, there will solutions provided in other languages as well (there always are). And I would like the authors of those solutions to think about the best approach in their language of choice without depending on libraries like Linq. \$\endgroup\$ – mai May 28 '14 at 14:00
  • \$\begingroup\$ Does Rule 2 mean ONLY vowels/consonants to be used from input? What about symbols *@#$ etc. Depending on that answer, potentially clarify Rule 5 regarding symbol input. As for Step 3 in the hash, should that progress further, similar to my Appended Numbers game so 103 consonants and 5 vowels would follow as 103+5 = 108, 1+0+8/10+8, etc.? \$\endgroup\$ – Matt Jun 4 '14 at 2:35
  • 1
    \$\begingroup\$ @Matt, clarified - only Latin letters are used from the input. If consonants or vowels are missing, use 0 instead. The sum should progress, until it's <=9. E.g. 103 consonants, 5 vowels: 103+5=108, 1+0+8=9. Then, Shift+9='(' \$\endgroup\$ – mai Jun 18 '14 at 10:36
3
\$\begingroup\$

Diplomacy

Note for Sandbox: I have not finished (or really started) the control program for this game, because I wanted to see if there was interest in it before I dedicated too much time to the project. that means that the rule are still up to be tweaked, so please leave a comment if you have a suggestion, and comment or vote if you are interested in seeing this happen.

Diplomacy is a complex strategy game, with a very entertaining combat system. This challenge will be to write a bot to compete in a simplified version of diplomacy combat.

Rules

Rounds

Countries (bots) will begin the game with 10 health, representing their remaining will to fight. The goal is to eliminate all other Nations by attacking them until they have 0 health.

The game will consist of several rounds. On the first round, all bots will receive 2 numbers as command line arguments: The first will be the total number of countries fighting, and the second will be their number in the list. Each following round, bots will receive a command line arguments containing the actions taken by each player last round and a list of all bots and their remaining health separated by commas, like so

 1:A2,2:S3,3:A4,4:A3 1:10,2:7,3:7,4:1

Each bot must then output a desired action, which is one two commands

  1. Attack a player. This is done by printing the letter A followed by the number of the player you with to attack. For instance, A3
  2. Support a player. This will give the player you support a boosted attack.

Resolving combat

After player have sent in their moves, attack scores will be calculated thus:

  1. All players start with a strength of 1, and one point is added for every player supporting them. For instance, if the moves are 1:A3,2:S1,3:A2,4:S2 then bot 1 has strength 2, bot 2 has strength 2, bot three has strength 1, and bot 4 has strength 1.
  2. After strength has been calculated, bots will deal damage based on their strength. The formula for damage is (Attacker's strength + 1) - (Defender's Strength) In the above situation, player 3 would take 2 damage and player 2 would take 0 damage. Note that, unlike regular diplomacy, attacking a supporter does not cut support.
  3. All attack take place simultaneously and independently. This means that if player 1 and 2 both attack player 4, then they each deal 1 damage. If player 3 were to support player 4, then player 4 would take no damage.

Round Ends

After combat has been resolved, countries that have 0 health will no longer be able to attack or support. However, they still will be listed in the input with an health of 0. When a bot is eliminated, all remaining bots will receive a single point.

Ending the game

The game ends when either 100 turns have elapsed or only 2 or less players remain. At this point, the player with the highest remaining health is the winner and receives 1 point. In case of ties, all tied bots will revive 1 point. If all bots die on the same turn, this is not a tied victory, but mutually assured destruction, and all bots will receive 0 points.

Scoring

The control program will run 100 rounds of the game. The winner will be the country with the most points at the end of 100 rounds.

Code

You may write in any language I can reasonably compile. I will make an effort to compile odd languages, but make no promises as to my ability to do so. Please provide your source code, an explanation, and a command line command to run your program.

Notes
  • You are allowed to write to a file. In fact, you are encouraged to do so.

  • Because this is a game where cooperation is paramount, you are allowed to write bots that work together, with the following restriction:

    • Only two bots can be written by a single player to work together at a time.
  • Standard Loopholes apply. You are not allowed to change the way the control program runs. If you provide invalid input to the control program, the program will just skip your turn. However, you are allowed to spy on other countries files, and all bot programs will be in the same folder at runtime. This is war, after all!

  • I reserve the right to disqualify any country that takes more than about a second to run, or that tries a loophole not mention within. That being said, if it is sufficiently clever I will probably let it go.

I will have source code up soon for a sample country that will be competing, and will post the control program when I finish it.

| |
\$\endgroup\$
  • \$\begingroup\$ "In case of ties, all tied bots will revive 1 point". Is that supposed to say "receive"? "If all bots die on the same turn, ... all bots will receive 0 points." If there are two bots left, each of which has received 1 point from the earlier death of a third bot, and the two bots destroy each other on the same turn, what's the final score for the round? I'm not sure whether it's 0-0-0 or 1-1-0. "You are allowed to write bots that work together": but how can they identify each other? Do they have to use their moves as a covert channel? \$\endgroup\$ – Peter Taylor Aug 29 '14 at 14:28
  • \$\begingroup\$ "Support a player. This will give the player you support a boosted attack." Or defence. Might be clearer to say "boost that player's strength for the turn". Should also state whether or not it's possible to support yourself. \$\endgroup\$ – Peter Taylor Aug 29 '14 at 14:29
3
\$\begingroup\$

Check GenericScript source code for compiler errors

Given the source code for a GenericScript program as input, parse the source code to check that it conforms to the syntax rules for the language. The syntax definition for GenericScript is below. If a part of the source code is found to be invalid, the program should output "Invalid syntax", otherwise it should output "Valid syntax".

Win Criteria

This is code golf. Shortest code wins.

Syntax

Source code will be considered to be valid if it matches the rule for "Program" below.

Program             = Sequence
Sequence            = Statement [Sequence]
Statement           = SequenceBlock | Assignment | If | While | Output
SequenceBlock       = "{" Sequence "}"
Assignment          = Identifier "=" (String | Bool); 
If                  = "if(" Bool ")" Statement ["else" Statement]
While               = "while(" Bool ")" Statement
Output              = "print(" String ");"
Identifier          = {Any sequence of alphanumeric characters prefixed with "var" }
Bool                = StringEquals | Identifier
StringEquals        = String "==" String
String              = StringConstant | OperatorConcat | Input | Identifier
StringConstant      = "'"StringContent"'"
StringContent       = Character [StringContent]
Character           = {Any character except for "'"}
OperatorConcat      = String "&" String
Input               = "read()"

Whitespace is defined as any sequence of the ascii characters 9, 10, 13 and 32. Whitespace characters are allowed between tokens but are not required.

Rules

  1. The answer should be a complete program
  2. Standard input/output allowed
  3. Standard loopholes apply
  4. Universally testable answers only

Test Input

Valid syntax:

print('What is your name?');
varInput = read();
print('Hello ' & varInput);

Invalid syntax:

if(read() == 'DoTask1')
  print('Executing you'r command');
| |
\$\endgroup\$
3
\$\begingroup\$

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.

| |
\$\endgroup\$
  • \$\begingroup\$ @Martin Thanks for your comments! I've updated the question. \$\endgroup\$ – Arnaud Aug 21 '14 at 7:59
  • \$\begingroup\$ Provided the player ignores the troll and goblin (i.e. doesn't try to kiss or kill them), they don't do anything? \$\endgroup\$ – Peter Taylor Aug 21 '14 at 8:30
  • \$\begingroup\$ @Peter you're right. Maybe the player should kill (with bare hands) the goblin in order to get the sword, and then kill the troll (with the sword) to get the key. \$\endgroup\$ – Arnaud Aug 21 '14 at 8:50
  • \$\begingroup\$ "The map must be spatially coherent" still doesn't disallow always going left without ending up in the same room twice, unless you specify that the rooms are all meant to be square (which is what I think you had in mind). Also, I still think that "at least" 30 rooms is unnecessary. Who would implement 8 additional rooms if they don't have to. It will definitely be shorter if I omit the two longest adjectives and just use all available combinations of the remaining ones (giving 30 unique rooms). So you can omit two adjectives and the "at least" right away, I'd say. \$\endgroup\$ – Martin Ender Aug 21 '14 at 9:19
  • \$\begingroup\$ I think it's fine to keep "at least" there for flavour, same with additional adjectives. Also, someone might figure out a way to make the code shorter with a longer adjective (for that reason, having a few more adjectives might be nice) \$\endgroup\$ – FireFly Aug 21 '14 at 9:38
  • \$\begingroup\$ @Martin I've added a criteria "Player should not be able to win in less than 30 turns", to force the golfer to implement more rooms. \$\endgroup\$ – Arnaud Aug 21 '14 at 9:39
  • \$\begingroup\$ @SuperChafouin That doesn't force it though. I just need to place the goblin at the end, troll at the beginning, trunk at the end, so that you need to traverse the map 3 times. \$\endgroup\$ – Martin Ender Aug 21 '14 at 9:51
  • \$\begingroup\$ @Martin It's also here to prevent the dungeon to be too straightforward to solve, e.g. if all the objects are in 5 adjacent rooms near the player start location. \$\endgroup\$ – Arnaud Aug 21 '14 at 10:51
  • \$\begingroup\$ +1 for golfing in Inform 7. \$\endgroup\$ – Lopsy Sep 20 '14 at 2:56
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) Due to community guidelines, if you don't respond to this comment in 7 days I have permission to adopt this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:58
  • \$\begingroup\$ @programmer5000 Yes no problem :-) \$\endgroup\$ – Arnaud Jun 10 '17 at 1:07
3
\$\begingroup\$

Simulate a Quantum Circuit

Work-in-progress until I can make sure I know what I am doing and can finish the spec. or maybe


Quantum computers are the way of the future! Why wait, when you can simulate one now?

Your mission is to determine the output of a quantum circuit given its input and a diagram of logic gates.

Details

You will simulate a single quantum register and apply a series of quantum logic gates to it. A quantum register is a group of qubits. The state of a register is described by a vector of 2^N complex numbers, where N is the number of qubits in the register.

a|000>
b|001>
c|010>
d|011>
e|100>
f|101>
g|110>
h|111>

Above is a representation of a 3-qubit register. Each letter (a b c etc.) represents a complex number. There is an addition restriction that:

|a|^2 + |b|^2 + |c|^2 + |d|^2 + |e|^2 + |f|^2 + |g|^2 + |h|^2 = 1

Quantum gates

Gates are represented by a 2^N x 2^N square unitary matrix, where N is the number of input qubits. All quantum gates have the same number of outputs and inputs, since they neither create nor destroy qubits, they modify them.

A common quantum gate is called the Hadamard gate and acts on a single qubit. The matrix [H] looks like this:

1/Sqrt(2)  1/Sqrt(2)
1/Sqrt(2)  -1/Sqrt(2)

If we let [R] represent the following 1-qubit register:

0.6|0>
O.8|1>

Then the application of the gate is represented by [H][R] and gives the following result:

7*Sqrt(2)/10|0>
 -Sqrt(2)/10|1>

It is still true that the sum of the squares of the absolute values is equal to 1.

(TODO: explain how to apply gates to larger registers)

Measurement

Measurement collapses the state of the quantum register.

(Todo: Explain how measurement works)

Input

Output

| |
\$\endgroup\$
3
\$\begingroup\$

BS

The goal of this challenge is to implement an AI for the game of BS, also known as Bull Shit, Cheat, Bluff, and numerous other names.

The game is outlined in this wikipedia article.

The Rules of the Game

For the purposes of this challenge, the game will work like this:

  1. A standard 52-card deck is dealt out to the players
  2. The current rank is set to Ace
  3. The play order is randomized
  4. The player holding the Ace of Hearts goes first
  5. On each player's turn:
    1. The current player plays some number of cards
    2. The current player states how many of what rank they played
    3. Other players may declare 'BS'.
    4. If any player declares 'BS':
      1. All players are notified of which players declared 'BS'.
      2. The played cards are revealed to all players.
      3. If the played cards are inconsistent with the current player's statement:
        • The current player adds the played cards and all cards in the pile to their hand
      4. If the played cards are consistant with the current player's statement:
        • The last player to declare 'BS' that round adds the played cards and pile to their hand.
    5. If no player declares 'BS':
      1. The played cards are added to the pile, without revealing them.
      2. If the played cards were inconsistant with the current player's statement, the current player may declare 'Peanut Butter'.
    6. If the current player has no cards in their hand, the current player wins.
    7. The current rank is incremented. (If the current rank is King, it becomes Ace.)

The Messaging Protocol

Play will be conducted via messages passed to the standard input and received from the standard output of each program. Each message will be terminated with a single newline character.

Cards

Card ranks are represented as one of A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, or K. Card suits will be represented as one of S, C, H, or D. Cards are represented as the rank, followed immediately by a suit. For instance, the Ten of Clubs would be represented by TC, and the Three of Hearts would be represented by 3H.

A hand of cards will be represented as a space-delimited sequence of cards. For instance, a hand containing the Queen of Spades and the Six of Diamonds could be represented as QS 6D or 6D QS.

Player Identification

A player will be represented by their nickname, followed by a number from 0 to 32768, in parenthesis, formatted as an integer. This number is guaranteed to be unique within a particular game. A player's nickname must have at least one character, can have up to 32 characters, and may only include letters, numbers, and underscores. For instance, a player with nickname ExampleAI and ID number 16480 would be identified in the game as ExampleAI(16480).

When the game begins, each program will recieve a message containing their unique ID:

Unique ID: uniqueID

Each player will reply with their desired nickname:

Nickname: name

Names may contain only alphanumeric characters and underscores.

After all players have responded with their nickname, the standard play sequence begins.

Standard Play Sequence

When a player's turn begins, each player will receive a be given a list of the players and their card counts, in order of play:

Players: player[count], player[count], ... player[count]

Each player will be informed of the contents of their hands:

Hand: initial_hand

The current the player will then receive this message:

Your turn: current_rank 

The current player will reply with a space-separated list of of cards:

Play: list_of_cards

Once they have submitted their play, all players will receive the number of cards, formatted as an integer, along with the current rank:

Player player plays: nunber_of_cards x current_rank

Each other player may then declare BS on that play by sending any message up to 32 characters, containing the capital letters B and S, and otherwise only contains lowercase letters and spaces. So any of Bull Shit, Bananna Split or Bacon Sandwich would be acceptable.

During this period, the current player may declare Peanut Butter by sending any message up to 32 characters, as long as it contains the capital letters P and B, and otherwise only contains lowercase letters and spaces. So any of Peanut Butter, Pancake Batter or Polish Bacon would be acceptable.

In order to allow the game to move faster, if a player does not wish to declare either of these things, they must instead send:

Pass

After all players have responded, all players will receive a list of players who called BS, in the order they called it:

Called BS: player, player ... player

If no player called BS, this message will still be sent --- it just won't have any players listed. If any player did call BS, then all players will recieve:

Player player had played: list_of_cards

If they were bluffing, all players recieve:

Player player was bluffing.

And the current player receives:

Your bluff was called: list_of_cards_recieved

If they were not bluffing, all players recieve:

Player player was not bluffing.
Player last_player receives the pile.

The last player who called BS recieves this message:

You misjudged: list_of_cards_received

The list of cards received will contain, in reverse chronological order, the contents of each play since the last call. (Separate plays will not be delimited in the list.)

If no player declared BS, and the current player was bluffing and declared Peanut Butter, then all players recieve the message:

Player player was bluffing.

If the current player has no cards left in their hand, all players receive this message, and the game terminates:

Player player won!

Otherwise, the next player's turn begins.


Example Game

The following might be considered a typical (abbreviated) message transcript:

Unique ID: 16481
> Nickname: Alice
Players: Alice(16481)[18], Bob(16479)[17], Charlie(16480)[17]
Hand: 2D 7S AS TC 5S JS JC 3C 8H 9D 5D AH 7C 6C 4D KC KH KS
Your turn: A
> Play: AS 2D AH
Player Alice(16481) plays: 3 x A
> PB
Called BS:
Player Alice(16481) was bluffing.
Players: Bob(16479)[17], Charlie(16480)[17], Alice(16481)[15]
Hand: 7S TC 5S JS JC 3C 8H 9D 5D 7C 6C 4D KC KH KS
Player Bob(16479) plays: 2 x 2
> BS
Called BS: Alice(16481)
Player Bob(16479) had played: 2H 2C
Player Bob(16479) was not bluffing.
Player Alice(16481) takes the pile.
You misjudged: 2H 2C AS 2D AH
Players: Charlie(16480)[17], Alice(16481)[20], Bob(16479)[15]
Hand: 7S TC 5S JS JC 3C 8H 9D 5D 7C 6C 4D KC KH KS 2H 2C AS 2D AH
 .
 .
 .
Players: Alice(16481)[3], Bob(16479)[41], Charlie(16480)[8]
Hand: KC KH KS
Your turn: K
> Play: KC KH KS
Called BS: Charlie(16480), Bob(16479)
Player Alice(16481) was not bluffing.
Player Bob(16479) receives the pile.
Player Alice(16481) won!

Your implementation may be written in any language, provided that you, upon request, provide a link to a suitable free-as-in-freedom compiler or interpreter that I can download and run at no cost. You also need to provide a UNIX command that can start your program.

Sandbox Questions

I want to gauge the community's interest in my problem before finalizing the spec and writing the control program.

I also need to get some idea of what sort of time-limiting scheme would be reasonable. In order to be able to to a lot of runs, I will need to be able to ensure that each AI doesn't take too much time to make its decisions, or prevent a stuck AI from holding up a game. I also need to be able to ensure that there is no motivation to deliberately stall a game. For example, if an AI determines that it is very unlikely to win, it might stall in order to prevent the game from finishing.

I would also like feedback on the messaging protocol:

  • Are there any additional messages that you think should be passed?
  • Would it be more convenient/clear if one or more of them were formatted differently?
    • Would it be better to use a different format for the plays message?
    • Would it be better to use different words to help distinguish the plays and played messages?
| |
\$\endgroup\$
  • \$\begingroup\$ It looks like quite a tough challenge, but should be enjoyable! \$\endgroup\$ – Alexander Craggs Sep 4 '14 at 16:54
  • \$\begingroup\$ @PopeyGilbert By the way, there was one thing I accidentally left out that I need feedback on. Specifically, time limits - to deal with intentional stalling, getting stuck, or taking too long to decide. \$\endgroup\$ – AJMansfield Sep 4 '14 at 17:05
  • 1
    \$\begingroup\$ A question and a feedback. Does our program run as "stop and run" or must receive feedback continuously? And for feedback. I honestly think that the whole username things is kinda confusing. Maybe if you just use only unique id? (Like just simple 0,1,2,3 instead of username) \$\endgroup\$ – Realdeo Sep 5 '14 at 8:33
  • \$\begingroup\$ Oh! More things! I also realize that suit doesn't really matter, right? (We only use suit for deciding who goes first), so fmpov, you can ditch the communication protocol for the suit. (No need for S,C,D,H) We can just use simple random from the computer. Question: What will happened if everybody make infinity loop of pass. For time limit, I prefer 1 second. If no response, make it auto pass. (KOTH chess time limit is 2 seconds. That's why 1 second is good enough) \$\endgroup\$ – Realdeo Sep 5 '14 at 8:38
  • \$\begingroup\$ @Realdeo Card suit is also used to distinguish between separate instances of a card. If Alice plays 3x2 (2S 2D 2C), is not revealed, and Bob gets the pile later, and then Bob plays 3x2 (2S 2C 2H), and this is revealed, it is important for Alice that she knows all four Twoes have passed through Bob's hand. There are other ways that can be used as well. \$\endgroup\$ – AJMansfield Sep 5 '14 at 13:29
  • \$\begingroup\$ @Realdeo I am not sure what you mean by "Does our program run as "stop and run" or must receive feedback continuously?". If you mean, "Does an AI program halt in the periods where no response is expected from it?" the answer is no. \$\endgroup\$ – AJMansfield Sep 5 '14 at 13:32
  • \$\begingroup\$ @Realdeo If everybody makes an infinity loop of pass, then eventually someone will run out of cards, since you are required to play at least one card each turn. \$\endgroup\$ – AJMansfield Sep 5 '14 at 13:33
  • \$\begingroup\$ @Realdeo Which is why making a automatic pass after a timeout not work when waiting for a player to decide their play. Perhaps a simple rule like 'if you take more than 1 second to decide what to play, four cards are selected at random from your hand'. \$\endgroup\$ – AJMansfield Sep 5 '14 at 13:36
  • \$\begingroup\$ And if a player has less then 4 cards? I think in some AI website, like aigames.com, they're like forced to give up that hand? You really want to test your entry before put them in the arena(like vsing a bot dummy?) Either way, this is a good challenge =) \$\endgroup\$ – Realdeo Sep 5 '14 at 13:40
  • \$\begingroup\$ @Realdeo Also note that you can actually play more than four cards in one play. A case where you might wish to do this is when: the next player is very close to winning and some other player is close to winning and you believe(all opponents believe(your next opponent will bluff) and the next opponent will not bluff and the next opponent believes(the other opponent close to winning will call BS against them)). A little convoluted, but could happen. \$\endgroup\$ – AJMansfield Sep 5 '14 at 13:42
  • \$\begingroup\$ @Realdeo Just to explain what I mean, is that there are two people close to winning, each of which would like to dump a large stack of cards on top of the other. Because of this, they both let your obvious bluff slide because they believe that will let them dump a large stack on the other. \$\endgroup\$ – AJMansfield Sep 5 '14 at 13:47
  • \$\begingroup\$ Don't worry I understand. This is a really famous high school game in my country. It just... a little bit too complex for CR. When I saw chess KOTH, I was kinda pessimist. This one? This may deserve it's own AI website. #seriously. I'm just trying to simplify this game =) \$\endgroup\$ – Realdeo Sep 5 '14 at 13:50
  • \$\begingroup\$ Let us continue this discussion in chat. \$\endgroup\$ – AJMansfield Sep 5 '14 at 13:50
  • \$\begingroup\$ RE the messaging service, I think the other players should be able to see how many cards the other players have. Also, card counting should be prohibited because that would make the game too easy. \$\endgroup\$ – Beta Decay Sep 10 '14 at 17:31
  • \$\begingroup\$ @BetaDecay First off, according to the protocol, every player is informed of every other player's hand size at the beginning of every round. \$\endgroup\$ – AJMansfield Sep 10 '14 at 18:27
3
\$\begingroup\$

Let's talk about this...

I am planning on hosting a King of the Hill challenge in which bots will have to coordinate each other in order to be successful. The idea is to play a Diplomacy-like game between bots. The engine (still in development) will start the bots and communicate with them via stdin/stdout. There will be three phases:

0. Initialization

Well, this is not a recurring phase, it is just the engine telling each bot his id, the total number of bots participating and a seed, which can be used for generation of pseudo-random numbers (bots need to be deterministic).

1. Talking Phase (10s)

In the Talking phase, bots can send messages to each other (via engine) in order to coordinate their actions. To this end, a common language is necessary. This language should be able to express any ideas, plans and opinions a bot could have. However, not every bot is forced to be able to understand everything. Simpler bots might just ignore messages they do not understand.

Since I would like each player to be able to submit more than one bot, it is forbidden to implement a "secret handshake" by which bots recognize each other and from then on work together unconditionally.

2. Planning Phase (2s)

In this phase, bots submit what they want to do this turn. Each bot has a certain amount of supply (initially five), and can command one action per supply point. There are three possible actions:

  1. Attack another bot
  2. Support another bot's attack against a third bot
  3. Defend another bot

There are some restrictions:

  • Per opponent, you can either attack or defend them, and only once
  • You cannot support an attack against a bot you also defend
  • You cannot attack, defend, support yourself or a dead bot, and neither can you support attacks against yourself

3. Resolution Phase (as short as possible)

After all orders have been submitted, the engine will resolve them simultaneously in the following way:

The defending strength of each bot is the number of bots defending that bot. The attacking strength of each attack is the number of support orders for that attack. Each attack with an attacking strength greater than the defending strength of the attacked bot results in the supply counter of the attacked bot being reduced by one, and the supply counter of the attacker being increased by one.

Support orders which support a non-existent attack do nothing.

Then, all bots with supply of zero or less will be shut down by the engine: they died.

Afterwards, all remaining bots are informed about the decisions of other bots, and a new turn begins with its Talking Phase.

Further Rules

A game will consist of ten plus random number turns, so that "last turn betrayals" are not possible. The supply count of each bot will count towards their total score. I plan an ensemble of about 100 games. The bot with the highest total score wins. Tie-breaker will be the popularity (number of votes).

I am interested in your opinion: do you think that this challenge is too complex? I imagine that the code of a decent bot would be too long to fit in a post. So people would have to use github or pastebin or similar to submit their entries. The main problem imo is the interpretation of the (yet to be determined) common language.

| |
\$\endgroup\$
  • \$\begingroup\$ I like it a lot. One possible variation would be to make the "secret handshakes" a feature. To do this, you could allow multiple instances of the same bot. Then part of the challenge is to recognise your own kin and mutually support them; and a viable strategy is to try and work out other players' secret handshakes and imitate them. If you're ok with emphasising this aspect of it, then you can make the shared language pretty unrestricted, e.g. bots can just send arbitrary strings to each other. (I realise this is not what you have in mind, I just thought I'd mention the idea.) \$\endgroup\$ – Nathaniel Oct 31 '14 at 15:13
  • \$\begingroup\$ @Nathaniel, what you propose is a battle of obfuscation/cryptography. What I would like to see is a battle of diplomacy. \$\endgroup\$ – M.Herzkamp Nov 2 '14 at 14:27
  • \$\begingroup\$ Fair enough - I just thought I'd say it in case it sparked any interesting thoughts for you, but I knew it was probably too different from what you want to see. If I have any other ideas about your challenge I'll let you know. Designing the language really seems to be the hard part. \$\endgroup\$ – Nathaniel Nov 3 '14 at 0:06
  • \$\begingroup\$ A diplomatic KOTH is something I've been wanting to see for a while. Working out the specifics of the "diplomatic language" is going to be the most difficult part. My proposal is that each message can either 1) state an intention to another bot, or 2) request an action from another bot. Each message would be formatted in a way similar to how a final command would be. \$\endgroup\$ – PhiNotPi Nov 9 '14 at 14:45
  • \$\begingroup\$ @PhiNotPhi: Thanks for the Feedback! I also imagined something similar with the ability to link atomic statements in a boolean fashion. \$\endgroup\$ – M.Herzkamp Nov 11 '14 at 9:23
3
\$\begingroup\$

Happy Holidays!

Introduction

With the holidays upon us, I decided to make an appropriately themed challenge. You are provided with a list of holidays and their respective date ranges, and given a date, you have to output a holiday greeting or the time remaining until the next holiday as appropriate.

Challenge

The list of holidays is below. You have to include it in your program (so no using a library or other external resource for this). Feel free to use any convenient format.

Start  | End    | Name
------ | ------ | -------------------
Dec 6  | Dec 7  | Saint Nicholas' Day
Dec 13 | Dec 14 | Saint Lucy's Day
Dec 24 | Dec 27 | Christmas
Jan 1  | Jan 2  | New Year
Jan 6  | Jan 7  | Epiphany
Feb 14 | Feb 15 | Valentine's Day

You are given a date as input (STDIN, function argument, or anything convenient) in YYYY-mm-dd HH:MM:SS format (e.g.: 2014-12-30 11:15:00).

You may assume that the time zone is either UTC or the system's time zone. The holiday lasts from 00:00:00 on the start date (inclusive) to 00:00:00 on the end date (exclusive).

If the date falls within the range of the holiday, you must output Happy <holiday>!, except if it's Christmas, in which case you must output Merry Christmas!.

If it doesn't, but another holiday is coming at most a week in the future, you must output:

<time> left until <holiday>.

where <time> is in the following format:

<days>d <hours>h <minutes>m <seconds>s

You can't use a library for converting the time to that format.

If there are no whole days, hours, minutes or seconds remaining, omit the number entirely. For example, 1d 0h 3m 4s should be printed as 1d 3m 4s.

If there are no upcoming holidays, you must output (no pun intended):

There are no upcoming holidays.

A trailing newline is optional, but be consistent in your program—don't add a trailing newline in one case and omit it in another.

Standard loopholes are obviously forbidden.

Test cases

Date                | Output
------------------- | ----------------------------------
2014-12-05 23:59:59 | 1s left until Saint Nicholas' Day.
2014-12-06 00:00:00 | Happy Saint Nicholas' Day!
2014-12-06 12:00:00 | Happy Saint Nicholas' Day!
2014-12-06 23:59:59 | Happy Saint Nicholas' Day!
2014-12-07 00:00:00 | 6d left until Saint Lucy's Day.
2014-12-14 00:00:00 | There are no upcoming holidays.
2014-12-24 00:00:00 | Merry Christmas!

Note that your program must work for any year, not just 2014.

Winner

This is code golf, so the submission with the fewest number of bytes wins. An answer will be accepted after a week, but I'll be happy to change the accepted answer if a new valid submission beats the previous high score.


| |
\$\endgroup\$
  • \$\begingroup\$ How do you expect people to test the test cases? It would probably be better to take input than to use the current time, because then it actually makes sense to talk about test cases. You should check date for duplicates, and if there are none you should add that tag. \$\endgroup\$ – Peter Taylor Dec 29 '14 at 14:51
  • \$\begingroup\$ @PeterTaylor You're right, I'll do that. \$\endgroup\$ – nyuszika7h Dec 29 '14 at 15:37
  • \$\begingroup\$ @PeterTaylor I couldn't find any exact duplicates, only two holiday-themed questions, both of which ask for much less than my challenge. \$\endgroup\$ – nyuszika7h Dec 30 '14 at 11:28
1
6 7
8
9 10
100

You must log in to answer this question.

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