579
\$\begingroup\$

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

Sandbox FAQ

Posting

To post to the sandbox, scroll to the bottom of this page and click "Answer This Question". Click "OK" when it asks if you really want to add another answer.

Write your challenge just as you would when actually posting it, though you can optionally add a title at the top. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it.

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

Discussion

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

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

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

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

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

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

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

\$\endgroup\$
4
  • 1
    \$\begingroup\$ What if I posted on the sandbox a long time ago and get no response? \$\endgroup\$ Commented May 15, 2024 at 14:05
  • 2
    \$\begingroup\$ @None1 If you don't get feedback for a while you can ask in the nineteenth byte \$\endgroup\$ Commented May 29, 2024 at 13:27
  • \$\begingroup\$ 500 c kanji link \$\endgroup\$ Commented Nov 23 at 17:52
  • \$\begingroup\$ Why some submissions which is a duplicate or some problems with don't downvoted but sometimes I had submissions which heavily downvoted and nobody posted reason? \$\endgroup\$ Commented Nov 23 at 20:19

4981 Answers 4981

1
9 10
11
12 13
167
4
\$\begingroup\$

Flit - a simple board game for bots


I've made a human playable version of this game with a simple strategy to give an idea of how the game plays out. You can play it before or after reading the rules here - picking up the rules intuitively adds an extra challenge...

If playing this gives any idea about whether the KotH version would be better with 2, 4, or more players per game, or any other subtle adjustments that would help, please let me know.


Note: adjacency is vertical or horizontal - for this game there are no diagonal neighbours.

Overview

The board is a square grid. Each bot starts with 2 pieces of their colour, and gains more pieces by converting neutral pieces that appear from time to time. The objective is to end up with more pieces than your opponents.

Each turn, one bot moves. It chooses one of its pieces and moves it to be next to another of its pieces. There is no limit to the distance a piece can move in a single step, provided it lands next to a piece of the same colour.

Neutral pieces

There are initially zero neutral pieces.

A new neutral piece can appear at any time, regardless of whether there are already neutral pieces unconverted. A neutral piece will only appear on an empty square that has 4 empty neighbours, to prevent it being instantly converted.

If a neutral piece is adjacent to another piece, it is converted - it becomes the colour of that piece. A neutral piece can only ever be adjacent to a single other piece - it will be instantly converted before any other bot has a chance to move next to it.

Moving

A move is specified by an origin square and a destination square. It is a valid move if the origin square contains a piece of the bot's colour, and the destination square is empty and is adjacent to at least one piece of the bot's colour. Note that the piece being moved cannot also be the piece adjacent to the destination square (a piece cannot simply move next to its own previous position). Two distinct pieces are required - one to be moved, and one to be adjacent to the destination.

[Not moving is a valid move, and is indicated by specifying the same coordinates for origin square and destination square. not sure about this rule] Not supplying a move within the time limit also results in not moving, but repeatedly exceeding the time limit will lead to the bot losing the opportunity to make further moves.

Communication

The board information will not be supplied each turn. Instead the bot must keep track of the board state itself. Each time a change is made a message will be sent to all bots describing the change. If a bot chooses not to move, the non-move will not be broadcast.

The board starts empty. The initial two pieces for each bot will be broadcast to all bots, then the first bot will be sent a request for a move, to which it must respond within the time limit. Any response sent after the time limit expires will be discarded (any waiting input will be read and discarded before the next request for a move is sent to that bot).

Bots will therefore have complete information about the board state at all times.

Specification

Available: An available square is an empty square that has 4 empty neighbours

Players

There are 4 bots competing in each game. Bots are numbered 1 to 4 and take turns in that fixed order.

Board

The board is a 32 by 32 square grid. It wraps toroidally - every square has 4 neighbours. The board has no boundaries - no edges or corners to give an advantage.

Initial state

For each bot, one piece will be placed on a square chosen uniformly from the available squares. After all first pieces have been placed, a second piece will be placed for each bot in the same way. The initial state contains no neutral pieces.

Addition of neutral pieces

Each turn one bot will move. After that move has been made, the addition of a new neutral piece will be considered. A square will be selected at random. If that square is available then a neutral piece will be placed on it with probability 1/16. If the square is unavailable then play continues - a second square will not be selected. [This differs from the human playable version linked above: there a list is kept of all available squares and a neutral piece is placed on one of those with probability 1/6 each turn - I now prefer this approach so the rate of new neutral pieces does not slow in the end game]

Bot STDIN

All received messages will be terminated by a newline. Each bot will receive messages of two types: an update or a move request

Update:

x y c

where (x, y) is the square to be updated, and c is the new colour (which may be 0 for empty, 1, 2, 3 or 4 for a bot colour, or 5 for neutral).

Move request:

M

where M is the literal string "M" and indicates that a move is required.

Bot STDOUT

The response must be terminated by a newline. A bot responds with a move in the following format:

x0 y0 x1 y1

where (x0, y0) is the origin square, and (x1, y1) is the destination square.

If origin and destination are identical, no move will be made. This is valid and does not lead to the bot being penalised. The bot will only be penalised if it fails to respond within the time limit.

Time limit

The time limit is 50ms. If a bot exceeds the time limit on 5 consecutive turns then it will no longer be prompted for moves. That bot will be frozen for the rest of the game.

Winning criterion

The winner is the bot with the most pieces when the game ends. There is no reward for second place. If two bots tie for first place, neither is rewarded.

The game ends when one of the following conditions is met:

  • the total number of turns taken exceeds 32,768 (8,192 per bot)
  • all 4 bots choose not to move consecutively
  • one bot has too many pieces to catch up with

Too many pieces to catch up with is defined as follows:

  • A, B and C are the numbers of pieces of the other 3 bots.
  • D is the number of pieces of the bot in question.
  • N is the number of neutral pieces.
  • E is the number of empty squares.
  • P is the number of potential neutral pieces. P = N + E - 4
  • M is the maximum number of pieces attainable by A, B or C.
  • M = Max(A+P, B+P, C+P)
  • If D > M then the bot has too many pieces to catch up with.

I've tried to make this game as simple as possible, while still having non-trivial dynamics.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Time limit could be abused - the bot is allowed to just take its sweet time for 4 turns straight, followed by a reset... How about average time? \$\endgroup\$ Commented Feb 18, 2018 at 12:40
  • \$\begingroup\$ Ah good point. I'll probably go with average time per move after an arbitrary 10 seconds to allow for high variance early on. \$\endgroup\$ Commented Feb 18, 2018 at 12:57
  • 1
    \$\begingroup\$ First player is at a very slight, systemic disadvantage. He's the only one that cannot see a neutral piece on his first turn. Piece spawning should probably happen before each player makes a move, instead of after. \$\endgroup\$ Commented Feb 20, 2018 at 14:58
  • \$\begingroup\$ Oh good point. That small difference is definitely relevant. Neutral pieces before rather than after a move sounds good. \$\endgroup\$ Commented Feb 20, 2018 at 17:18
4
\$\begingroup\$

Musical Washing Machine

I have a washing machine with a knob and several buttons. The knob selects the type of laundry and the buttons cycle through water temperature, etc. options. When pressed, these each create a musical note. There are five musical notes that can be made, in this ascending order: F A C D E

knob (K) When 360ed: play D and reset all other buttons wash temp (T) 1st press (cool -> warm): A 2nd press (warm -> hot): F 3rd press (hot -> cold): E 4th press (cold -> cool): C (repeat) spin speed (S) 1st press (medium -> max extract): F 2nd press (max extract -> no spin): E 3rd press (no spin -> medium): A (repeat) soil level (L) 1st press (medium -> heavy): A 2nd press (heavy -> extra heavy): F 3rd press (extra heavy -> light): E 4th press (light -> medium): C (repeat) 

The Challenge

Given a series of notes, determine if if can be played on my washing machine, and, if so, output the series of moves to generate it.

I/O coming soon to a washing machine near you

\$\endgroup\$
2
  • \$\begingroup\$ As a side note, there is a washing machine that plays the New Zealand Athem \$\endgroup\$ Commented Aug 27, 2015 at 21:02
  • \$\begingroup\$ I think I understand, but it looks a bit confusing. Maybe you should give an example with an explanation. \$\endgroup\$ Commented Feb 9, 2018 at 17:18
4
\$\begingroup\$

Make a Sierpinski triangle

Your challenge is to output a n-th order right-angle Sierpinski triangle, similar to this (third-order):

# # # # # # # # # # # # # # # # # # # # # # # # # # # 

Input:

A number, n, and a character (in this example '#');

Output:

A 2**n (two to the n) line Sierpinski triangle, made of the given character. You could consider it a two-state cellular automaton: the cells are separated by a single spaaace; if it is on, it contains the given character; Otherwise is contains a spaaace.

Examples:

in:

0 * 

out:

* 

explanation:

2**0=1

in:

1 * 

out:

* * * 

in:

2 * 

out:

* * * * * * * * * 

Winner:

this is codegolf so the winner is the answer with the least bytes. (NOTE: might add something tho do with triangles of the same character.)

Hint:

it might be helpful to know that the n-th line contains the previous line xor that line shifted right by one cell (x^(x>>1)).

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to PPCG and thanks for using the sandbox! There is a challenge to draw an Sierpinski Triangle which is broad enough to allow your format, so the challenge might be considered a duplicate. Then again I think the old challenge is no longer up to the current site standards and should probably be closed ... \$\endgroup\$ Commented Mar 10, 2018 at 10:08
  • 1
    \$\begingroup\$ This is also close enough to Generate Pascal's triangle that by the standards of this site (can answers be copied with trivial modifications?) I would consider it a duplicate. \$\endgroup\$ Commented Mar 10, 2018 at 19:42
4
\$\begingroup\$

-(-(--x)--))> Code Kebabs! <-(-(--x)--))


Your goal is to parse Code Kebabs, they look like this:

-x--> 8 2 <-(-(--x)--)) -x-x-x--> -10 --x> 255 

A Code Kebab is made up of 3 parts, the stick, the tip (< and >), and the stand (the number compared by)

stick tip stand --x-- > -5 

The stick


The stick contains 4 operators, and the variable (x) The operators are listed here, in order of precedence:

  1. ( ... ) | Brackets. They are the "veggies" on a code kebab. Everything inside them runs before the rest of the kebab, with the last, deepest pair going first. Brackets can be nested.

  2. v-- | Suffix decrementation. This is one of the 4 parts of the stick, and decrements the value supplied to it by one.

  3. v-v | Subtraction. This is the 2nd part of the stick, and subtracts the two values.

  4. --x | Prefix decrementation. This is the 3rd part of the stick, and decrements the value supplied to it by one.

  5. -v | Negation. This is the 4th and final part of the stick, and inverts the value supplied.

Each operator returns it's result, and can be used as input for other operators.

The Tip


The tip is one of two symbols: < or > When the tip is <, the stand must be left of it, with the tip being left of the stick. When it is >, the stand is to it's right, with the tip being on the right of the stick.

The Stand


The stand is any integer. That's all there really is to say about it.

Execution of the kebab


You can't execute a kebab without eating it!

Kebabs are executed in a loop until their condition (The result of the stick being less than the stand's value) is fulfilled. When execution is finished, the variable (x) is set to the result of the stick, X is printed, and execution resumes again unless the condition is fulfilled.

When execution starts for the first time, X is set to 10 beforehand.

TODO


  • Add test cases.

  • Clear a few things up.

  • Make the description of execution a bit clearer?

\$\endgroup\$
8
  • 1
    \$\begingroup\$ You should describe the difference between pre and post decrement. \$\endgroup\$ Commented Apr 30, 2018 at 21:22
  • \$\begingroup\$ Also, how are the input variables initialized? \$\endgroup\$ Commented Apr 30, 2018 at 21:22
  • \$\begingroup\$ A test case that has something like -x--5 to force parsing it as a subtraction and unary negation, rather than post-decrement x, would be very good. \$\endgroup\$ Commented May 1, 2018 at 13:02
  • \$\begingroup\$ @AdmBorkBork Numbers aren't mentioned as a requirement for parsing, so -x--x would probably work better. But yea, good idea. \$\endgroup\$ Commented May 1, 2018 at 13:48
  • \$\begingroup\$ @Pavel The input variable X is set to 10 beforehand, as mentioned in The execution of the kebab \$\endgroup\$ Commented May 1, 2018 at 13:51
  • \$\begingroup\$ Is this correct? And if not, where is my flaw? The input is the Code Kebab (i.e. -x--> 8) with x=10 by default, and the output is the x once it fulfills the Kebab check. So for -x--> 8 with x=10 as start, it will do x-- first (so it becomes x=9), and then the -x negation (so it becomes x=-9), and then checks it with the tip (-9 > 8). This is false, so it continues with x now being -9? So then x-- again (x=-10), then -x again (x=10), and then the check again (10 > 8). Which is true, so it outputs 10 as result? I have the feeling I misunderstand it a bit.. \$\endgroup\$ Commented May 2, 2018 at 11:08
  • \$\begingroup\$ Also, why is suffix decrementation before prefix? In most languages (Java, JS, C, etc.) it's usually the other way around. \$\endgroup\$ Commented May 2, 2018 at 11:10
  • \$\begingroup\$ And one more question, is something like ---x (negation & prefix decrementation), or x---x (suffix decrementation & subtraction) a possible valid input? Or would these always be surrounded by parenthesis (---x would be -(--x) instead; x---x would be (x--)-x or x-(--x) instead). \$\endgroup\$ Commented May 2, 2018 at 11:14
4
\$\begingroup\$

Nearest neighbors in a square lattice

Premise

Consider an infinite 2D square lattice. We can choose one point as the origin and label each point with a pair of integers that corresponds to points on the Euclidean plane:

enter image description here

Now consider the point at the origin, \$(0,0)\$. The set of lattice points closes to the origin (but not including the origin) is \$\{(1,0),(0,1),(-1,0),(0,-1)\}\$. We will call this set the \$1\$st nearest neighbors. The set of lattice points closest to the origin but not including the \$1\$st nearest neighbors is \$\{(1,1),(-1,1),(-1,-1),(1,-1)\}\$. We call this set the \$2\$nd nearest neighbors

Now we can define the \$k\$-th nearest neighbors as the set of points closest to the origin and not included in the union of the set of \$n\$-th nearest neighbors for \$n\in\{1,2,...k-1\}\$.

Define the sequence \$NN(k)\$ as the length of the set of \$k\$-th nearest neighbors.

Task

Given \$k\$, compute \$NN(k)\$. This is A105352 on OEIS without the first element.

Rules

  • You may use 0- or 1- based indexing.
  • Given \$k\$, you may either output the first \$k\$ elements of the sequence or the \$k\$-th element.
  • You may alternatively take no input and output the sequence indefinitely.
  • Standard loopholes disallowed.

Here are some 1-indexed test cases:

n NN(k) 1 4 8 8 9 4 10 8 38 16 52 8 80 8 121 24 145 12 
\$\endgroup\$
8
  • \$\begingroup\$ OEIS A105352. \$\endgroup\$ Commented Sep 13, 2018 at 20:47
  • \$\begingroup\$ @Mr.Xcoder Thanks \$\endgroup\$ Commented Sep 13, 2018 at 20:58
  • \$\begingroup\$ Could you allow the infinite sequence \$\{NN(1),NN(2),NN(3),\ldots\}\$ as output (with no input)? \$\endgroup\$ Commented Sep 15, 2018 at 8:34
  • \$\begingroup\$ @Delfad0r Sure. \$\endgroup\$ Commented Sep 15, 2018 at 16:33
  • 1
    \$\begingroup\$ Very related. Just filter out zeroes. \$\endgroup\$ Commented Sep 15, 2018 at 16:38
  • \$\begingroup\$ @user202729 Do you think it's a dupe? \$\endgroup\$ Commented Sep 15, 2018 at 17:06
  • \$\begingroup\$ @dylnan I don't know... \$\endgroup\$ Commented Sep 17, 2018 at 13:08
  • \$\begingroup\$ IMO it's a dupe: adding a loop and an if test is a pretty trivial modification. \$\endgroup\$ Commented Sep 17, 2018 at 14:34
4
\$\begingroup\$

Breaking into 3 Palindromes:

As discussed here and here, every positive integer can be written as the sum of 3 palindrome integers. Given a number "n", output these integers.

Challenge

  • This is a code golf challenge. The shortest functional solution wins.
  • The input number "n" will be any integer greater than 0 but less than 1,000,000,000.
  • The three output numbers must be palindromes. Their sum must be "n".
  • A palindrome number is a number which is the same forwards as backwards. It can have any number of digits.
  • To make this easier, I will allow positive or negative palindrome integers.
  • Output and input can be formatted in any what that is convenient as long as it can be readily understood.

Examples

input: 5 output: 0,0,5 input: 1234 output: 1001,222,11 input: 3141592 output: 2200022,926629,14941 
\$\endgroup\$
17
  • 2
    \$\begingroup\$ This is actually a very interesting problem. The paper which proved that this would work for any base lists 40 different algorithms that are used to find these values depending on the value of "n". I suppose there should be a requirement to solve this in a reasonable about of time to avoid brute force but I don't know how I should phrase that. \$\endgroup\$ Commented Sep 17, 2018 at 21:18
  • \$\begingroup\$ It's up to you, but time limit requires a particular computer to test the solutions on. \$\endgroup\$ Commented Sep 18, 2018 at 1:18
  • \$\begingroup\$ Maybe it would be a good idea to link that paper in the challenge. Also, I tried to bruteforce in 05AB1E, and the 1234 case already times out after 60 sec, so I won't even have to try 3141592.. It barely doesn't make it within the 60 sec, but does output most of the possible outputs. Maybe make this a [fastest-code] challenge instead of code-golf, so the goal is to solve it as fast as possible. Alternatively [fastest-algorithm] could be used as well, but usually when someone find one, others will copy it. \$\endgroup\$ Commented Sep 18, 2018 at 6:41
  • 1
    \$\begingroup\$ Honestly, i don't think i am comfortable managing a fastest-algorithm challenge due to my own limited skill. I'm a pretty amateur programmer so if someone uses languages, libraries, etc. I'm unfamiliar with I won't be able to fairly judge them. This idea though (complicated but sounds simple) seems great for one of these challenges. \$\endgroup\$ Commented Sep 18, 2018 at 13:04
  • 1
    \$\begingroup\$ Would it be feasible to require the code to run within 20 minutes on Ideone? Is that linked to my computer's abilities? \$\endgroup\$ Commented Sep 20, 2018 at 13:39
  • \$\begingroup\$ I think if you keep this at base 10 (decimal only) it's not so bad. \$\endgroup\$ Commented Sep 21, 2018 at 12:59
  • \$\begingroup\$ @ouflak I had no intention of leaving base 10. I'm really liking the Ideone idea but am not sure if people would be ok with that. \$\endgroup\$ Commented Sep 21, 2018 at 18:51
  • 1
    \$\begingroup\$ rnta.eu/cgi-bin/three_palindromes/pal3.py and somethingorotherwhatever.com/sum-of-3-palindromes The speeds for these are bad at all. One in python the other in Javascript. I'm doing a C++ version (completely ungolfed) as I'm at a bit of a lull at the moment. It's just a translation of the Javascript code with some tweaks. I'll post a link to that as well. I would forget the timings and go with the straight up challenge. \$\endgroup\$ Commented Sep 26, 2018 at 9:22
  • 1
    \$\begingroup\$ I've done this up in non-golfed C++. Anybody know a site where I can put this online where people can run it? It's big, but fast. \$\endgroup\$ Commented Oct 3, 2018 at 15:24
  • 1
    \$\begingroup\$ The non-golfed C++ is 36 kbytes. Maybe limiting this to just the 4 digit case might be OK. I might try that in LUA and see what it looks like. This is such a great idea. Unfortunate that the algorithms are so lengthy. \$\endgroup\$ Commented Oct 8, 2018 at 13:56
  • \$\begingroup\$ @ouflak, the fact that the algorithms are lengthy is why I thought this would make a good challenge. It is ripe for optimization. I'm worried about posting this challenge though as I'm sure there are many algorithms that will give an answer eventually but are so slow they defeat the purpose of the challenge. \$\endgroup\$ Commented Oct 8, 2018 at 14:29
  • \$\begingroup\$ Ok, I've sorted out a much shorter algorithm in LUA for the three digit case, un-golfed. repl.it/repls/AchingEnchantedHack. This has given me an idea for how to sort out the general case, which I think now actually might not be so bad. \$\endgroup\$ Commented Oct 9, 2018 at 7:43
  • \$\begingroup\$ Here is a solution that should work for any sized number. This is brutally un-golfed LUA. I haven't even taken the opportunity to use a recursive function where it obviously would apply. For 5 digit numbers and smaller, it's pretty quick, easily less than a second. For 6 digit numbers and above, it depends on how soon it finds the first set of palindromes. I had one number (390081) take a good five minutes on the test site. I'm sure it would be quicker on my machine. I'd like to think there are places for optimization for speed (as well as golfing). repl.it/repls/BlondWaryShareware \$\endgroup\$ Commented Oct 9, 2018 at 11:59
  • \$\begingroup\$ Just one other comment on your constraints, I wouldn't allow negative palindromes as I'm not convinced this makes it 'easier'. Should I start golfing this thing? ;) \$\endgroup\$ Commented Oct 9, 2018 at 12:10
  • \$\begingroup\$ @ouflak you can probably wait until i post it as a real question but your enthusiasm definitely implies I need to. \$\endgroup\$ Commented Oct 9, 2018 at 12:50
4
\$\begingroup\$

Classical construction golf: Wernick's list No. 47

Background

Compass-and-straightedge construction, a.k.a. classical construction, is the construction of lengths, angles, and other geometric figures using only an idealized ruler and compass. A ruler can only be used to draw a straight line passing through two given points; a compass can only be used to draw a circle with two given points (a center, and a point on the circle).

All compass and straightedge constructions consist of repeated application of five basic constructions using the points, lines and circles that have already been constructed. These are:

  • Creating the line through two existing points
  • Creating the circle through one point, with another point as the center
  • Creating the point which is the intersection of two existing, non-parallel lines
  • Creating the one or two points in the intersection of a line and a circle (if they intersect)
  • Creating the one or two points in the intersection of two circles (if they intersect).

Five basic constructions

In addition to these listed on Wikipedia, we have the sixth basic construction:

  • Creating an arbitrary point on the plane, possibly with a constraint:
    • On a line ("line" includes straight lines and circles)
    • Not on a line
    • On a closed or open part of a line, bounded by existing points on it
    • Inside a closed or open region, bounded by existing lines

In any geometric problem, we have an initial set of symbols (points and lines), an algorithm, and some results. From this perspective, geometry is equivalent to an axiomatic algebra, replacing its elements by symbols.

This is the basis of the new kind of : classical construction golf.

Challenge

Wernick's list is a collection of construction problems. The common objective is to recover the three vertices of a triangle, given three of its 16 characteristic points. They include:

  • \$A, B, C, O\$: three vertices and circumcenter,
  • \$M_a, M_b, M_c, G\$: the side midpoints and centroid,
  • \$H_a, H_b, H_c, H\$: three feet of altitudes and orthocenter,
  • \$T_a, T_b, T_c, I\$: three feet of internal angle bisectors and incenter.

Out of the 139 problems, some are solvable by construction, but some are not. The problem we'll tackle here is problem 47, where the given points are:

  • \$A\$: a vertex.
  • \$H_a\$: the foot of the altitude on side \$a\$; that is, the opposite side of the vertex \$A\$.
  • \$T_b\$: the foot of the bisector of angle \$B\$.

Given these three points, recover the other vertices \$B\$ and \$C\$.

enter image description here

Scoring & Winning criterion

Every usage of the six basic constructions (shown above) counts. For the line intersections, creating each point adds 1 score, e.g. if you need both intersections of two circles, you get 2 score from the step.

The solution with the lowest score wins.

Scoring example

Task: Construct the midpoint of two points \$A\$ and \$B\$.

Solution:

  • Draw circle \$C_1\$ with center \$A\$ going through \$B\$. (+1)
  • Draw circle \$C_2\$ with center \$B\$ going through \$A\$. (+1)
  • Draw two intersections \$X, Y\$ of two circles \$C_1\$ and \$C_2\$. (+2)
  • Draw line \$f\$ going through the two intersections. (+1)
  • Draw line \$g\$ going through the two given points. (+1)
  • Draw the intersection \$M\$ of \$f\$ and \$g\$. (+1)

The score of this construction is 7.

Example task

Tools

GeoGebra is a free online geometry tool. In addition to basic and advanced constructions, it has construction protocol feature which clearly shows the steps used to create the final image. For the above example task, the construction protocol looks like this:

Example construction protocol

Out of 9 steps in total, the points \$A\$ and \$B\$ are given, so we can confirm that seven steps are taken for this particular construction.

It also supports scripting (in GGBScript and JS) for those who want to view this challenge as or . Among many geometry commands, the Prove and ProveDetails commands may help you identify if a particular construction is indeed correct.

Notes

I'm using a relatively easy problem here, in order to see how this new challenge type is received. If it goes well, I'll propose some harder and open-ended problems later.


Meta

  • Is this actually on-topic on PPCG? I'm asking this since this is the first challenge of its kind. I'll assume on-topic unless someone says otherwise on this meta question.
  • Maybe we need to tweak the difficulty of the challenge at hand. Is it too easy or too hard? Any other suggestions? I picked Wernick's list because it's not something you may see on Euclidea or similar, and the optimal (or elegant) solutions for many of the problems are not yet known. I'll go for the task this time, and try to ramp up in subsequent challenges.
\$\endgroup\$
4
  • 2
    \$\begingroup\$ I think it would be a stretch to consider this on-topic: proofs in logic can be argued to be as good as programs by reference to the Curry-Howard correspondence, but I don't really see extending that to proofs in general. It might be more interesting to instead ask for a program which generates proofs and score by the length of the generated proofs (although since the linked paper talks about a 6000-line program to search for them, that may be outside the scope of a reasonable PPCG challenge). \$\endgroup\$ Commented Jul 23, 2018 at 11:35
  • \$\begingroup\$ On the difficulty of the given theorem: without much effort (5 minutes maximum) I have a solution scoring 16. It's certainly much easier than the existing proof-golf questions to get an answer, although I can believe that there may still be room to golf my solution. \$\endgroup\$ Commented Jul 23, 2018 at 11:38
  • \$\begingroup\$ (In fact I've spotted one unnecessary intersection, so 15). \$\endgroup\$ Commented Jul 23, 2018 at 11:49
  • \$\begingroup\$ Do you think this would be better here or on Puzzling? \$\endgroup\$ Commented Sep 30, 2018 at 12:02
4
\$\begingroup\$

The max() is not enough

The max() is not enough

\$\endgroup\$
25
  • \$\begingroup\$ This could do with a better title, any suggestions? \$\endgroup\$ Commented Oct 2, 2018 at 22:14
  • \$\begingroup\$ "Max is only half the story" \$\endgroup\$ Commented Oct 3, 2018 at 2:06
  • \$\begingroup\$ What if the largest integer in the list is not unique, do we output the second largest? I.e., with the list [1,8,4,8] do we output nothing because the 8 is duplicated, or do we output 4 instead being the largest unique integer? EDIT: Scratch the italic part before. Also, I assume we can take the input in any reasonable format? As an integer list, integer-array, integer-stream, comma-separated string, newline- or space-delimited STDIN, etc? Or is it mandatory to input it in a comma-separated string format? \$\endgroup\$ Commented Oct 3, 2018 at 8:24
  • \$\begingroup\$ Ignore the first question. Just noticed it's either nothing if all values in the list are unique, or the max otherwise (even if the largest is not unique). In that case: Can the list contain negative integers or zero? And are we allowed to output another falsey value instead of an empty output? \$\endgroup\$ Commented Oct 3, 2018 at 8:25
  • 1
    \$\begingroup\$ Can we have more test cases with all elements equal \$\endgroup\$ Commented Oct 3, 2018 at 10:05
  • \$\begingroup\$ I have a 5-byter ready, it's a great challenge if it isn't a duplicate! \$\endgroup\$ Commented Oct 3, 2018 at 12:40
  • \$\begingroup\$ @Quintec Great suggestion to focus on "max" - definitely inspired the new title! \$\endgroup\$ Commented Oct 4, 2018 at 13:13
  • \$\begingroup\$ @KevinCruijssen / Anyone: I think failing to follow the rules to the letter should be permissible BUT carry some level of bytes as a penalty. I'm not sure what the usual is here - how about 15 bytes each for either using some other input format and for outputting garbage instead of no output? \$\endgroup\$ Commented Oct 4, 2018 at 13:13
  • \$\begingroup\$ @JoKing Of course, although I'm curious to know - is this somehow non-trivial to infer from the existing cases? What's the catch? :P \$\endgroup\$ Commented Oct 4, 2018 at 13:13
  • \$\begingroup\$ @maxb This will like be up "for real" sometime tomorrow UK time. Good luck! \$\endgroup\$ Commented Oct 4, 2018 at 13:13
  • \$\begingroup\$ Nah, but it would help people catch if their solutions are invalid. Also, I would discourage byte bonuses/penalties, and just let solutions take input how they like rather than overriding the site defaults \$\endgroup\$ Commented Oct 4, 2018 at 13:28
  • 1
    \$\begingroup\$ @ElectricWarr The default is usually to have a flexible input and output formats. But if you insist on having a string comma-separated input, then I will use a split by comma instead to make it into a list in my program itself instead of taking the 15 bytes penalty, considering my full program with list input is just 5 bytes, and changing the comma-separated string to a list is +4 bytes (way below 15 ;p). I would advice to don't use penalties or bonusses at all for challenges btw (and use flexible I/O, but the I/O choice is still up to you of course if you insist on comma-separated strings). \$\endgroup\$ Commented Oct 4, 2018 at 13:31
  • \$\begingroup\$ Btw, about "Assume input integers may be more than one digit but no larger than 4 bytes", your last test case has 6-byte numbers? \$\endgroup\$ Commented Oct 4, 2018 at 13:36
  • 1
    \$\begingroup\$ @KevinCruijssen I figure I'll try strict requirements this time around and if it's a problem I'll avoid them in future. On 6-byte numbers - ha! - good point, I'll reword that. Of course I should have foreseen that here of all places "bytes" is a measure of length first and as a quantity of information second! \$\endgroup\$ Commented Oct 4, 2018 at 13:46
  • 3
    \$\begingroup\$ Polyglot, 30 bytes Takes +15 for not taking any input and +15 for not outputting anything \$\endgroup\$ Commented Oct 5, 2018 at 1:54
4
\$\begingroup\$

Formulize the sum: Faulhaber's formula

Sums of the form Σkⁿ over k in 1..x can be turned into a polynomial of x whenever n is a natural number.

Examples

Σ1 = x Σk = (1/2)x²+(1/2)x Σk²= (1/3)x³+(1/2)x²+(1/6)x 

Criteria

You will take n as a non-negative integer input and output the coefficients in reduced fraction form of the resulting polynomial from leading coefficient down to the last non-zero coefficient.

This is code-golf, shortest code wins.

Test cases

0 #=> 1 1 #=> 1/2 1/2 2 #=> 1/3 1/2 1/6 3 #=> 1/4 1/2 1/4 0 4 #=> 1/5 1/2 1/3 0 -1/30 5 #=> 1/6 1/2 5/12 0 -1/12 

(extra spacing here is just for clarity and is not necessary.)

\$\endgroup\$
8
  • \$\begingroup\$ 0 is positive? non-negative is better. \$\endgroup\$ Commented Nov 23, 2017 at 13:40
  • \$\begingroup\$ Fixed @user202729 \$\endgroup\$ Commented Nov 23, 2017 at 13:41
  • \$\begingroup\$ Is outputting floating point coefficient allowed? Is errors from floating point imprecision allowed? \$\endgroup\$ Commented Nov 23, 2017 at 13:43
  • \$\begingroup\$ @user202729 No, because you get some fractions like 5/12 or 1/3 with non-terminating decimal expansions. \$\endgroup\$ Commented Nov 23, 2017 at 13:45
  • \$\begingroup\$ What about the latter question? / Is errors from integer overflow (for large arguments) allowed? \$\endgroup\$ Commented Nov 23, 2017 at 13:47
  • \$\begingroup\$ @user202729 Yes, though you program should be able to handle up to, say, n = 20. \$\endgroup\$ Commented Nov 23, 2017 at 13:48
  • \$\begingroup\$ I think the answer for 3 should be 1/4 1/2 1/4. \$\endgroup\$ Commented Nov 20, 2018 at 17:03
  • \$\begingroup\$ Don't we already have a Bernoulli numbers challenge? \$\endgroup\$ Commented Nov 26, 2018 at 19:45
4
\$\begingroup\$

The Hungry Moose

Inspiration.

Moose face harsh conditions during the winter. According to one source:

Their winter foods are lower quality than what they eat in summer and provides less energy, consequently, they need to eat more of it. During harsh winters, having both extreme cold temperatures and deep snow, moose expend more energy than they take in and many can starve.

Challenge

At noon on day 1, a hungry moose starts at a food source (the top left corner). Each morning, the moose may either walk to any 8-adjacent square or stay in place. Each evening, the moose clears the food and snow from its location (adding its net nutritional value to its calorie store and setting that value in the array to 0), and before the end of the day loses 1 calorie to the extreme cold.

The moose dies when its calorie store falls to 0 or below at the end of a day. In particular, if the value at the upper-left corner is 1, 0, or negative, the moose dies on day 1.

Input

A 2D array of integers. Negative numbers represent calorie-negative deep snow.

Output

The maximum number of days the moose can survive (counting day 1 as a full day).

Test cases (add)

6 0 -2 3 0 0 -5 -5 0 0 -1 3 8 42 -100 1 -100 -100 2 3 4 5 42 5 -3 1 1 -9 9 12 
\$\endgroup\$
2
  • \$\begingroup\$ What happens if all the array values are all negative? Does the moose survive a single day or none at all? \$\endgroup\$ Commented Nov 22, 2018 at 20:21
  • 1
    \$\begingroup\$ A worked example would be useful. You also need to clarify if we can wrap around the array. \$\endgroup\$ Commented Nov 25, 2018 at 14:28
4
\$\begingroup\$

Static Code Analysis Battle!

Your programs will play a friendly game of rock, paper, scissors. There's a catch though; you can not use randomness and the combatants can see each other's source code.

That is, you will write a python program that, when imported, provides a function named rps. Given two combatants, say player1.py and player2.py, the controller will import them, and execute player1.rps(player2sourceCode) and player2.rps(player1sourceCode). These should output R, P, or S. The winner is then whoever would win in rock paper scissors with those moves. If one player makes a valid move, and the other does not, that player wins. If both players make an invalid move, it is considered tie. Additionally, taking more than 1 second to move is considered an invalid move.

Here are the rules:

  1. Both the action of importing your module and your rps function should be pure functions. This means for example that you can not do the following:
    1. Use randomness or other non-deterministic code.
    2. Interfere with or receive information from the file system, I/O, peripherals, etc...
    3. Use time.sleep.
    4. Alter or access the state of the controller.
    5. Use other functions to do impure actions. For example, you can not call eval on the source code of an impure function call. An exception to this is if the only impure thing it does is interact with your program's state (i.e. it is permitted to change variables in your program's namespace). You can, however, call it on pure function call source code.
    6. Anything else that a pure function could not do.
  2. Other functions in your source code, however, may be impure.
  3. You may assume that the source code passed as an argument to rps obeys rule 1. You may not, however, assume that the rps in the passed source code is a pure function when you pass it source code that does not obey rule 1. Additionally, other functions in the module may be impure.
  4. Additionally, going into an infinite loop is perfectly fine, although if it happens when the caller calls your program, your move will be considered invalid. If the opponent calls your program and it causes them to go into an infinite loop, however, their move will be considered invalid, and vice versa.

This is , so the program that defeats the other programs wins! In particular, I will run a match between each program and each other program. The winner will be the condorcet winner if one exists. Otherwise, the result will be a tie between the Schwartz set members.

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

The Forest Game (KotH, WIP)

Summary

You have been given a space of land to plant trees in. Unfortunately, due to an administrative mix-up, so have 4 other people. You are in a competition with them to make the most money out of your trees within the next 100 years.

The map

A 10 by 10 grid, representing the area of land. Each square will be one of the following:

  • A number, 0 to 4, representing a player
  • ., representing a seed (more later)
  • i, representing a sapling
  • T, representing a tree
  • F, an ongoing fire
  • , an empty space

Actions

Actions, given by your program, are 1 or 2 characters long. The first is the type:

  • . - plant a seed, costs 1
  • i - plant a sapling, costs 10
  • F - start a fire, costs 5
  • m - move, costs 0
  • w - work, gains 1 (what you do for easy points/to do nothing)
  • - - harvest, variable gains (see below)

Anything else as the first character will result in ignored command. The second character is one of `^'<>,v., a direction, which refers to the relative location of the square on which to perform the command:

` ^ ' NW N NE < > --> W E , v . SW S SE 

For the work command, the second character need not be present, but must be one of the eight if it is. An invalid command is ignored.

Growing

Seeds become saplings, saplings trees. After 5 rounds (25 turns), a seed becomes a sapling with the probability \$\frac{8 - C}8\$ where \$C\$ is the number of nearby (diagonally or orthogonally adjacent) saplings or trees. Saplings become trees after 7 rounds, with the same probability (\$C\$ here is only trees). This is worked out from the top left, going across each row in turn, meaning that each seed/sapling growth may be affected by saplings/trees created that turn.

Value

When harvested, saplings/trees add to your score. Saplings are valued at 15, trees at 20. After every round, a tree gains 1 point of value, up to a maximum of 40 points. Seeds cannot be harvested, nor can other players' saplings/trees.

Fires

Fires spread from the point you set them to all nearby trees and saplings, unless there is a player other than you also nearby. Example:

 T T T T i5 i5 F5 5 TTTTTT --> FFTTTT --> FTTT --> TTT F1 ii 1 ii 1 ii 1 ii i i i i 

Where 1 is you and 5 is the other player. Each step represents one turn (not one round).

Tournament

Each game, you start with 15 points, and loose/gain them as described in the 'actions' and 'value' sections. The aim is to be the player with the most points at the end of 100 rounds (500 turns in total). Each game will be played 6 times, and then repeated until one player has won more than any of the others. This collection of 6+ games is a 'match'. Every two days, if there have been new players added, the players will be split up into groups of 5, padded out with simple bots of mine if necessary. The winners of each of these will be split into groups of five and the above process repeated until there is only one group of five, the winner of which is the victor!

I/O

Your submission should be a Python 3 program, with a method run defined in the global scope. This method will be called with the following parameters:

  • map_ - a list of ten lists of single character strings. This will be a deep copy of the map, each string is one of 01234.iTF, representing that square.
  • round_ - the round number
  • points - a list of integers, representing the number of points each player has, in order.
  • num - whereabouts on the points list you come, also the number representing you and where you come in the turn order.

It should output the two/one character string mentioned above.

Controller

WIP, extremely buggy

''' Rules --- map, 20 by 20 squares, starts empty with randomly placed players square can be: ' ' - empty '1' - [0-4], player '.' - seed 'i' - sapling 'T' - tree 'F' - flames actions: 'm' - move 'i' - plant sapling '.' - plant seed '-' - harvest tree 'F' - start fire 'w' - work (dir optional and ignored) '?' - other, nothing each action other than move should be accompanied by a direction, [<>^v`,'.O] = (W,E,N,S,NW,SW,NE,SE,O) flames: - go out if person nearby other than starter - turn every nearby tree/sapling to flames, 33% each - go out, leave ' ' costs/bonuses: 'm' - none 'i' - -10 '.' - -1 '-' - +15 for sapling, +20 for tree + turns living max. +40 'F' - -1 'w' - +1 '?' - none growing: . > l - (8-nearby [lT])/8 chance, after 5 turns l > T - (8-nearby [T])/8 chance, after 7 turns T+ - +1 value every turn, max. 40 every five turns, tree drops a seed in an empty nearby square start at 10 points game end after 100 rounds I/O --- ''' import random, os, time, sys class Item(object): def __init__(self, x, y, game, creator=None): self.x = x self.y = y self.game = game self.creator = creator class Flame(Item): def update(self, around): burn = [] for i in around: if str(i) in map(str, range(6)): if str(i) != str(self.creator): return elif str(i) in 'Ti': burn.append(i) for i in burn: self.game.place(Flame, i.x, i.y, self.creator) self.game.place(Empty, self.x, self.y) def __str__(self): return 'F' class Seed(Item): def __init__(self, x, y, game, creator, count=25, _next=None): _next = _next or Sapling super(Seed, self).__init__(x, y, game, creator) self.counter = count self.creator = creator self.next = _next def update(self, around): self.counter -= 1 if self.counter: return pos = sum(str(x) in 'Ti' for x in around) if random.randrange(8) in range(pos): self.game.place(Empty, self.x, self.y) return self.game.place(self.next, self.x, self.y, self.creator) def __str__(self): return '.' class Sapling(Seed): def __init__(self, x, y, game, creator): super(Sapling, self).__init__(x, y, game, creator, 35, Tree) def __str__(self): return 'i' def __int__(self): return 15 class Tree(Item): def __init__(self, x, y, game, creator): super(Tree, self).__init__(x, y, game, creator) self.val = 20 def update(self, around): self.val += 1 if self.val > 40: self.val = 40 def __str__(self): return 'T' def __int__(self): return self.val class Empty(Item): def update(self, around): pass def __str__(self): return ' ' class Player(object): def __init__(self, x, y, name, game): self.game = game self.x = x self.y = y self.name = name self.around = (None,) * 8 self.points = 15 def update(self, around): self.around = around def command(self, text): text = "mv" if len(text) != 2: if len(text) != 1: return else: self.points += text[0] == 'w' return dirs = "`^'<p>,v." #p = placeholder if text[1] not in dirs: return ny = self.y + (dirs.index(text[1]) % 3) - 1 nx = self.x + int(dirs.index(text[1]) / 3) - 1 if (nx, ny) == (self.x, self.y): return itm = self.around["`<,^v'>.".index(text[1])] if text[0] == 'w': self.points += 1 elif ny < 0 or nx < 0 or not itm: #remove for wrapping return if text[0] == 'm': if str(itm) == ' ': self.game.move(self.x, self.y, nx, ny) elif text[0] == 'F' and self.points > 0: if str(itm) in 'Ti': #never!!! self.game.place(Flame, nx, ny, self) self.points -= 1 elif text[0] == '.' and self.points > 0: if str(itm) == ' ': print('.') self.game.place(Seed, nx, ny, self) self.points -= 1 elif text[0] == 'l' and self.points > 9: if str(itm) == ' ': print('l') self.game.place(Sapling, nx, ny, self) self.points -= 1 elif text[0] == '-': if str(itm) in 'Ti': if itm.creator == str(self): #never!! self.game.place(Empty, nx, ny) self.points += int(itm) def __str__(self): return str(self.name) class Game(object): def __init__(self, players, names, size=20): self.map = [] choose = [] self.names = names for x in range(size): self.map.append([]) for y in range(size): self.map[-1].append(Empty(x, y, self)) choose.append((x, y)) self.players = {} random.shuffle(choose) for i in range(len(players)): pos = choose.pop() p = Player(*pos, str(i), self) self.players[players[i]] = p self.map[pos[0]][pos[1]] = p self.round(1) def round(self, number): for i in self.players: self.updatemap() self.turn(i, number) if not 'idlelib.run' in sys.modules: time.sleep(0.04) os.system('cls') print(' |0 1 2 3 4 5 6 7 8 9') print('---------------------') [print(str(self.map.index(i)) + '|' + ' '.join(str(j) for j in i)) for i in self.map] if number != 100: self.round(number+1) else: [print(' '.join(str(j) for j in i)) for i in self.map] for i in self.players: print(names[i], self.players[i].points, sep=': ') def turn(self, player, rn): points = [] n = 0 for i in self.players: if i == player: num = n points.append(self.players[i].points) text = player(map_=[x[:] for x in self.map], num=num, points=points, round_=rn) self.players[player].command(text) def place(self, item_t, x, y, creator=None): try: itm = item_t(x, y, self, creator) self.map[x][y] = itm return itm except IndexError: pass def move(self, ox, oy, x, y): try: self.map[x][y] itm = self.map[ox][oy] self.place(Empty, ox, oy) self.map[x][y] = itm itm.x = x itm.y = y except IndexError: pass def updatemap(self): for x in range(len(self.map)): for y in range(len(self.map[x])): around = [] for rx in (-1, 0, 1): for ry in (-1, 0, 1): if rx or ry: try: around.append(self.map[x+rx][y+ry]) except IndexError: around.append('') if str(self.map[x][y]).strip(): print(' '.join(str(i) for i in around[:3]), ' '.join(str(i) for i in around[3:6]), ' '.join(str(i) for i in around[6:]), str(self.map[x][y]), sep='\n', end='-----') self.map[x][y].update(around) import burnitall, flamingworker, hardworker, plantandwait, seedandreap allnames = ('Burn It All', 'Flaming Worker', 'Hard-worker', 'Plant And Wait', 'Seed And Reap') allplayers = (burnitall, flamingworker, hardworker, plantandwait, seedandreap) players = [] names = {} for i in allplayers: players.append(i.run) names[i.run] = allnames[allplayers.index(i)] Game(players, names, 10) input() 

Game results

Nothing yet!

Sandbox

  • Any thoughts? Do you like it?
  • All numbers, rules are undecided, tell me what you think I should change.
  • I know the controller has many bugs, I posted it here to show that one is being made but it's very much not ready to use.
  • That doesn't mean I don't want bug reports, if you use it and spot one, please tell me.
  • If you don't like Python - tough. It's all I've got on my computer*1, and I don't have space for much else.

*1 I tell a lie, I have got Java, but so much fuss in implementing it for one more language? I'll think about it...

\$\endgroup\$
2
  • \$\begingroup\$ I'd recommend cutting the probability aspect of saplings growing into trees and make it a variable growth rate based on neighbors. \$\endgroup\$ Commented Apr 12, 2019 at 18:30
  • \$\begingroup\$ @Beefster Interesting. I'll think about that. \$\endgroup\$ Commented Apr 12, 2019 at 19:51
4
\$\begingroup\$

Inscriptio Labyrinthica

In the burial place of King Silo of Asturias there is an inscription that reads SILO PRINCEPS FECIT (King Silo made this).

SILO PRINCEPS FECIT

The first letter is found in the very middle, and from there one reads by going in any non-diagonal direction radiating outward. The final letter is found on all four corners. In this challenge, you'll generalize the process to make them.

Input

A string (or equivalent), and an integer. You may make the following assumptions about the input:

  • The string will have an odd length.
  • The integer will be an odd number between 1 and one less than twice the length of the string.

Output

An inscriptio labyrinthica for the string, using the integer for the height (see models). Output should be each letter with no spaces, line break as default to your system/language.

Test cases

Note that an input of 1 or (length * 2 - 1) will result in a horizontal or vertical palindrome.

 Input: FOO, 3 Input: BAR, 1 Input: BAR, 3 Input: BAR, 5 Output: OOO Output: RABAR Output: RAR Output: R OFO ABA A OOO RAR B A R Input: ABCDE, 5 Input: ABCDE, 3 Input: *<>v^, 3 Output: EDCDE Output: EDCBCDE ^v>v^ DCBCD DCBABCD v><>v CBABC EDCBCDE ><*<> DCBCD v><>v EDCDE ^v>v^ 

Scoring

This is so shortest answer in bytes wins. Standard loopholes forbidden.

(I feel like I've seen one similar, but searching around I couldn't find it, and I happened to be reading about this king when I got the idea).

Questions

In my original proposal, I had listed as a bonus to draw reading lines, but feedback was bonuses in code golf are discouraged. I still like that idea and am thinking about integrating it as a a main part of the challenge, but don't know if that would over complicate it or actually make it more interesting. The output for REI, 3 in such a case would be

I←E→I ↑ ↑ ↑ E←R→E ↓ ↓ ↓ I←E→I 

The idea is that it would prevent simple flipping of data after calculating a quarter or half of the but still perhaps allow for some creative ways (I can think of some creative ways to do it shortly in some languages, but maybe it'll be overly complicated for others).

\$\endgroup\$
3
  • \$\begingroup\$ @trichoplax I've updated the challenge based on your feedback, let me know what you think. \$\endgroup\$ Commented Jun 30, 2019 at 17:20
  • \$\begingroup\$ Looks good to me. +1 \$\endgroup\$ Commented Jun 30, 2019 at 18:24
  • \$\begingroup\$ you should now edit this to a link to the post and delete it. Thanks! \$\endgroup\$ Commented Jul 24, 2019 at 19:11
4
\$\begingroup\$

Golf the truth and null values

In many programming languages there is a null and/or other special values. Sometimes they don't follow the normal rules of boolean operations. They may not even agree with the values of the same name in other languages.

Here are some different kinds of the "extended" boolean values, either borrowed from some languages or invented myself:

  • False.
  • True.
  • Absent. All operations between absent and another operand return the other operand.
  • Whatever. All operations between whatever and another operand returns whatever (itself).
  • Partial. If the result can be decided using the other operand, return that. Otherwise return partial (itself).
  • Error. An error as the first operand works like whatever, and an error as the second operand works like partial, except that "itself" means error. It has higher precedence than whatever and partial.

Your task is to define all these values in your language, and the 2 operations and or.

To be clear, the 2 operations should work exactly as in the following tables. The left column represents the first operand, and the top row the second operand.

and F T A W P E or F T A W P E F F F F W F F F F T F W P E T F T T W P E T T T T W T T A F T A W P E A F T A W P E W W W W W W W W W W W W W W P F P P W P E P P T P W P E E E E E E E E E E E E E E E 

Rules

You could use anything distinct and consistent to represent these values. You don't have to use a truthy value to represent true, or a falsy value to represent false. You are allowed and encouraged to use values that contain useful code, i.e. this loophole is not forbidden.

You are allowed to use actual errors or exceptions to represent some of the values. In this case the definition of that value should throw the same error, instead of represent the caught error. But the caught errors or the output messages should be distinct and consistent. Alternatively, you may choose to include STDERR in the output of your code, and use the printed message string as a normal value.

You may choose to pass functions generating and returning the values but doing nothing else to your code as input, in place of the values themselves, without counting the extra code.

You may use different ways of input/output for different values, as long as it is consistent for each kind of value, and it is possible to tell apart the first and the second operand.

You are allowed to use builtin functions and operators without boilerplate, in any argument order, even if you cannot save them in something callable in your language.

There could be some common code shared by all the 8 definitions and appear only once as header/footer. Other than that, the 8 definitions of operations and values must work independently from each other. The only way you can call something defined in the values in the operations is through a valid input method (e.g. you cannot set a variable in a value and read it in an operation).

Your score is the length of common code * 12 + the total length of the 2 operations * 6 + the total length of the values. Smallest score wins. The length of a value is either the length of the code generating it, or the length of itself unquoted if all the values are strings and you choose this way.


Abandoned rules

You are allowed to use operators, or chains of operators and values to represent the 2 operations, even if you cannot save them in something callable in your language. You may require the operands to appear at specific positions, but each operand must appear exactly once and be grouped together. You may choose whether to save operands in variables previously, and don't count the assignment if it doesn't add new information in the assignment (e.g. by changing its type). This makes it possible to use the built-in operators with short-circuit evaluation in languages that don't allow redefining them and preserve this characteristic, and may also make it shorter in some other languages.

Previous scoring: total length of the 2 operations * 50 + the total length of the values.

Possible follow-up

Original title: All the weirdness about the nulls

Extended tables including Valid in a previous version, Reverse aka Opposite by Zgarb, and Possible.

and T F N O W E V R P or T F N O W E V R P T T F T O W E ? F T T T T T T W T T T T F F F F F W F F F F F T F F O W E ? T F N T F N O W E ? ? ? N T F N O W E ? ? ? O O F O O W E ? O O O T O O O W E ? O T W W W W W W W ? W W W W W W W W W ? W W E E E E E E E ? E E E E E E E E E ? E E V T F ? O F F ? ? ? V T T ? T F F ? T ? R F F ? O W ? ? ? ? R T T ? O W ? ? ? ? P T F ? O W ? ? ? ? P T F ? T W ? ? ? ? 

Other potential additions:

  • Default, that is opposite to Opposite.
  • Merge Possible with Valid.

Sandbox questions

  1. Will this be too easy in some languages that already have all of them?

    In languages that has True defined to be -1 and unifies bitwise and logical operations, most integers would works as Partial. GCD/LCM in APL is similar to this. SQL null is Whatever Partial. Most languages that has shortcut evaluation has errors as Error. Not sure about Absent, though.

    (Maybe the easiest way to find out is to post this question. It doesn't make the answer bad. But it's just some consideration in the sandbox for me to decide whether I'll post a stronger version.)

  2. Allowing "operators and chains of operators" seems to open a can of worms. Should I just remove this rule?

\$\endgroup\$
5
  • \$\begingroup\$ How about Opposite that behaves like the negation of the other operand? \$\endgroup\$ Commented Dec 11, 2016 at 19:10
  • \$\begingroup\$ @Zgarb Too similar to Other. For the "2 more to be added", I intended to make it possible to write expressions to 1) decide whether a variable is a specific value, and 2) return a specific value if a variable is true, or false otherwise. This may make the list more useful later. \$\endgroup\$ Commented Dec 11, 2016 at 19:42
  • \$\begingroup\$ @Zgarb I gave up and even removed one, to make hardcoding the tables less likely to be the optimal way. \$\endgroup\$ Commented Dec 13, 2016 at 17:56
  • \$\begingroup\$ if(whatever){/*???*/} \$\endgroup\$ Commented Dec 13, 2016 at 20:23
  • \$\begingroup\$ @Zgarb I forgot this post for some reasons. Now I found your idea quite interesting. But I'll post the first version without it, and may add a stronger version if it worked well or is too easy, and may name it Degenerate to make most of the other results from operations make sense. \$\endgroup\$ Commented Apr 30, 2019 at 8:40
4
\$\begingroup\$

Babel on and on (working title...)

Background

Babel is a cornerstone of modern web development. It takes Javascript using new or proposed ECMAscript features and "transpiles" it into an older language version, so that browsers can run it without updates. In order to do this it inserts its own shim methods, and own custom transforms.

The Challenge

Your objective is to write the Javascript code which produces the largest babel output in characters. Your code must be less than or equal to 128 bytes in length

Babel has an online, interactive compiler which you can access HERE. It's highly recommended that you use this to form your answer. If you work locally, you are restricted to modifying only the settings that the babel website allows you to modify.. There is a guide on installing babel at the end of the question.

Rules

  • For consistency, you may use a Babel version between 7, but not above 8.* (when it eventually comes).
  • You may change the interactive REPL's settings, source type, presets, options, and env-presets. You may change these settings locally if you are using a local installation of babel.
  • You may only provide one input file.
  • You may not exceed 128 bytes in your input file.
  • You may not add your own plugins.
  • You may not use the loophole listed below, or any of the standard loopholes.
  • You may not use error output as a result. babel must transpile the code successfully under one of the allowed configurations.
  • Neither your input or output need to run, or halt. The compilation just needs to output something.

Examples

41 in, 1075 out

{t: [...(function*(){let [a,b]=[1,2]})]} 

32 in, 1101 out

export class b{d=function*(){}} 

125 in, 7336 out

const b = function*(){return function*(){return function*(){return function*(){return function*(){return function*(){}}}}}}; 

Scoring

You must provide both the code and the settings you are using. For users of the online REPL, a link with the settings set in the URL suffices. The answer with the largest output with an input less than or equal to 128 bytes wins. Unlike many challenges of this nature, settings do not cost any bytes of input.

Setting up a local environment (OPTIONAL)

Most of the people doing this challenge will probably use babel's online transpiler to complete it. In the event that the website is taken down in the future or made inadequate for the challenge, it can be completed locally. Make a folder for the challenge, and in a shell in that folder, try something like the following:

Install Babel (globally - you could do it locally)
sudo npm install -g @babel/core @babel/cli
Set your .babelrc with a preset (in this case env)
echo '{"presets": ["@babel/preset-env"]}' > .babelrc
Install babel's dependencies
npm install --save-dev @babel/preset-env @babel/core

Then, given an input file test.js, you can figure out your output score with

babel test.js | wc -c

Happy Hunting!

Questions

This is my first time ever posting one of these. Does everything look on the up-and-up?

Also, should this incorporate "the less characters of input, the better?". I kept trying to think of ways to reward a large output for a small input, but every way I considered changed the tone of the challenge significantly.

Also also, I know that codegolf users don't like being constrained to one language. Is this bound to be an exception or will that stop the question in its tracks?

Proposed Tags: [BUSY BEAVER], [Javascript], [CODE CHALLENGE]

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Hi and thanks for using the sandbox! I'll start right off by saying I don't know enough about babel to particularly talk about if this will be interesting. I think this kind of challenge is fine, just like regex-golf. This should probably be tagged code-challenge and shouldn't be tagged compiler. I am concerned that you tie everything to an external site. While I doubt the site will go down, what happens when they update babel? Will it break the challenge? Since this is a bit abnormal, you may want to ask on meta (specifically about the online scoring) or in chat for more feedback. \$\endgroup\$ Commented Jul 1, 2019 at 21:56
  • 2
    \$\begingroup\$ @FryAmTheEggman thanks for the tags and pointing me to meta for this, I think I'll wind up clarifying things over there. And also, about the foreign site - it's not required, but makes it far, far easier. That's why I edited in the clause about being able to do it locally. If the site is used, the settings are query parameters in the URL (but could be interpreted even if it went down). And contestants can do it locally, provided they post the settings they use, and use the same version. So I'm not too worried about tying it to a site, since it's just for convenience. \$\endgroup\$ Commented Jul 2, 2019 at 12:52
  • 1
    \$\begingroup\$ We discourage language specific challenges when there is no reason for it, but here it is clearly part of the challenge so I see no problem at all. \$\endgroup\$ Commented Jul 16, 2019 at 20:42
  • 1
    \$\begingroup\$ Having a fixed number of input bytes to work with can be awkward in language agnostic challenges as it's difficult to choose a suitable number that doesn't make it too difficult / too easy for some languages. Since everyone is using the same language here a fixed 128 bytes seems reasonable. Your examples already show it doesn't need to be higher. You could consider lower, depending on how you want the challenge to go. With 128 bytes there's a good chance some outputs will be too large to fit in the 65536 character answer length limit, but I don't see that as a problem either. Looks good to me \$\endgroup\$ Commented Jul 16, 2019 at 20:47
4
\$\begingroup\$

Castilian Numerals

A little known (but actually real) number system are the Castilian numerals. They were an odd mix of a digital and positional counting system used in Spain in the late middle ages. There are certain qualities about them, however, that make them not entirely straight forward to generate when you have lots of them in a group, in particular the fact they would be aligned by thousands places. Your challenge will be to print a vertical list of numbers, correctly spaced.

Description of the Numerals

A Castilian numeral is, in effect, a Roman numeral, but only uses 1-999, uses additives for 4 (IIIJ), 9 (VIIIJ), and 900 (DCCCC), and subtractives for 90 (XC) and 400 (CD). Both methods were commonly used for 40 (XL, XXXX). Additionally, final Is were written as Js, such that the sequence 1-6 goes J, IJ, IIJ, IIIJ, V, VJ. (This means standard Roman numeral generators will likely not be much help.) They were generally written lowercase, but for this challenge we'll use all uppercase.

For values under between 1-999, the fact that the letters indicated numerals was made clear by the presence of a symbol that looks like a U. Generally the numerals themselves were right aligned:

1 U J 2 U IJ 999 U DCCCXCVIIIJ 

For values between 1000-999999, everything we would place to the left of the comma would be rendered as if it were its own independent 3-digit number and romanized, and the reminder placed to the right, such that

 1,000 J U 1,001 J U J 21,030 XXJ U XXX 500,444 D U CDXXXXIIIJ 

For values 1,000,000-999,999,999, an additional separator was used, Qto, but for our purposes, we'll just use Q. It would only be used if the number was over 1,000,000, unlike the U that always separated it.

 1,000,000 J Q U 1,000,001 J Q U J 1,001,000 J Q J U 1,001,001 J Q J U J 123,456,789 CXXIIJ Q CDLVJ U DCCLXXXVIIIJ 

As should be noticed, within each grouping of three (arabic) digits, everything is right aligned, with the thousands/million separators all in alignment. Because 0 didn't exist, it would just be left blank.

Input

A sequence of integers in whatever format you feel gives you the best advantage (a list, an array, a series, etc). You may assume that the integers are between 1 and 999,999,999.

Output

A printed list of Castilian numerals, properly aligned on different lines. Note the restrictions on 4/9: mandatory additives are 4,9,900; mandatory subtractives are 90 and 400; 40 is valid either way. The numerals for 1-999 should be right aligned, with a single space on either side of Q or U (there may be padding spaces, but the single longest numeral in each grouping will have the single space). Newlines may be whatever is native to your system/language.

Rules

This is code golf. Fewest bytes wins. Standard loopholes forbidden.

Test cases

Comments/observations are given after # and not part of the output.

Given: 1,2,3 U J U IJ U IIJ # one space between U and I Given: 1,1000,10,100 U J J U # trailing space not required U X U C Given: 123,4,5678,111111111,90,12345,6789012 U CXXIIJ U IV V U DCLXXVIIJ # single space between U and the longest numeral CXJ Q CXJ U CXJ # Q only appears if >= 10^7 U XC XIJ U CCCXXXXV # also valid CCCXLV VJ Q DCCLXXXIX U XIJ  # single space between Q and the longest numeral 
\$\endgroup\$
4
\$\begingroup\$

Polyglot wrappers

Many polyglots are a disastrous mess of unmaintainable code. Let's make this different.

Challenge

Make a polyglot "wrapper" such that code from two or more languages may be embedded in the file without modification.

Example

Consider the following polyglot wrapper for Bash and Python:

'''true' B exit 0 #''' P 

This wrapper can be used such that B can be replaced by an arbitrary bash script, and P can be replaced by an arbitrary python script.

After the scripts have been injected into the wrapper, running the resulting polyglot via either interpreter (bash or python) will result in functionally identical behavior as the original input scripts.

Rules

  1. Your wrapper must support the injection of 2 or more languages
  2. Your wrapper can use arbitrary markers for the string->script replacement
  3. The markers must be at least 1 byte in size (no line number tricks)
  4. Assume the replacement will be done by first replacing all markers with sufficiently long and random data, such that conflicts between the marker literals and contents of the input code cannot exist. However, your markers cannot conflict with the contents of the wrapper itself.
  5. The behavior of the original input programs must not be altered by the wrapper. Ex: an input program that returns 0 must return 0 when run from your wrapper. An input program that crashes must still crash.
  6. The winner is the polyglot wrapper that supports the most languages, with a tie breaker of smallest size (in bytes).
  7. Allowances shall be made for a program that accesses itself on disk. Obviously no polyglot wrapper could correctly return identical output for a script that outputs its own file size.

Question for the sandbox

Is this sufficiently unique and understandable? Are there any loopholes I haven't covered?

\$\endgroup\$
6
  • 1
    \$\begingroup\$ What if, for example the bash script contains '''? Is that what rule 4 is talking about, since I don't really understand that rule. \$\endgroup\$ Commented Sep 2, 2019 at 5:51
  • \$\begingroup\$ I'm indeed wondering the same as @JoKing. What if the content of the code we'd potentially insert into the wrapper contains something that could break the wrapper or other program itself? For example, let's say I submit 0W, where 0 is a wrapper for a 05AB1E program, and W for a Whitespace program. 05AB1E in general ignores all whitespaces between commands and Whitespace ignores all characters except for spaces/tabs/newlines. But what happens if the potential 05AB1E program contains a string with a space/tab/newline in it, which would interfere with the Whitespace program? \$\endgroup\$ Commented Sep 2, 2019 at 9:25
  • \$\begingroup\$ Perhaps make it such that the inner programs are a turing complete subset of the parent language, such that the overall program will always run correctly. Answers would have to make a list of restrictions placed on the language subsets, as well as prove that they are still turing complete, and can't 'break out' of their wrappers, nor have effects on other sections of the program \$\endgroup\$ Commented Sep 2, 2019 at 12:08
  • 1
    \$\begingroup\$ Would this work as a cops and robbers? Cops provide wrappers and robbers provide code that breaks the wrappers? \$\endgroup\$ Commented Sep 3, 2019 at 11:49
  • 1
    \$\begingroup\$ Good catch, everyone! I'll have to think about this some more. Cops and robbers sounds like a good way to make that problem into a feature, @trichoplax \$\endgroup\$ Commented Sep 3, 2019 at 14:16
  • \$\begingroup\$ Your example can break in a different way too. An unterminated here-doc in bash will continue until the end of the script: B = cat << EOF \$\endgroup\$ Commented Sep 8, 2019 at 6:29
4
\$\begingroup\$

Translate a simple sentence from Toki Pona

\$\endgroup\$
1
  • \$\begingroup\$ grammatical construct - this term seems too general. why not call these predicate marker and object marker, or simply "li" and "e" in quotes? \$\endgroup\$ Commented Oct 25, 2019 at 11:44
4
\$\begingroup\$

Is it a Snake Cube?

A snake cube is a quite popular wooden puzzle. There are usually 27 cubes threaded on an elastic string. Each cube has a hole that either goes straight through from one face to the opposite face, or that makes a 90° bend, that means it exits through a face that is adjecent to the one it enters. (And the two end cubes into which this string enters. Two adjecent cubes on that string can rotate against eachother. The goal is rotating them all such that the whole "snake" forms a large 3x3x3 cube.

Images from Wikipedia (1)(2)

Obviously we cannot have any random sequence of the straight/90° pieces if we want to get a cube in the end. This leads us to the

Challenge

Given a sequence of the types of the inner 25 cubes of a "snake", determine whether it is possible to form a cube.

Example

I will here use the symbol T for a piece with a straight hole, and F for a piece with a 90° hole. The example in the image would be encoded (from the bottom left to the top right) as

TFFFTFFTFFFTFTFFFFTFTFTFT 

Details

  • You can take the input as a string or list/array or any other type of sequence.
  • You can use different symbols for the two types, you could also take booleans or integers.
  • The output is also flexible: You're can have two distinct output, one for each case, but they must be consistent. If it is not obvious (e.g. True/False) please specify which one means what.

Examples

No cube possible:

TFTFTFTFTFTFTFTFFTFFFTFFF (we have 8 consecutive (overlapping) straight runs of length 3) TFTFTFTFFFFTFTFFFTFFTFFTT (we have a straight run of four pieces at the end) 

Cube possible:

TFFFTFFTFFFTFTFFFFTFTFTFT TFTFTFTFFFFTFTFFFTFFTFFFT 
\$\endgroup\$
3
  • 2
    \$\begingroup\$ Oh hey, I have that exact cube, but I forgot how to put it back together again \$\endgroup\$ Commented Dec 14, 2019 at 2:44
  • \$\begingroup\$ @JoKing ...then I should maybe modify the challenge and ask for the solution as output :P \$\endgroup\$ Commented Dec 14, 2019 at 9:37
  • \$\begingroup\$ Don't worry, I dug it out of the drawer it was stuck in and finally solved it \$\endgroup\$ Commented Dec 16, 2019 at 7:07
4
\$\begingroup\$

Hexagonify™ a String Block

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

Rennab

Reverse banneR

In the language of your own choosing write a program or function that takes as input the output of the super-handy-for-the-farsighted tool banner. And simply outputs the original text.

Example 1a of banner output on Linux:

> banner 'Code Golf' XXXX XX XXXX XX XX X X X X X X X X X X X X X XXXXX XXXXX XXXXX X XXXXX X XXXX X X X X X X X X X X X X X X X X X XXXXXXX X XXX X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X XXXX XXXXX XXXXXX XXXXX XXXX XXXXX XXXXX XXXX 

Example 1b of rennab program that runs on Linux and takes input from stdin as lines of strings, and outputs to stdout, and supports the characters: [' ', 'C', 'G', 'd', 'e', 'f', 'l', 'o']:

> banner 'Code Golf' | rennab Code Golf 

Example 2a of banner output on Linux:

> banner ':-)' X X X X X X XXXXXXX X X X X X X X 

Example 2b of rennab program that runs on Linux and takes input from stdin as lines of strings, and outputs to stdout, and supports the characters: [':', '-', ')']:

> banner ':-)' | rennab :-) 

Choose what ever characters (minimum of 3) you want to support but that effects your score (see Rules below).

Rules

  • Program or function - your choice.
  • Input the output of banner in whatever format you'd like (eg 2d array of characters, list of strings, reading from stdin straight from the horse's mouth, &c).
  • For this challenge we'll use Cedar Solutions' open-source GNU/GPL banner implementation common on Linux. Prints horizontally only with a fixed size.
  • Output the original text in whatever format you'd like, return character at the end optional (eg as a string, a list of characters, as output to stdout, &c).
  • You can assume only the characters supported are input.
  • You must support a minimum of 3 characters.
  • Score is calculated by this formula (where \$n\$ is the number of code bytes and \$c\$ is the number of characters supported): \$n - 8c\$.
  • Scores can be negative.
  • No standard loopholes.
  • Lowest score wins.

Questions

  • Has this been done before?
  • Is the score formula any good? Any and all suggestions welcome.
  • Is the question any good? Any and all feedback welcome.
\$\endgroup\$
7
  • \$\begingroup\$ Shouldn't banner output be rotated 90 degrees? When I was testing banner, everything was sideways, not horizontal. \$\endgroup\$ Commented Jan 13, 2020 at 20:55
  • \$\begingroup\$ @Jono2906 The output in my post is copy/pasted straight from my Linux terminal. \$\endgroup\$ Commented Jan 13, 2020 at 21:57
  • \$\begingroup\$ Huh, serves me right for using Unix. \$\endgroup\$ Commented Jan 13, 2020 at 21:59
  • 1
    \$\begingroup\$ @Jono2906 Found out there's a few different types of banner implementations out there thanks to your comments. I've picked the one I'm used to and noted that in the post. Thanks :-) \$\endgroup\$ Commented Jan 15, 2020 at 10:59
  • \$\begingroup\$ No problem! I learnt something myself as well (the banner command and also that different OS's implement commands differently). \$\endgroup\$ Commented Jan 15, 2020 at 11:02
  • \$\begingroup\$ This is pretty similar, just a different big-character set. \$\endgroup\$ Commented Jan 17, 2020 at 19:50
  • \$\begingroup\$ This one is also really close, with just slight modifications to the big-character set. \$\endgroup\$ Commented Jan 17, 2020 at 19:52
4
\$\begingroup\$

Reversed Iota's

I didn't invent this challenge, but I find it very interesting to solve.

For every input number, e.g.:

4 

Generate a range from 1 to that number:

[1 2 3 4] 

And then, for every item in that list, generate a list from 1 to that number:

[[1] [1 2] [1 2 3] [1 2 3 4]] 

Then, reverse every item of that list.

[[1] [2 1] [3 2 1] [4 3 2 1]] 

Notes:

  • 1 being a loose item is allowed, since flattening will not matter with this anyway.
  • To preserve the spirit of the challenge, the range has to be 1-indexed.
\$\endgroup\$
4
  • \$\begingroup\$ How should output be formatted? \$\endgroup\$ Commented Jan 26, 2020 at 16:20
  • \$\begingroup\$ This old challenge is pretty similar. The regular challenge isn't really a dupe, but one of the more common ways to get the bonus was to do essentially this. I don't think I would close it because the old one has a bonus, but I can't speak for everyone. \$\endgroup\$ Commented Jan 26, 2020 at 19:01
  • \$\begingroup\$ A naming suggestion: Reveresed Iota's \$\endgroup\$ Commented Jan 27, 2020 at 9:05
  • \$\begingroup\$ May the initial 1 be a loose item instead of a list [1]? I.e. 3 bytes in Jelly. \$\endgroup\$ Commented Jan 28, 2020 at 13:37
4
\$\begingroup\$

Is it a doubling sequence?

Posted here:

Is it a doubling sequence?

\$\endgroup\$
3
  • \$\begingroup\$ Can the input array be empty or of length 1? \$\endgroup\$ Commented Feb 12, 2020 at 1:45
  • \$\begingroup\$ @JoKing In that case, the output must be vacuously True, I guess. \$\endgroup\$ Commented Feb 12, 2020 at 4:47
  • \$\begingroup\$ @JoKing good question, I edited the input to only handle arrays with two or more numbers. \$\endgroup\$ Commented Feb 12, 2020 at 13:16
4
\$\begingroup\$

Posted to main.

\$\endgroup\$
12
  • \$\begingroup\$ The initial set of squares should have a guaranteed distance from each other set of squares. grid needs better specification. What does "nearby square" mean? Other than that, solid spec. \$\endgroup\$ Commented Oct 31, 2018 at 13:12
  • 2
    \$\begingroup\$ 1) The wording is weird on the Game of Life rule explanation. Please take a look at the Wikipedia page and clarify them. Currently, I'm not sure if a cell can change color if it's surrounded by more opponents than allies. Also, it seems to be implied that a live cell surrounded by 3 neighbors dies (which I'm pretty sure wasn't your intention). 2) What happens when no colors remain on the board? 3) Nitpick: the "this" in "it has at this time" threw me off - "that" instead, perhaps? \$\endgroup\$ Commented Oct 31, 2018 at 13:18
  • 2
    \$\begingroup\$ 4a) Since there's no explicit ban on cooperation, it's allowed by default. Was this your intention? 4b) Can bots communicate with each other? 5) Can bots store data across games? 6) Can we get a more easy-to-use system of storing data within one game? Scopes are useful for this: function externalFunc() { /* Storage */ return function gameLoopFunc(args) { /* Code */ }; } 7) next is not very robust. Some people (including myself) will remake the game simulation to gain access to more advanced functionality. 8) What happens if the returned value isn't within 2 cells of one of my own cells? \$\endgroup\$ Commented Oct 31, 2018 at 13:30
  • 1
    \$\begingroup\$ 9a) Why is selecting a live cell that is not your own a legal move, despite not doing anything? 9b) Is it legal to pass a move always? If so, what should we return if we want to pass a turn? 9b2) If it's not legal to pass a turn... why? It sounds pretty useful and makes sense. Please consider it. \$\endgroup\$ Commented Oct 31, 2018 at 13:33
  • \$\begingroup\$ @NathanMerrill Thanks, I've clarified that now. \$\endgroup\$ Commented Oct 31, 2018 at 13:46
  • \$\begingroup\$ @Alion I've fixed 1, 3. I've removed next - good point (7). I've changed access to localStorage to access to this, clears between games (5,6). I've changed the scoring to a percentage and clarified draws (2). I've clarified that passing values out of bounds is illegal (8) and what (9a) does. I've also made passing legal (9b/c). (4) I did intend for cooperation (but not communication) to be legal; I've clarified that. Thanks for all the help! \$\endgroup\$ Commented Oct 31, 2018 at 14:02
  • 2
    \$\begingroup\$ Splendid work. That being said, I'm not done yet. 10) Typos: id > it (line 2 of rule explanation), bot's > bots' (last restriction). 11) Can bots modify the grid passed to them (in the non-malicious sense)? 12) Black doesn't immediately strike me as a living cell. I'd recommend specifying that there exist neutral living cells (I only realized this during my 4th reading). 13) What format should submissions be? Template and example submissions both work. 14) Controller: If you haven't already, you should check out Dave's JS KotH framework. \$\endgroup\$ Commented Oct 31, 2018 at 15:21
  • \$\begingroup\$ 15) You've opened Pandora's Box with cooperation restriction. I'll illustrate what I mean with several abstract examples. GrudgeBot and PassiveBot: GrudgeBot will not attack PassiveBot, because PassiveBot doesn't bother GrudgeBot. FriendlyBot: Attempts to make friends with bots that it comes into contact with by testing if they will attack it. 2 instances would quickly team up after meeting each other. AlgoBot: Runs simulations and tests how well other bots play according to its idea of "optimal". 2 instances quickly realize that the other is playing optimal or near-optimal moves and team up. \$\endgroup\$ Commented Oct 31, 2018 at 15:40
  • \$\begingroup\$ 15 cont.) So, where do you draw the line? 16) performance.now() for timing purposes. Introduces unpredictability, but lets bots police their own time instead of their creators having to wildly guess the right values. Allowed or not? 17) cellular-automata, game, grid (maybe). \$\endgroup\$ Commented Oct 31, 2018 at 15:44
  • \$\begingroup\$ Whew, what a rampage. Despite all of that, I'm impatiently looking forward to this hitting main. Expect to see me there immediately. Keep up the good work! \$\endgroup\$ Commented Oct 31, 2018 at 15:47
  • 1
    \$\begingroup\$ Thank you very much! I've fixed (10)-(12). I'll add an example submission when I'm finished the controller - and I will definitely check out that framework! (15) - Good point, but I don't want to give an advantage to people who build multiple bots. I've added a clarification that a test for "too much cooperation" is preset move sequences and the like - identifying a bot by its strategy is okay. There's room for interpretation, but I trust that non-malicious entries will be reasonable. All of your examples I'm okay with. :) I will add some tags. \$\endgroup\$ Commented Oct 31, 2018 at 15:58
  • \$\begingroup\$ @Alion I know it's taken way too long for me to get around to this, but if you're still interested... \$\endgroup\$ Commented Feb 17, 2020 at 17:32
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\$
8
  • \$\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\$ Commented Mar 28, 2020 at 10:46
  • \$\begingroup\$ Falsy numbers belong to A007770. \$\endgroup\$ Commented Mar 29, 2020 at 22:49
  • \$\begingroup\$ @Arnauld Nice catch + Title suggestion! \$\endgroup\$ Commented Mar 30, 2020 at 0:25
  • 2
    \$\begingroup\$ With the term "happy number" in hand, I found a probable duplicate. \$\endgroup\$ Commented Mar 30, 2020 at 8:37
  • \$\begingroup\$ Ugh, why do I always have duplicate ideas recently... \$\endgroup\$ Commented Mar 30, 2020 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\$ Commented Mar 30, 2020 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\$ Commented Mar 30, 2020 at 23:00
  • \$\begingroup\$ @Arnauld Good point, that old challenge is sure showing its rust. \$\endgroup\$ Commented Mar 30, 2020 at 23:14
4
\$\begingroup\$

Posted

Solve a Picross Row

\$\endgroup\$
2
  • 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\$ Commented May 6, 2020 at 7:54
  • 1
    \$\begingroup\$ To make the challenge more self-contained, consider adding a brief introduction to picross/nonogram and its rules. \$\endgroup\$ Commented May 6, 2020 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\$
2
  • 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\$ Commented Jul 9, 2020 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\$ Commented Jul 20, 2020 at 6:08
4
\$\begingroup\$

Solve a 2xN Maze (posted)

\$\endgroup\$
1
  • \$\begingroup\$ Now that this has been posted to main, could you delete this proposal to create more space for new answers? \$\endgroup\$ Commented Sep 25, 2020 at 1:04
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\$
11
  • 1
    \$\begingroup\$ What's the "naive fill" algorithm exactly? \$\endgroup\$ Commented Jul 12, 2020 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\$ Commented Jul 12, 2020 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\$ Commented Jul 12, 2020 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\$ Commented Jul 12, 2020 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\$ Commented Jul 12, 2020 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\$ Commented Jul 12, 2020 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\$ Commented Jul 12, 2020 at 17:03
  • \$\begingroup\$ @LuisMendo Fair enough; I've tweaked the text again now. \$\endgroup\$ Commented Jul 12, 2020 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\$ Commented Jul 14, 2020 at 15:00
  • \$\begingroup\$ @Dingus "Can the naïve bot fill the grid?" counts as similar, right? \$\endgroup\$ Commented Jul 14, 2020 at 17:23
  • \$\begingroup\$ Ooh, that's even better. Immediately makes me curious to find out what the naïve bot is. \$\endgroup\$ Commented Jul 15, 2020 at 0:35
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\$
17
  • \$\begingroup\$ Does anyone know the maths for this? Feel free to edit it in! \$\endgroup\$ Commented Nov 22, 2019 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\$ Commented Nov 22, 2019 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\$ Commented Nov 22, 2019 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\$ Commented Nov 22, 2019 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\$ Commented Nov 22, 2019 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\$ Commented Nov 22, 2019 at 13:09
  • \$\begingroup\$ @AlienAtSystem I've edited to try and make it clearer what I'm looking for. Is it clearer now? \$\endgroup\$ Commented Nov 22, 2019 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\$ Commented Nov 22, 2019 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\$ Commented Nov 22, 2019 at 13:24
  • \$\begingroup\$ Would it be better for the point on the sphere to be the input, then? \$\endgroup\$ Commented Nov 22, 2019 at 13:27
  • \$\begingroup\$ If you want the challenge to be about finding the points it's closest to, yes. \$\endgroup\$ Commented Nov 22, 2019 at 13:31
  • \$\begingroup\$ I want it to be a good challenge on this theme, whatever that would look like :) \$\endgroup\$ Commented Nov 22, 2019 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\$ Commented Nov 22, 2019 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\$ Commented Nov 22, 2019 at 14:39
  • 1
    \$\begingroup\$ Note that the actual implementation is very simple, as explained in chat. \$\endgroup\$ Commented Jul 15, 2020 at 2:43
1
9 10
11
12 13
167

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.