469
\$\begingroup\$

What is the Sandbox?

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

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

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

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

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

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

||||||
\$\endgroup\$
  • \$\begingroup\$ How are tags added to questions? \$\endgroup\$ – guest271314 Jan 9 '19 at 7:51
  • \$\begingroup\$ @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] \$\endgroup\$ – James Aug 29 '19 at 15:19
  • \$\begingroup\$ Why no featured anymore? Can't we have it auto-added or something? \$\endgroup\$ – S.S. Anne Sep 26 '19 at 15:57
  • 3
    \$\begingroup\$ @JL2210 We now have a permanent info box that links to the Sandbox, so the featured tag isn't necessary \$\endgroup\$ – caird coinheringaahing Sep 29 '19 at 13:43

2744 Answers 2744

1
21 22
23
24 25
92
2
\$\begingroup\$

List of integers to pairs ?? Any suggestions for the title ??

Write a function or a full program taking a list of non negative integers numbers L that outputs a pair of numbers [X , Y] such that X %( Y + i ) == L [ i ] .

Output specifications

  • You can output X Y in any order, just indicate it and be consistent.
  • X Y are also unsigned integers, obviously Y must be greater than 0 to avoid modulo 0 errors.
  • If your language doesn't support 0 indexed list you can consider X %( Y + i ) == L [ i + 1 ] ?? Any suggestions how to handle this ??

Example

[ 1, 2, 3 ] => [ 11, 2 ]

 11 %( 2 + 0 ) = 1
 11 %( 2 + 1 ) = 2
 11 %( 2 + 2 ) = 3

[ 10, 2 ] => [ 98, 11 ]

 98 %( 11 + 0 ) = 10
 98 %( 11 + 1 ) = 2

Test cases

[ input ] , [ output ] pairs

[ 0, 1, 2 ] ,  [ 5, 1 ]
[ 1, 2 ] ,  [ 5, 2 ]
[ 1, 2, 3 ] ,  [ 11, 2 ]
[ 1, 2, 3, 4, 5 ] ,  [ 59, 2 ]
[ 4, 3, 2, 1, 0 ] ,  [ 9, 5 ]
[ 6, 12, 18 ] ,  [ 3318, 18 ]
[ 27, 18, 9 ] ,  [ 279, 28 ]
[ 3, 9, 27 ] ,  [ 4059, 26 ]
[ 2, 4, 8, 16 ] ,  [ 8584, 14 ]
[ 0, 0, 0, 0, 0, 0 ] ,  [ 60, 1 ]
[ 1, 1, 1, 1 ] ,  [ 61, 2 ]
[ 120, 20 ] ,  [ 12220, 121 ]
[ 10, 2 ] ,  [ 98, 11 ]
[ 9, 8, 7, 0 ] ,  [ 1339, 10 ]
[ 0, 1, 4, 9, 2, 10, 4, 15, 10, 5, 0, 16, 12, 8, 4, 0, 22, 19, 16, 13 ] ,  [ 100, 10 ]
[ 9, 99, 90, 81, 72, 63, 54, 45, 36, 27 ] ,  [ 999, 99 ]

Rules

  • Input/output can be given by any convenient method.
  • You can print it to STDOUT or return it as a function result.
  • Either a full program or a function are acceptable.
  • Standard loopholes are forbidden.
  • This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

||||||
\$\endgroup\$
  • \$\begingroup\$ For the testcases I think you can omit the outer parenthesis and the trailing comma. Furthermore I'd talk about nonnegative integers instead of unsigned integers. \$\endgroup\$ – flawr Nov 17 '19 at 16:44
  • \$\begingroup\$ But I have another question: Is this problem always solvable? \$\endgroup\$ – flawr Nov 17 '19 at 16:44
  • \$\begingroup\$ @flawr thanks I'll fix then. For the second question Idk.. Numbers increase extremely, I made a program for solving the problem and also a program to do the reverse(X,Y to list) I may do some test for each X,Y to a certain number.. \$\endgroup\$ – AZTECCO Nov 17 '19 at 17:48
  • \$\begingroup\$ I don't think [0,0,1,1] has a solution (consider the parity of X) cc @flawr \$\endgroup\$ – H.PWiz Nov 17 '19 at 17:53
  • \$\begingroup\$ @H.PWiz sadly yes \$\endgroup\$ – AZTECCO Nov 17 '19 at 18:45
  • \$\begingroup\$ @flawr and H.PWiz so if it's not always solvable do I have to delete this challenge? \$\endgroup\$ – AZTECCO Nov 17 '19 at 18:47
  • 1
    \$\begingroup\$ I dunno, you could guarantee that the input is solvable. Or you could ask a different (harder) question instead: "Is there a solution?" \$\endgroup\$ – H.PWiz Nov 17 '19 at 19:06
2
\$\begingroup\$

Create a block maze solver AI

A block maze is a maze in which goal is to complete a pathway by adding blocks.

It starts like this :

#..#.
#...#
..###
.#...
.#..#

# is a block (which can be crossed). . is empty space (which cannot be crossed).

The goal is to connect top-left corner S to the bottom-right corner E. Diagonals are not allowed.

S....
.....
.....
.....
....E

One possible solution for the example above is to add three blocks like this :

#..#.
#...#
#####
.#..#
.#..#

Think about a man who want to cross a river with crocodiles . using huge stone blocks #.

The task is to create a program that take a grid as input and return a solution as output.

Scoring

The sum of all blocks required to solve all solutions in a 1.000 test case file I will provide.

The winning program is the one that use the fewest blocks to solve all mazes.

Rules

  • All grids are 25 x 25.
  • Start / end points are always top-left / bottom-right corners. There is always a block on those points.
  • There is always one guaranteed solution (which can be found by filling all empty spaces)
  • Program must be entirely deterministic; pseudorandom solutions are allowed, but the program must generate the same output for the same test case every time. If two programs take the same number of steps (e.g. they both found the optimal solutions), the shorter program will win.

The program should return the solution as a sequence of blocks x-y coordinates (the coordinates of blocks to add to solve maze) in the format of your choosing :

11-3;15-6;19-12   

Meta

  • I cannot think of a simple algorithm that returns an optimal (best possible) solution in a reasonable time. I expect programs to use some heuristics to get non-optimal/near-optimal solutions. I made the grids 25 x 25 to make it challenging enough and prevent simple solutions like brute force.
  • Is this a duplicate? There is lot of related questions but I couldn't find anything related to block maze.
  • The tags are . Anything else?

EDIT : as AlienAtSystem pointed out in comments, there is an optimal algorithm for all cases. I made some tests: even a slightly modified Dijkstra's algorithm will work (it will find shortest path in a short time). I will not post this challenge as it is trivial. I leave it here in case someone else would have same idea.

||||||
\$\endgroup\$
  • \$\begingroup\$ By fewest total steps, do you mean cumulatively? \$\endgroup\$ – Corsaka Nov 20 '19 at 10:07
  • \$\begingroup\$ I mean the sum of all blocks. If solution for maze01 use 4 blocks and solution for maze02 use 5 blocks, it is 4+5 = 9 blocks in total. The lowest is the best. Someone who has 7+1=8 blocks will win. I have edited answer. \$\endgroup\$ – tigrou Nov 20 '19 at 10:37
  • \$\begingroup\$ You should allow people to have any output format as long as it has x first, y second. None of the mazes are duplicate. I can't think of any other tags. This should be good to post. \$\endgroup\$ – Corsaka Nov 20 '19 at 10:49
  • \$\begingroup\$ Should we add a test suite of some sort? Or how are you going to verify the score of a submission? But in general the challenge looks clear. A few questions: I assume there are some test cases among the 1000 requiring us to go right/up for the optimal solution, instead of only going left/down? Are the input-characters strict, or could we also use for example 012 for @.x respectively as integer-matrix? One other relevant tag: [path-finding] \$\endgroup\$ – Kevin Cruijssen Nov 20 '19 at 13:25
  • \$\begingroup\$ @KevinCruijssen I am planning to provide a program to validate solutions. right/up : some mazes might be shorter to solve that way but it is not allowed. The goal is go from top-left to bottom-right (not to cross from left to right). character set : programs should use the same characters as the test file. Anyway, using 012 might be a good idea (I might update the test file with such chars). There is no @ character in the test file since the start / end position are always the same. \$\endgroup\$ – tigrou Nov 20 '19 at 14:31
  • \$\begingroup\$ @tigrou Ah ok, so @ is not part of the input. In that case a binary-matrix with just 0s and 1s would be a suitable input format I guess. As for the right/up: I meant it for an input like this pastebin. With this maze you could walk from the top-left to bottom-right with just 2 x insertions (at the _ positions), but you'd have to travel up and left in the path from the top-left to bottom-right. But if I understand correctly we only travel right and down, so this would be the solution (with 4 insertions at _) instead? \$\endgroup\$ – Kevin Cruijssen Nov 20 '19 at 18:38
  • 1
    \$\begingroup\$ @KevinCruijssen : both solutions you posted are valid. You can go up / down / left right at any moment. \$\endgroup\$ – tigrou Nov 20 '19 at 18:42
  • \$\begingroup\$ I can think of an algorithm that should be optimal for all test cases. This could result in the tie-breaker problem if other people realize it, too. \$\endgroup\$ – AlienAtSystem Nov 22 '19 at 6:32
  • \$\begingroup\$ @AlienAtSystem : optimal algo : is it because of my test cases (which have some flaws) or the maze challenge in general ? \$\endgroup\$ – tigrou Nov 22 '19 at 8:20
  • 1
    \$\begingroup\$ @tigrou In general. It can be translated into a shortest path challenge over a considerably smaller graph. While A* wouldn't work on that one, other algorithms will. This wouldn't be short in terms of bytes, although I suspect not that much compared to other approaches, given that some part tasks need to be done by everyone. \$\endgroup\$ – AlienAtSystem Nov 22 '19 at 9:35
  • 2
    \$\begingroup\$ I think you don't need to give up entirely right away. While this doesn't work as test-battery challenge because it's too easy to get everything right, it should be good for posting as generic code golf. \$\endgroup\$ – AlienAtSystem Nov 22 '19 at 13:36
2
\$\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 with the conditions above (i.e. coordinates representing the top of the die after it's rolled), identify the closest value (1-6) to that point (i.e. what the roll value should resolve to).

Input

A co-ordinate on the sphere.

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

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

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

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

for clarity:

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

Output

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

Usual exclusions etc. apply.

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

OEIS A125959

https://oeis.org/A125959 is a sequence I submitted. It is the following array, which then repeats:

1 2 3 4 5 6 7 8 9    
2 4 6 8 1 3 5 7 9    
3 6 9 3 6 9 3 6 9    
4 8 3 7 2 6 1 5 9    
5 1 6 2 7 3 8 4 9    
6 3 9 6 3 9 6 3 9    
7 5 3 1 8 6 4 2 9    
8 7 6 5 4 3 2 1 9    
9 9 9 9 9 9 9 9 9

This is a rather useful array for quickly calculating the digital root of the product of any two numbers (i.e the iterative sum of the digits of the product). See the OEIS link if you're interested in the details.

The challenge is to print the array in the shortest number of bytes.

Input

None

Output

The above array. It can be output as strings with new lines, or as a nested array, or an array of strings; but not as a single-line sequence (i.e. the 2d-nature of the array must be reflected in your output).

||||||
\$\endgroup\$
  • 4
    \$\begingroup\$ So it's the multiplication table mod 9, except 0s are 9's? \$\endgroup\$ – xnor Nov 25 '19 at 12:58
  • \$\begingroup\$ @xnor is it? I hadn't spotted that before. Does that stop it being an interesting challenge? \$\endgroup\$ – simonalexander2005 Nov 25 '19 at 13:49
  • 1
    \$\begingroup\$ I believe it does (because it is "create a 10x10 table of the function (-~a*-~b-1)%9+1" now). \$\endgroup\$ – my pronoun is monicareinstate Nov 25 '19 at 14:05
  • 2
    \$\begingroup\$ I think it makes it too similar to generic print-a-multiplication table challenges, but others might disagree. \$\endgroup\$ – xnor Nov 26 '19 at 2:10
2
\$\begingroup\$

Times have changed!

(pun intended)


Preface

As mathematics progressed, mathematicians agreed upon the 'order of operations', to prevent mathematical expressions from becoming ambiguous.

Given the expression \$7 \times 6 + 5 \times 3\$ we know to first evalulate multiplication, giving \$ 42 + 15\$, which is equal to \$57\$.

But what if another group of mathematicians had agreed to evaluate addition before multiplication? This expression would become \$ 7 \times 11 \times 3\ = 231\$: which is different from our answer by an error of \$305\%\$!


The Challenge

Given a mathematical expression containing + (addition), * (multiplication), and the digits 0123456789, we can find:

  • \$E_1\$ - the 'real' value of the expression, when multiplication takes precendence.
  • \$E_2\$ - the 'alternate' value of the expression, when addition takes precedence.

Your task is to write a program or function which, given a string representing an expression, calculates and outputs the percentage error, \$\frac{|E_1 - E_2|}{E_1} \times 100\$.


Rules

  • WIP.
||||||
\$\endgroup\$
  • \$\begingroup\$ Related \$\endgroup\$ – Chas Brown Dec 1 '19 at 22:33
  • \$\begingroup\$ @ChasBrown do you think it's similar enough to call this challenge a dupe? \$\endgroup\$ – FlipTack Dec 27 '19 at 14:14
2
\$\begingroup\$

Bake the cookie

Quick intro

So i was playing cookie clicker yesterday, and I thought about something. We keep producing cookies, without any loss. What if your cookies failed? This is where I thought about a clicker that would cook a cookie. Don't click too much, or the cookie will be overcooked!

Task

Your task will be to create a function that will "bake" a cookie :

  • Your function will have to randomly select a number between 5 and 10 : it will establish the cooking duration of your cookie (and so, the number of time you'll have to call the function to cook your delicious cookie).
  • Each time you call that function, it will iterate the baking process of your cookie.
  • Your function should return "Undercooked" if your cookie is not fully cooked, "Overcooked" if you ... overcooked it, and "Cooked" when the cookie is baked just right.

Example

Since I'm bad at explaining things, an example will show you more clearly what needs to be done. Let's call my function bake() :

bake()    // The random number generated is 6, so i need to call my function 6 times
Undercooked

bake()
Undercooked

bake()
Undercooked

bake()
Undercooked

bake()
Undercooked

bake()    // We hit the 6th function call, the cookie is baked.
Cooked

bake()    // The 7th call overcooked the cookie. Congratulation, you ruined it.
Overcooked

Rules

  • The random number of iterations has to be set the first time you call the function. It has to be between 5 and 10 (inclusive).
  • A cookie has to be undercooked before being cooked, and has to be cooked before being overcooked. The 3 steps have to be reachable. A cookie can't uncook itself, therefore you can't go from cooked to undercooked, or from overcooked to cooked (it's too late, you ruined the cookie anyway).
  • The function can have as many parameters as you please.
  • Classic rules apply, no standard loopholes
  • This is codegolf, so the shortest code wins.

Meta

  • Is the challenge clear enough ?
  • Should I go with this method to iterate the "baking" process ?
  • Are there some rules I could add to make it more exciting ?
  • Does this challenge exist already ?
  • Should we bake pies instead ?
||||||
\$\endgroup\$
  • \$\begingroup\$ I'm assuming bake() will take no parameters and will have to store the count somehow, which means you might want to include some rules about file and global variable I/O. I also did a small editing pass. \$\endgroup\$ – Veskah Dec 2 '19 at 16:14
  • \$\begingroup\$ @Veskah I never thout about restricting bake()'s parameters, gonna edit the rules to include this particulatiry. Also, thanks for the edits. \$\endgroup\$ – The random guy Dec 3 '19 at 8:12
  • \$\begingroup\$ I don't think I understand what you are trying to accomplish. Why do you refer to the submission always as a function? Could it not be a program? Similarly, your edit to allow arbitrarily many parameters conflicts with the general tone that seems to imply that we should be storing state between calls. I think you will want to try explaining the task simply, perhaps even to the level of a non-programmer. \$\endgroup\$ – FryAmTheEggman Dec 8 '19 at 19:47
2
\$\begingroup\$

Score a 1 player game of Carcassonne

Carcassonne is a tile-based game, where the objective is to construct Roads, Cities and Monasteries, in order to score points. The game works by players taking turns to draw and place tiles to construct a landscape, then claiming roads, cities and monasteries. An example landscape is:

Example Landscape

There are \$19\$ distinct tiles (ignoring rotations), each of which contains at least one feature (Road, City or Monastery):

All tiles

Also, notice that the landscape must be consistent. This means that roads must connect to other roads, city edges must connect to other city edges and fields must connect to fields. Therefore, these tiles are inconsistent:

Inconsistent tiles

In a normal game of Carcassonne, each feature in the landscape is claimed by a player, and contributes to their final score. However, in this version, we will change the rules slightly (primarily for people who already know the standard Carcassonne rules):

  • There will only be \$1\$ player
  • The player will automatically own every feature in the landscape
  • There will be no "badge" score for cities
    • Notice that in some of the tiles in the pictures have badge symbols on them. In this challenge, we're ignoring them.

In a landscape, each feature is either complete or incomplete:

  • A complete monastery is one where it's tile is surrounded by \$8\$ tiles. This landscape contains one complete monastery (in the center) and one incomplete monastery (Top center).
  • A complete city is one fully enclosed by walls. This landscape has \$2\$ complete cities and \$2\$ incomplete cities.
  • A complete road is one where both ends terminate at either a city, village or by forming a loop. This landscape has \$2\$ complete roads and \$2\$ incomplete roads.

A landscape is scored as follows:

  • For every complete city, the player scores \$2\$ points for every tile containing that city. Therefore this city scores \$4\$ points, and this city scores \$18\$ points.
  • For every complete road, the player scores \$1\$ point for every tile containing that road. Therefore this road scores \$6\$ points, and this road scores \$2\$.
  • For every complete monastery, the player scores \$9\$ points, such as this monastery.

  • For every incomplete city, the player scores \$1\$ point for every tile containing that city. This landscape contains two incomplete cities, one scoring \$2\$ and the other 5.

  • For every incomplete road, the player scores \$1\$ point for each tile containing that road. This landscape contains three incomplete cities, scoring \$1\$, \$2\$ and \$3\$ points.
  • For every incomplete monastery, the player scores \$1\$ point for each tile that neighbours the monastery, plus \$1\$ for the monastery itself. This landscape contains \$3\$ monasteries, scoring 2, \$5\$ and \$7\$.

Take this landscape:

Example landscape 2

This landscape contains \$1\$ complete city, \$2\$ incomplete cities, \$4\$ complete roads, \$2\$ incomplete roads and \$1\$ incomplete monastery which scores \$4 + (3+3) + (3+2+6+2) + (4+2) + 4 = 33\$ points.


To avoid this challenge being about image processing, we can translate each tile into a list containing \$5\$ values, according to this legend:

[North edge, East edge, South edge, West Edge, # of cities]

0: Field
1: Road
2: City

For instance, this tile can be described as [2, 0, 1, 1, 1]. Using this legend, we can describe each tile uniquely, and it's rotations are rotations of the first four elements. The entire grid can be described as a rectangular matrix, with a \$20^\text{th}\$ distinct value for an empty square. Translating the first landscape into this format, we get:

[
 [             [],              [], [1, 1, 0, 0, 0], [1, 1, 2, 1, 1], [0, 1, 0, 1, 0],              [],              []],
 [[1, 0, 1, 0, 0],              [], [0, 0, 0, 0, 0], [2, 0, 2, 0, 2],              [], [0, 2, 2, 2, 1], [0, 0, 0, 2, 1]],
 [[1, 1, 0, 1, 0], [0, 0, 1, 1, 0], [0, 0, 0, 0, 0], [2, 2, 0, 0, 1], [2, 2, 0, 2, 1], [2, 0, 0, 2, 1],              []]
]

using [] to represent an empty square. The complete list of tiles (ignoring rotations) in the same grid as the second image is

[1, 0, 1, 0, 0] [0, 0, 1, 1, 0] [2, 1, 1, 1, 1] [0, 1, 1, 1, 0] [2, 0, 0, 0, 1]
[2, 2, 0, 2, 1] [0, 0, 0, 0, 0] [2, 2, 2, 2, 1] [2, 2, 0, 0, 1] [2, 1, 1, 2, 1]
[2, 2, 0, 0, 2] [0, 0, 1, 0, 0] [2, 0, 1, 1, 1] [2, 1, 1, 0, 1] [0, 2, 0, 2, 1]
[1, 1, 1, 1, 0] [2, 1, 0, 1, 1] [2, 2, 1, 2, 1] [2, 0, 2, 0, 2]

Your task is to take a matrix of lists in the above format representing a landscape and to output the score the player would have if they claimed all the features, complete or incomplete, in the landscape. You may take input in any convenient method, may choose any three consistent values to represent Field, City and Road edges and may use any value to represent the empty squares that isn't already a tile. Output must be an integer represented in your language's most natural format. If you aren't sure about an I/O format, just ask.

In addition, the inputs will always have consistent landscapes, and will always have at least 1 tile. Finally, the tiles will not be constrained by the tile availability (like in the real game).

This is so the shortest code in bytes wins.

Test cases

Test cases will be added in a bit


Meta

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

Posted

||||||
\$\endgroup\$
  • \$\begingroup\$ I don't think this is possible? Surely you can't tell what direction is involved with the mirrors, e.g. /1, can you tell if the pointer started on 1 going east vs / going north? \$\endgroup\$ – Jo King Dec 18 '19 at 9:10
  • \$\begingroup\$ @JoKing Hm yeah I think your right. I will try a little more but you are right that mirrors can't be used. \$\endgroup\$ – Ad Hoc Garf Hunter Dec 18 '19 at 15:06
  • \$\begingroup\$ @JoKing I actually do think this is possible. \$\endgroup\$ – Ad Hoc Garf Hunter Dec 18 '19 at 15:15
2
\$\begingroup\$

Traverse the Bridges of Köningsberg

The Seven Bridges of Köningsberg is a logical problem that singlehandedly kicked off both the fields of topology and graph theory. The city of Köningsberg was bisected by a river, with two islands in it. Thus the city spanned four landmasses. Connecting those were seven bridges. Leonhard Euler proved that it was impossible for a person to walk through Köningsberg and cross every bridge exactly once.

The bridges, increasingly abstract representation This is an increasingly abstract representation of the problem. The bridges can be represented as edges of a graph, and the landmasses as nodes. Try to start from one node, and "walk" to the other nodes, crossing every edge exactly once (crossing nodes multiple times is okay). Euler proved that it was impossible for Köningsberg. Info on how to solve this problem for any set of islands and bridges can be found on the Wiki page.

The problem

As input, your program/function should take an adjacency matrix, in any form that you wish (e.g. concatenating every number to a single string is fine, as is making a string list, or even a built-in matrix data structure if your language has one). The examples here are provided using a csv format.

The adjacency matrix for Köningsberg looks like this:

0;2;1;2
2;0;1;0
1;1;0;1
2;0;1;0

Each row and column represents the bridges from and to specific nodes. Node 1 (first row) has 2 bridges to node 2 (second column), and vice versa. Every bridge is bi-directional, so the matrix will always be symmetrical. Bridges from a node to itself are allowed (that does not make much sense architecturally, but topology nerds recently hacked several city planning agencies to make this challenge more interesting, so do not disappoint them) - but by convention such connections are counted double in the adjacency matrix.

Output, for any given adjacency matrix, a truthey/falsey value for whether it is possible to walk so that you traverse every edge exactly once. You don't need to end up back at your starting position - that's a different problem. The maximum amount of nodes/landmasses is 9, and the maximum amount of bridges between two landmasses is also 9. The maximum amount of bridges from one landmass to itself is 4 (notated as 8 in the matrix). There is no guarantee that all the landmasses are connected - if there's islands that you cannot reach, but you can reach all the bridges, then the answer is still truthey!

This is a challenge, so the shortest challenge in bytes wins!

Test cases

2

TRUE

2;8
8;2

TRUE

6;4;9
4;0;1
9;1;0

TRUE

6;2;4;0
2;4;3;9
4;3;2;3
0;9;3;4

TRUE

6;2;4;2;5
2;8;1;1;9
4;1;6;4;8
2;1;4;8;7
5;9;8;7;8

FALSE

0;0;0;0;0;0
0;0;0;0;0;0
0;0;0;0;0;0
0;0;0;0;0;0
0;0;0;0;0;0
0;0;0;0;0;0

TRUE (there's no bridges, so they can all be reached)

2;0;0;0;0;0;0
0;2;0;0;0;0;0
0;0;2;0;0;0;0
0;0;0;2;0;0;0
0;0;0;0;2;0;0
0;0;0;0;0;2;0
0;0;0;0;0;0;2

FALSE (every landmass only connects to itself)

0;0;0;0;0;0;0;0
0;0;0;0;0;0;0;0
0;0;0;0;0;0;0;0
0;0;0;0;0;0;0;0
0;0;0;0;0;1;0;0
0;0;0;0;1;0;1;0
0;0;0;0;0;1;0;1
0;0;0;0;0;0;1;0

TRUE (starting at a landmass with a bridge, you can reach all of them)

4;0;1;6;3;6;9;7;4
0;6;1;7;2;8;5;6;1
1;1;2;6;1;4;4;3;4
6;7;6;8;9;7;0;3;4
3;2;1;9;4;8;1;0;0
6;8;4;7;8;0;6;6;8
9;5;4;0;1;6;2;3;6
7;6;3;3;0;6;3;6;6
4;1;4;4;0;8;6;6;4

TRUE

Tags

Sandbox

Do I need to include the logical solution to the problem? It's pretty simple, but I might want to make figuring that out part of the challenge.

Any other feedback welcome, of course.

||||||
\$\endgroup\$
  • 1
    \$\begingroup\$ Why are the outputs to 5th and 6th examples False? Looks like 5th is invalid (because it's not symmetric) and 6th should be True (because there are no bridges to start with, so we already walked over all bridges). \$\endgroup\$ – Bubbler Dec 17 '19 at 4:30
  • \$\begingroup\$ @Bubbler right on both counts (I was adjusting some of the squares but forgot the symmetry). Will update when I have time! \$\endgroup\$ – KeizerHarm Dec 17 '19 at 6:54
  • 1
    \$\begingroup\$ @Bubbler fixed! Thank you! \$\endgroup\$ – KeizerHarm Dec 17 '19 at 8:24
  • 1
    \$\begingroup\$ Pretty sure this is a duplicate \$\endgroup\$ – FlipTack Dec 20 '19 at 16:53
  • \$\begingroup\$ @FlipTack Oh, bugger. Is this one different enough because the input is an adjacency matrix rather than a list of bridges? \$\endgroup\$ – KeizerHarm Dec 20 '19 at 19:11
  • \$\begingroup\$ I wouldn't say so. Especially since the challenge isn't that interesting, just checking it's connected and there's 0-2 odd vertices. \$\endgroup\$ – FlipTack Dec 21 '19 at 6:55
  • \$\begingroup\$ Especially because the degree of a node is simply the sum over its line in the adjacency matrix. \$\endgroup\$ – AlienAtSystem Dec 22 '19 at 16:52
2
\$\begingroup\$

Title: When is Hannukah?

Input

The input will be a year between 1583 and 2250.

Output

The Gregorian date of the first evening of Hannukah that year. That is the day before the first full day of Hannukah. Your code should output the month and day of the month in any easy to understand human readable form of your choice.

Examples

2013    November 27 
2014    December 16
2015    December 6  
2016    December 24 
2017    December 12 
2018    December 2  
2019    December 22
2020    December 10 
2021    November 28 
2022    December 18
2023    December 7  
2024    December 25 
2025    December 14 
2026    December 4  
2027    December 24
2028    December 12 
2029    December 1  
2030    December 20 
2031    December 9  
2032    November 27 
2033    December 16

How do you do this?

It could hardly be simpler. We start with a couple of definitions:

We define a new inline notation for the division remainder of \$x\$ when divided by \$y\$: $$(x|y)=x \bmod y$$

For any year Gregorian year \$y\$, the Golden Number, $$G(y) = (y|19) + 1$$ For example, \$G(1996)=2\$ because \$(1996|19)=1\$.

To find \$H(y)\$, the first evening of Hannukah in the year \$y\$, we need to find \$R(y)\$ and \$R(y+1)\$, the day of September where Rosh Hashanah falls in \$y\$ and in \$y+1\$. Note that September \$n\$ where \$n≥31\$ is actually October \$n-30\$.

$$R(y)=⌊N(y)⌋ + P(y)$$ where \$⌊x⌋\$ denotes \$x-(x|1)\$, the integer part of \$x\$, and

$$N(y)= \Bigl \lfloor \frac{y}{100} \Bigr \rfloor - \Bigl \lfloor \frac{y}{400} \Bigr \rfloor - 2 + \frac{765433}{492480}\big(12G(y)|19\big) + \frac{(y|4)}4 - \frac{313y+89081}{98496}$$

We define \$D_y(n)\$ as the day of the week (with Sunday being \$0\$) that September \$n\$ falls on in the year \$y\$. Further, Rosh Hashanah has to be postponed by a number of days which is

$$P(y)=\begin{cases} 1, & \text{if } D_y\big(\lfloor N(y)\rfloor \big)\in\{0,3,5\} & (1)\\ 1, & \text{if } D_y\big(\lfloor N(y)\rfloor\big)=1 \text{ and } (N(y)|1)≥\frac{23269}{25920} \text{ and } \big(12G(y)|19\big)>11 & (2)\\ 2, & \text{if } D_y\big(\lfloor N(y)\rfloor \big)=2 \text{ and } (N(y)|1)≥\frac{1367}{2160} \text{ and } (12G(y)|19)>6 & (3)\\ 0, & \text{otherwise} & (4) \end{cases}$$

For example, in \$y=1996\$, \$G(y)=2\$, so the \$N(y)\approx13.5239\$. However, since September 13 in 1996 was a Friday, by Rule \$(1)\$, we must postpone by \$P(y)=1\$ day, so Rosh Hashanah falls on Saturday, September 14.

Let \$L(y)\$ be the number of days between September \$R(y)\$ in the year \$y\$ and September \$R(y+1)\$ in year \$y+1\$.

The first evening of Hannukah is:

$$ H(y)=\begin{cases} 83\text{ days after }R(y) & \text{if } L(y)\in\{355,385\}\\ 82\text{ days after }R(y) & \text{otherwise} \end{cases} $$

Notes and thanks

Thank you to @Adám for pointing me to the rules. To keep things simple, this challenge assumes the location to be Jerusalem.

||||||
\$\endgroup\$
  • \$\begingroup\$ Please type out the rules on that image into actual text. Challenges are supposed to be self-contained, while that image will be subject to link rot. Also, it's lacking an explanation how the Golden Number G is calculated. \$\endgroup\$ – AlienAtSystem Dec 29 '19 at 20:26
  • \$\begingroup\$ What if the given year has no Hannukah? Or there are two "first day of Hannukah"s in the given year? \$\endgroup\$ – Adám Dec 30 '19 at 10:56
  • \$\begingroup\$ @Adam. Now you have confused me! For which years between 1900 and 2100 were there 0 or 2 Hannukahs? \$\endgroup\$ – Anush Dec 30 '19 at 11:01
  • \$\begingroup\$ @Anush Ah, I didn't notice the range. 3031 will have 0 and 3032 will have 2. \$\endgroup\$ – Adám Dec 30 '19 at 11:17
  • \$\begingroup\$ Hold on, the first evening? That'd be the day before before the "first day of Hannukah". You should be very clear about this. \$\endgroup\$ – Adám Dec 30 '19 at 11:26
  • \$\begingroup\$ Hm, I just noticed that there's a risk of people actually not implementing the algorithms, but instead relying on a built-in calendar conversion. Though you don't state it, the answer is always the 24th day of the month Kislev in the Hebrew year CivilYear+3761. \$\endgroup\$ – Adám Dec 30 '19 at 11:47
  • \$\begingroup\$ Also, you may want to extend the valid input range. Otherwise it will often be shortest to hard-code the dates, e.g. in base 30. \$\endgroup\$ – Adám Dec 31 '19 at 14:31
  • \$\begingroup\$ @Adam Could you please double check the formula in the question actually matches the example dates I have given. If so, I will post the question. \$\endgroup\$ – Anush Dec 31 '19 at 14:43
  • 1
    \$\begingroup\$ Working on it... \$\endgroup\$ – Adám Dec 31 '19 at 15:00
  • 1
    \$\begingroup\$ OK, I've tried it now and it works. It actually works. However, don't go ahead and post yet; There are a few issues to address. \$\endgroup\$ – Adám Dec 31 '19 at 15:39
  • \$\begingroup\$ The first day of Hannukah day 84 if Rosh Hashanah is day 1, so you need to add 83 to get the first day of Hannukah, but 82 to get the evening before. \$\endgroup\$ – Adám Dec 31 '19 at 15:40
  • \$\begingroup\$ The last three paragraphs are superfluous as your range is bigger. However, I also suggest adjusting the range somewhat. If you go above 2239 then .NET won't help (which may be good or bad depending on whether you want to push people to implement the actual algorithm instead of just converting the Hebrew date using the built-in. In any case, the Hebrew calendar isn't really defined beyond 2250. \$\endgroup\$ – Adám Dec 31 '19 at 15:47
  • \$\begingroup\$ You can however pull back the earliest year to 1583, but not earlier, as that's the first year of the civil calendar. \$\endgroup\$ – Adám Dec 31 '19 at 15:49
  • \$\begingroup\$ The mathematical formulas are really awkwardly written. Maybe MathJax those? I can do it if you want. \$\endgroup\$ – Adám Dec 31 '19 at 15:50
  • 2
    \$\begingroup\$ I would adjust the output requirements to read "The Gregorian date of the first evening of Hannukah." to pre-empt people just submitting print("24 Kislev"). \$\endgroup\$ – AlienAtSystem Jan 1 at 8:24
2
\$\begingroup\$

Posted: Find the Inverse Neighbor Pairs

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

Decode the password

Given a printable ASCII string separated with spaces, output the specified index of every word. E.g.

"are turbas unsafe ?!", 1

will yield run!

  • When the index is out of bounds, this index should yield the null string (which can be joined with other strings).

More test cases

"Is Pascal truly unloyal to users?",3 -> "sure"
"I'd pass kittens to anyone stopping by!!",4 -> "stop!"
||||||
\$\endgroup\$
  • 1
    \$\begingroup\$ The definitive answer here is yes. \$\endgroup\$ – Lyxal Feb 3 at 6:58
  • \$\begingroup\$ I assume this was just meant to be laying out the idea not to forget about it. But just in case I figured I should say that you definitely need to specify what happens when the index is too large for one of the substrings, and that the rest of the string will be printable ascii / whatever you choose. \$\endgroup\$ – FryAmTheEggman Feb 5 at 17:19
  • 1
    \$\begingroup\$ The first test case in the more test cases section seem wrong should it not yield "sule" and not "sure"? \$\endgroup\$ – Mukundan Feb 11 at 15:56
  • 2
    \$\begingroup\$ And the last test case only works for 1-indexing, while all others are 0-indexed. \$\endgroup\$ – AlienAtSystem Feb 11 at 16:10
  • \$\begingroup\$ What happened to this user? \$\endgroup\$ – S.S. Anne Feb 11 at 23:58
2
\$\begingroup\$

Is this entire list likewise-modulus-aligned?

A pair of numbers are aligned in a modulus when they all share the same remainder when they can be put under the modulus function against an integer greater than or equal to 2 and less than or equal to the absolute value of both.

For example,

13 and 22 are aligned numbers under 3 because
13%3 = 1
22%3 = 1

3<=13, 3<=22, and 3>=2

All our requirements are met.

A list is likewise-modulus-aligned when all the elements are aligned under the same modulus base.

Challenge

Take in a list (not necessarily non-empty) of non-zero integers (not necessarily positive nor unique), and check if all the elements are likewise-modulus-aligned. Output is a truthy or falsy value.

Note; This is a "true-until-proven-otherwise" problem, meaning a single value in the list or an empty list will return TRUE.

Example I/O

      In      | Out | Why
--------------|-----|---------
         [5 7]|TRUE |1 mod 2
     [7 12 18]|FALSE|(7,18) are not mod-aligned
     [7 11 19]|TRUE |1 mod 2
  [5 13 28 44]|FALSE|(5,28) are not mod-aligned
[10 13 37 108]|FALSE|(37,108) aren't aligned in any base below 10
            []|TRUE |No disproven pairs
          [42]|TRUE |No disproven pairs
    [-5 13 16]|TRUE |1 mod 3
      [1 9 18]|FALSE|Arrays of size 2 or greater with 1 or -1 will always be false
    [14 17 19]|FALSE|Every pair is modulus-aligned, but not under the same base
[17,22,32,107]|TRUE |2 mod 5
      [4,8,12]|TRUE |0 mod 2
        [-1,1]|FALSE|No mod 1 allowed
           [1]|TRUE |No disproven pairs
       [7,7,7]|TRUE |Numbers >=2 are always mod-aligned with themselves
     [2,2,8,8]|TRUE |0 mod 2
   [3 9 22 22]|FALSE|Pairs don't suddenly make (9,22) mod-aligned.

Sandbox Questions

I'm gauging the interest to this question and seeing if this is an acceptable and unique challenge, just want to make sure I haven't missed another post doing a similar thing.

I changed the rules to be a lot more lenient on the comparisons, might do the pairwise comparison as a bonus or follow-up challenge later. But this is a compromise I can live with.

Extra Hints/Tips

For all non-1 derivations, a number will be aligned with its negative self.
1 is never aligned with any other number, nor will -1.
A number that is a multiple of another will be aligned with that number in all its factors.
Numbers that share factors will always align, but numbers that don't share factors also may.
All odd numbers are aligned with each other, as are all even numbers.

||||||
\$\endgroup\$
  • 1
    \$\begingroup\$ I'm not clear on why this challenge asks to compare all pairs of a list, rather than just a single pair. The condition covers pairs of numbers, so it would be more natural to just receive a pair of numbers as input. \$\endgroup\$ – isaacg Feb 19 at 18:21
  • \$\begingroup\$ Because it's a combination of that function and a list-pair function with interesting shortcuts that can overlap. Asking for a pair could take X bits, and pushing all pairs to a function could take Y, but the combination of the two isn't necessarily X+Y. In my going at it, I saved like 8 bytes in the mix by being clever. This way, there are several ways to solve while still being a challenge. \$\endgroup\$ – Mathgeek Feb 19 at 18:24
  • 2
    \$\begingroup\$ Some test cases that are not 1 mod x would be good \$\endgroup\$ – Jo King Feb 20 at 5:21
  • \$\begingroup\$ Good suggestion, Jo. I just added one, and I'll add a few more in a bit - I hadn't even caught that! \$\endgroup\$ – Mathgeek Feb 20 at 13:32
  • 2
    \$\begingroup\$ While what you observed can be true, in my experience it is not usually a source of interest in golfing to combine tasks unnecessarily. Similarly, does including negative numbers make this task more interesting? In most languages this will not make a difference, but it will make answering in some languages (consider Retina) substantially more difficult - to the point where people probably won't answer. I always try to recommend making a challenge as simple as possible - just like writing a proof. \$\endgroup\$ – FryAmTheEggman Feb 20 at 18:59
  • \$\begingroup\$ I made negative numbers allowed because negative modulus is still a valid application of modulus - but that argument of "combining two things" is applicable to like literally every other code golf question. The string-wise calculus question could have just been "print out which of two characters is the largest", but then there was added difficulty to comparing pairs and assigning those values to distinct characters. This isn't just an arbitrary expansion, it's a setwise comparison of several elements applied over a function; You see these "expansions" all the time, so why is this one an issue? \$\endgroup\$ – Mathgeek Feb 20 at 19:24
  • \$\begingroup\$ I agree that the part of the challenge where you check every pair seems unnecessary, and was going to comment on this independently. I think just having two numbers as inputs would make a better challenge overall. Or, have all numbers in the list need to be aligned by the same modulus, which seems like a more natural extension. \$\endgroup\$ – xnor Feb 20 at 19:33
  • 2
    \$\begingroup\$ Okay, what about a fairer follow-up instead - instead of checking if all pairs are modulus-aligned, a list is modulus-aligned if all the entries share an identical mod-point. ie: They all have to be n mod m together for the list to be valid. Think that's still a more fair question? I think submitting pairs only is a very low-level simple problem that doesn't have any real puzzle or golfing elements to it, so I'd like it to be slightly more complex somehow. \$\endgroup\$ – Mathgeek Feb 20 at 19:37
  • 2
    \$\begingroup\$ What you and xnor propose sounds good to me. I tried to phrase what I said as suggestions and opinions, because that is all they are. There isn't anything wrong with what you have, but I know I'd be more likely to answer if you changed some things about it. The same is true for many challenges on this site (including my own). Over time, I've come to see that including requirements that are technically valid but aren't necessary rarely adds interest to a challenge. \$\endgroup\$ – FryAmTheEggman Feb 20 at 20:29
  • 1
    \$\begingroup\$ Doesn't [10 13 37 109] satisfy 1 mod 3 (and therefore it is modulus-aligned)? \$\endgroup\$ – Bubbler Feb 20 at 23:45
  • \$\begingroup\$ You're correct fixed! \$\endgroup\$ – Mathgeek Feb 21 at 13:14
  • 1
    \$\begingroup\$ @KevinCruijssen But that's fine. If I have a list [7, 14], they are aligned under Base 7. \$\endgroup\$ – Mathgeek Feb 21 at 14:40
  • 1
    \$\begingroup\$ I also just read the "(not necessarily positive nor unique)" part of your challenge, so you might want to add a few test cases containing multiple of the same number in that case. \$\endgroup\$ – Kevin Cruijssen Feb 21 at 14:46
  • 1
    \$\begingroup\$ Nice challenge btw. And good choice on explicitly mentioning "Note; This is a "true-until-proven-otherwise" problem, meaning a single value in the list or an empty list will return TRUE.", since those [1]/[-1] test cases are really annoying in my approach. ;) I had a prepared solution which worked for all initial test cases in 10 bytes, but now it's 50% larger to 15 bytes just to fix those two test cases, haha. Looking forward to when it goes live. I would leave it in the sandbox for a little while longer for others to give feedback though, just in case. Oh, and welcome to CGCC! \$\endgroup\$ – Kevin Cruijssen Feb 21 at 15:05
  • 1
    \$\begingroup\$ @xnor yes, the question then dissolves to finding whether the gcd of the differences of consecutive elements is >1. \$\endgroup\$ – Don Thousand Feb 21 at 16:09
2
\$\begingroup\$

Square-Cube Digit Usage

||||||
\$\endgroup\$
  • \$\begingroup\$ In response to the first sentence: nice. \$\endgroup\$ – Lyxal Feb 20 at 0:43
  • \$\begingroup\$ I'm not exactly sure how your title relates to the challenge. Obviously "Square-Cube Digit Usage" won't exactly roll off the tongue, but what you have now seems misleading. \$\endgroup\$ – FryAmTheEggman Feb 20 at 20:22
  • \$\begingroup\$ Nice challenge. I prepared a solution for when it goes live. I would add a few more test cases first, though. One suggestion: 1333 (or 3133/3313/3331) -> 111 (first positive integer as input that has a 3-digit number as output). Here the results for the first 10,000 inputs. \$\endgroup\$ – Kevin Cruijssen Feb 21 at 10:53
2
\$\begingroup\$

Draw an American flag for any amount of states

The flag of the United States of America goes by many names. The Stars and Stripes. Old Glory. The Last Known Non-Erotic Usage Of The Verb 'To Spangle'.

It is also one of the few flags semi-regularly updated. The red and white stripes represent the 13 original states, but one more star has been added to the blue canton for every state that joined the union later. This last happened in 1960, when Hawaii got in. Flag designs with 51 stars are already waiting for when Puerto Rico or Washington D.C. are made states, but this vexillologist is lazy. You are to make a program that can draw the flag with any number of stars desired!

Specification

Here's a neat image of the official, government-standardised design for the current U.S. flag: flag design

Disregard the contents of the canton for now. Your program must draw a flag that adheres to only the ratios I give here:

  • A (the height of the flag) = 1
  • B (the width of the flag) = 19/10
  • C (the height of the canton) = 7/13
  • D (the width of the canton) = 19/25
  • L (the height of any stripe) = 1/13

Because raster solutions are not exact and this flag is commonly misdrawn anyway, there's tolerance of 2% for every ratio, taking the flag height as the base.

Furthermore, the correct colours must be used.

  • Every odd-numbered stripe must be this shade (hex): #B22234
  • The blue canton must be in this shade: #3C3B6E
  • Every even-numbered stripe, and every star, must be in this shade: #FFFFFF

Conversions to other colour coordinate systems can be found on the wiki page as well.

Stars

Your program must takes as input any integer between 0 and 200, and draw that number of stars within the canton. The following rules apply.

  • Each star must have five outer points and be five-fold rotationally symmetrical.
  • Each star must be the same size.
  • The bounding circles of stars may overlap, but the surface of the stars itself may not overlap.
  • The bounding circles of the stars may go outside the canton, but the surface of the stars itself may not go outside the canton.
  • I don't want solutions that just place every star on the same line; that would leave a lot of blue canton untouched, which would be a waste. So, as a rule, the combined surface area of the bounding circles of every star in the canton must be at least 20% of the surface area of the canton.

    Since overlapping bounding circles still count, you get a formula for the minimum width w of the star, where a is the area of the canton and n the number of stars: formula. See here for how it's derived.

Other specifications

There's no minimum or maximum size for your output image, though I recommend something that will allow 200 stars to fit but still be demonstrably star-shaped. When they are only a few pixels high, it becomes hard to argue that they have the required amount of points. Obviously, for vector solutions any size is permissible.

This is , so the smallest program wins!

Test cases

Because I gave no specific arrangement of the stars (you may arrange them however you want), there is an infinite number of correct and incorrect solutions for each number of stars. These are just examples of valid and invalid solutions:

Valid:

valid1

Invalid (stars too small):

invalid1

Valid:

valid2

Invalid (stars of unequal size, going out of the canton):

invalid2

Invalid (stars have too many points, stripes have wrong colours, colours are the wrong hue, proportions are wrong):

invalid3

Sandbox

Do I need more test cases? Any other feedback?

||||||
\$\endgroup\$
  • 2
    \$\begingroup\$ If you really want to allow 0 as an input, you'll need an exception to the rule that the combined areas of the bounding circle must be at least 20% of the area of the canton. (If there aren't any stars, there aren't any bounding circles, so the combined areas would be 0.) \$\endgroup\$ – Mitchell Spector Mar 7 at 2:19
  • 4
    \$\begingroup\$ I know it's less thematic, but maybe the task could be just to draw the canton? Arranging and drawing the stars is the interesting part, whereas the stripes aren't changing, so in terms of golfing the stripes seem somewhat extraneous. I guess you could also have the number of stripes be variable. \$\endgroup\$ – xnor Mar 7 at 17:40
2
\$\begingroup\$

God is real . . . unless declared integer

||||||
\$\endgroup\$
  • \$\begingroup\$ Newbie here. Looking for general feedback on this challenge. \$\endgroup\$ – Dingus Mar 24 at 13:10
  • \$\begingroup\$ Are the implicit statements guaranteed not to overlap? Or might it be the case that, for a list of implicit type declarations, one pair sets GOD to be something, and then a later pair re-sets GOD to be of a different type? \$\endgroup\$ – RGS Mar 24 at 18:33
  • 1
    \$\begingroup\$ @RGS yes, guaranteed not to overlap. Edited the fourth bullet point. \$\endgroup\$ – Dingus Mar 24 at 22:22
  • \$\begingroup\$ I'd suggest not including the No. column in the test cases. People often just copy-paste these into their verification code, and extra characters make that slightly more annoying. \$\endgroup\$ – xnor Mar 25 at 0:46
  • 2
    \$\begingroup\$ You might want to have a test case with something like I(G-G). This looks like a good first challenge. Thanks for using the sandbox, and for responding to feedback! :) \$\endgroup\$ – FryAmTheEggman Mar 25 at 18:52
  • \$\begingroup\$ @FryAmTheEggman thanks, great suggestion. I had to go and check whether that works in Fortran! Also added two more test cases: the simple I(G) and the last one, where all identifiers randomly appear multiple times and each letter's type is individually specified. \$\endgroup\$ – Dingus Mar 25 at 23:06
2
\$\begingroup\$

Excessively complicated Game of Life

In the excessively complicated version of the Game of Life, the world is a \$W \times H\$ square torus with a grid of squares. Each square has a rulestring attached to it - by default, B/S. Each square has a dead or alive cell in it. Each alive cell is controlled by a player. Every turn, if there is not an alive cell in a square, it is born iff the part between B and / contains the number of alive neighbours. Every turn, if there is an alive cell in a square, it survives iff the part after S contains the number of alive neighbours. Cells are considered adjacent if they have a common edge or a corner. A cell is not adjacent with itself. Cells controlled by other players also count as alive neighbours.

For example, normal Conway's Game of Life cells have the B3/S23 rulestring: cells are born if they have exactly 3 alive neighbours, and survive if they have 2 or 3.

Each player starts with a B/S012345678 cell, placed uniformly randomly.

Each cell knows a 3x3 array of numbers from \$-1\$ to \$1\$, representing adjacent cells (including self). \$1\$ in it means an ally cell, \$0\$ means a dead cell, and \$-1\$ means an enemy cell, and a 3x3 array of rulestrings for adjacent cells.

Every turn, every cell can alter one bit of the rulestring of any adjacent square (including its own) - that is, remove or add a number from it (or, alternatively, it can do nothing).

When cells are born, the player they belong to is chosen semi-randomly: the odds of the cell being assigned to a player are proportional to the number of cells they contributed to the cell's birth.

A player is eliminated when all their cells die. When \$N\$ turns passed, or when only one player remains, the game ends. A full point is distributed between all remaining players proportionally to the number of cells they control (dead cells don't count).

Clarifications

  • Rulestrings are attached to squares, not to cells. When a cell dies, the rulestring on its square is not changed.
  • No cell can be born with zero alive adjacent cells (that is, rulestrings cannot start with B0).
  • When multiple cells attempt to alter the same bit in a rulestring, it is only affected once.

Challenge

Define a pure function \$(nearbyStates, nearbyRules)\to(\Delta x, \Delta y, index)\$ to be used as the algorithm for your cells. To do nothing, output an index of 0.

Otherwise, an index of 1 corresponds to toggling B1, 2 to B2 and so on until B8, the index 9 is skipped, then an index of 10 corresponds to toggling S0, 11 to S1 and so on until S8.

Winning criterion

\$X\$ games are run, and the leaderboard is formed by sorting participants by the total number of points.

This is , so whoever wins wins!

Sandbox stuff

  • Is this a good idea?
  • Is the description of the game clear?

I think I decided that the language for submissions will be Javascript. Now I have to write a controller.

Besides the obvious Javascript option, I am considering C++ with a Javascript engine (probably V8). This can multiply the performance by \$\%NUMBER\_OF\_PROCESSORS\% \cdot \frac{cppPerformance}{jsPerformance} \cdot \frac{myC++skill}{myJSskill}\$, which can be quite large. Unfortunately, that might also muptiply the challenge's popularity by \$\frac{webBrowserLoadingSpeed}{programInstallationSpeed}\$, which can be quite small! Would that be a good idea?

||||||
\$\endgroup\$
  • \$\begingroup\$ Disclaimer: I'm biased in both categories. Language: Leaning towards JS, especially since this challenge seems to be of the "hack around and see what works" type, and I believe browser-based ones shine here the most. Python seems to be popular as well, but AFAIK it's usually used for challenges that don't need rich visualization. Other languages, like Java, .NET, C++, etc., can also be considered, of course (higher performance)... Orientation: Removing orientation does seem to be a good fit. It increases the amount of interactions that can happen between any two entries. \$\endgroup\$ – Alion Mar 26 at 18:31
  • \$\begingroup\$ Regarding C++: You can have your cake and eat it too. Have you heard of Wasm and Web Workers? This combination lets you get near-native peformance along with multithreading all in the browser. \$\endgroup\$ – Alion Mar 29 at 13:40
  • \$\begingroup\$ Note that improving controller performance only gets you so far. You're gonna have to go the Formic route and cache entry responses in some smart way to extract all the potential of C++. \$\endgroup\$ – Alion Mar 29 at 13:48
  • \$\begingroup\$ @Alion I include "caching in some smart way" in "improving controller performance". I have also considered using Emscripten (and started using it, starting with the renderer first, because I randomly decided so) but then I got worried because I thought calling JS from WASM and WASM from JS is going to be too slow. After reading the comment, I googled and it turned out Emscripten has multithreading. I guess I'll continue now. \$\endgroup\$ – my pronoun is monicareinstate Mar 29 at 13:50
  • \$\begingroup\$ I'd like to see a good C/C++ KoTH. I'm always excluded from them because I don't know any languages that they're in. \$\endgroup\$ – S.S. Anne yesterday
  • \$\begingroup\$ @SSAnne I do not understand your comment. Are you proposing a C/C++ KoTH, or are you stating that they cannot be good because you don't know these languages? \$\endgroup\$ – my pronoun is monicareinstate yesterday
1
\$\begingroup\$

I've Got The Key, I've Got The Secret

A cryptography challenge in 2 parts.

Part 1

Implement a pair of programs in any language (the two programs could be in different languages if you wanted) to encode and decode a string of plaintext.

Input and Output

The encoder must take the plaintext (and an optional key) and return an encoded string. The decoder must take the cyphertext (and an optional key) and return the plaintext exactly as it was given to the encoder.

Restrictions

  • The encoding and decoding code must be entirely implemented in the language - no libraries or cryptography functions may be used.
  • The code (encoder+decoder) cannot be longer than 1024 characters.

Part 2

Implement programs (multiple programs per answer, one answer per entrant) which crack your opponents encryption algorithms.

Input

The cyphertext.

Output

The plaintext that generated the ciphertext.

Scoring

I will upvote all answers to part 1 which have working encryption and have obviously made an attempt at golfing their answer.

In order to be eligible to win, an entrant will have to have taken part in both parts of the question. Overall score will be (length of shortest program that cracks your code-(length of encoder+length of decoder)). Highest score wins and winning entrant's entries will be accepted on both questions.

||||||
\$\endgroup\$
  • 1
    \$\begingroup\$ The obvious place for this to fall flat on its face is if someone is able to implement AES or something similar within the 1024 character restriction. \$\endgroup\$ – Gareth Jun 13 '12 at 13:06
  • 1
    \$\begingroup\$ Probably better if the methods of the part one programs are disclosed in non-obfuscated language, though with the short length restriction this may not be necessary. \$\endgroup\$ – dmckee --- ex-moderator kitten Jun 13 '12 at 15:23
  • 2
    \$\begingroup\$ Forget AES: RSA is easily doable. That aside, you need to define "crack" in part 2. \$\endgroup\$ – Peter Taylor Jun 13 '12 at 15:35
  • 1
    \$\begingroup\$ Also, it's not clear whether "optional key" means that it's optional to make the algorithm unkeyed (doesn't make much sense, I admit) or optional to supply it, in which case it uses a default key. \$\endgroup\$ – Peter Taylor Jun 13 '12 at 15:42
  • 1
    \$\begingroup\$ @PeterTaylor I just put optional in to leave it up to the implementer whether or not they wanted to have the key input or hard-coded (or use no key). I'd have thought everyone would have the key input into their program, but I didn't want anyone to feel forced into it by the spec. Hmm, if RSA is doable within the character restriction I'll end up with a load of unbreakable codes which would make for a pretty crap part 2. By crack I meant cyphertext goes in, some time later plaintext comes out. Would restricting the character count further help, or is this question beyond help? \$\endgroup\$ – Gareth Jun 13 '12 at 16:05
  • 3
    \$\begingroup\$ On that definition of crack, I can brute force for the length of the decoder plus a few bytes to iterate over all keys of the right length and some heuristics to check plausibility of the plaintext. The brute force cracker might even be shorter than the decoder if the decoder wasn't written in GolfScript... I think this question may be beyond help. \$\endgroup\$ – Peter Taylor Jun 13 '12 at 16:28
  • 3
    \$\begingroup\$ @PeterTaylor Okay, thanks. I like the 'build your own - knock everyone else's down' aspect of this question though. I'll have to find another area where it could apply. \$\endgroup\$ – Gareth Jun 13 '12 at 16:34
  • 2
    \$\begingroup\$ @Gareth I too like the competitive nature of this idea. I'm looking forward to a question with this plan in mind! \$\endgroup\$ – Gaffi Jun 13 '12 at 19:31
  • 1
    \$\begingroup\$ I think it would be better to split this into a "cops" post and a "robbers" post. \$\endgroup\$ – wizzwizz4 Feb 16 '17 at 9:46
  • 1
    \$\begingroup\$ @wizzwizz4 Wow, this is another blast from the past. I think this pre-dates the cops-and-robbers tag. I always seem to be ahead of my time. :-) \$\endgroup\$ – Gareth Feb 16 '17 at 9:49
  • 1
    \$\begingroup\$ Can we delete this because the sandbox lags so much and this hasn't been touched in 5 years? \$\endgroup\$ – programmer5000 Apr 13 '17 at 17:35
1
\$\begingroup\$

Countability of Sets of Finite Sets

The aim of this challenge is to code-golf a program which returns an iterator that will iterate over all possible non-empty finite sets of positive integers.

So if running long enough, this iterator should eventually touch on {1}, {2, 5}, {3, 6, 112} (ie none of these should occur "at infinity")

You may choose the order in which you iterate over these sets, but the order must satisfy the following requirement:

Under a particular ordering, if S is the i'th set to be returned by the iterator, then we shall call i the index of set S.

Let a restriction (k,T) be an assertion about a set S that says S has size k and T is a subset of S.

For a given restriction (k,T) and iterator IT, let the restricted iterator be the iterator which takes sets returned by IT and filters out sets that don't satisfy the assertion, iterating only over the ones that do. In other words, if IT iterates over the sequence of all sets, the restricted iterator iterates over the subsequence satisfying (k,T). Now if S is the n'th set returned by the restricted iterator, then we'll call n the restricted index of S with respect to (k,T)

Your ordering must satisfy the property that for any restriction there exists a polynomial P(x) such that for any set satisfying the restriction (with index i and restricted index n), i < P(n)

Note that the following ordering is not acceptable:

{1} {2} {1, 2} {3} {1, 3} {2, 3} {1, 2, 3} {4} {1, 4} {2, 4}...

This is the sequence that comes from counting 1, 2, 3, 4, 5, 6... and listing the set bits in the binary representation of each number.

This is because the restriction (1, {}) satisfies only the sets {1}, {2}, {3}, {4}... whose index i as a function of their restricted index is i=2^(n-1) which is not bounded by any polynomial


Sandbox Questions

The reason for the strange requirement at the end is to disqualify any variants on the most natural ordering which simply counts upwards from 1 and enumerates the set bits in each number. In this ordering, the n'th set of length-one occurs at index 2^n which is non-polynomial.

I posted this problem originally, but didn't think of the obvious solution and so I left out the final restriction. I'd like to re-post it with the extra restriction. But first I'd like to know what people think. Is there a better way I can word that restriction or a more natural restriction I could impose instead?

||||||
\$\endgroup\$
  • 1
    \$\begingroup\$ I don't understand the extra restriction, so I can't suggest a rewording, but I can say that it needs one. (In particular: what is k? And what function does T serve? Is it really a parameter of the property?) \$\endgroup\$ – Peter Taylor Jun 18 '12 at 8:25
  • 1
    \$\begingroup\$ I don't understand it either. Maybe a sample of an ordering, satisfying the requirement, and another one, violating it, would help. \$\endgroup\$ – user unknown Jun 18 '12 at 15:31
  • 1
    \$\begingroup\$ I understand the restriction now, although I haven't worked through the full implications. Does allowing T to be non-empty make a significant difference at all? \$\endgroup\$ – Peter Taylor Jun 19 '12 at 6:52
  • 1
    \$\begingroup\$ I don't know. It may not. I guess the size part is the important part. I was just thinking that the ordering should be such that you run into all kinds of sets frequently. \$\endgroup\$ – dspyz Jun 20 '12 at 7:17
  • 1
    \$\begingroup\$ Can we delete this because the sandbox lags so much and this hasn't been touched in 5 years? \$\endgroup\$ – programmer5000 Apr 13 '17 at 17:36
1
\$\begingroup\$

The One with Two Parts

The aim of this challenge is to create a pair of functions which scramble and unscramble any given piece of text.

Part 1

In part one you post your scrambling function, along with the length in characters and language of your unscrambling function (but NOT its code). The length of the scrambler does not affect your score so you needn't golf it unless you want to. The two functions may be written in different languages if you wish.

Input/Output

The scrambling function should take one argument only - a string containing the input text - and return a string containing the scrambled text. The unscrambling function should also take only one argument - the scrambled text - and return the original text. The input text will be limited to characters in the ASCII set range from 0 to 127.

Part 2

In part two you try to beat your opponents' scores for their unscrambling functions. You MUST use the language they specify for their unscrambler in part one. Please give just one answer to this question containing all your unscrambling functions making it clear which question in part one each function unscrambles (maybe each answer in part one should give its scrambler a name for identification?).

Once the closing date (TBA) has passed all participants should post their unscrambling functions in their answer to part one to prove the length, language and functionality of their function.

Scoring The participants score will be calculated as follows: (unscrambler length from part one) - (shortest unscrambler length from part two). The participant with the lowest score wins and will have their answers accepted on both parts of the challenge. To be eligible to win a participant must have taken part in both parts of the question.

Example

In part 1:

  • Bob posts a Python answer and says his unscrambler is a 165 character Python function.
  • Fred posts a GolfScript answer and says his unscrambler is a 59 character GolfScript function.
  • Joe posts a JavaScript answer and says his unscrambler is a 180 character PHP function.
  • Jim posts a Ruby answer and says his unscrambler is 163 character Ruby function.

In part 2:

  • Bob posts an 82 character GolfScript function to unscramble Fred's scrambled text. He also posts a 175 character PHP function to unscramble Joe's scrambled text.
  • Fred posts a 181 character PHP function to unscramble Joe's scrambled text.
  • Joe posts a 150 character Python function to unscramble Bob's scrambled text.
  • Jim posts a 156 character Python function to unscramble Bob's scrambled text. He also posts a 91 character GolfScript function to unscramble Fred's scrambled text.

The scores:

  • Bob scores 165 - 150 = 15
  • Fred scores 59 - 82 = -23
  • Joe scores 180 - 175 = 5
  • Jim scores 163 - 0 = 163

so Fred wins.

Miscellaneous

I suggest that the closing date be two weeks after the challenge begins, and that unscramblers be posted to part one within 48 hours of closing date in order to be eligible.

||||||
\$\endgroup\$
  • \$\begingroup\$ Are there any rules regarding scrambling? i.e. is "Stockholm"->"Stockhoml" a valid scramble? (it may not matter, but I'm curious. And to be clear, the scoring is the difference between your opponent's unscrambler length and your own for the same language? \$\endgroup\$ – Gaffi Jul 16 '12 at 16:39
  • \$\begingroup\$ @Gaffi No, you scramble however you want. If you want to just output the text as given that's ok, but you probably won't win with that strategy. The aim is to do it in a way that is easy for you to unscramble but difficult for all the others. That way your score will be smaller. Yes, the score is the difference between your score and the score of the best of your opponents' attempts. I'll add an example to make that bit clearer I think. \$\endgroup\$ – Gareth Jul 16 '12 at 21:27
  • \$\begingroup\$ I think this gives an advantage to people who use (relatively) obscure languages. If the scrambler is written in J and the descrambler in GolfScript then only people who know both can realistically attempt a descrambler. (NB the rules don't say how the score works if no-one attempts a particular unscrambler). \$\endgroup\$ – Peter Taylor Jul 17 '12 at 6:59
  • \$\begingroup\$ I did consider saying that programs that had no attempts at beating them were not eligible to win, but then I thought that if they were scored as though the shortest attempt to beat them was 0 then they wouldn't have much of an advantage. I'll add that into the example scoring. What do you think? I want to encourage answers that are clever or well obfuscated rather than written in Malbolge or something like that. \$\endgroup\$ – Gareth Jul 17 '12 at 7:28
  • 1
    \$\begingroup\$ Does it mean that since no one attempts to solve Jim's Ruby challenge his chances are minimal that he'll win? That would discourage complicated scramblers or difficult languages. \$\endgroup\$ – Howard Jul 17 '12 at 17:12
  • \$\begingroup\$ @Howard As it stands, yes that's how it would work. The alternative, as Peter Taylor points out, is that people using obscure languages have an advantage. I'm not sure how else I might score unscramblers that no-one has attempted to beat. Maybe give them a score of 0? Please, if you or anyone else has any suggestions for making the challenge as inclusive as possible, let me know. \$\endgroup\$ – Gareth Jul 17 '12 at 17:51
  • \$\begingroup\$ Can we delete this because the sandbox lags so much and this hasn't been touched in 5 years? \$\endgroup\$ – programmer5000 Apr 13 '17 at 17:37
1
\$\begingroup\$

Compile BF to TM

Your task is to write a compiler accepting a Brainfuck program (previous challenge: Interpret Brainfuck, wikipedia: Brainfuck) as input and outputting a Turing Machine which produces identical output when supplied with the same (correct) input.

You may select the output format from among the various formats accepted by the answers to Turing Machine Simulator.

The following links may also be useful.
An introduction to programming in BF
BF is Turing-complete
Programming a Turing Machine
Programming Praxis: Turing Machine Simulator

Equivalently, you may write a Brainfuck interpreter in TM, or any partial compilation/interpretation which results in a TM program as described above.

If we consider squares of the TM tape to represent bits (blank=0, mark=1) of the BF memory, then eight squares represent a cell. Each BF instruction translates to a minimum of 8 states of the Turing Machine.

'>' "advance" (++ptr) could be implemented by eight states (sixteen transitions):

adv8 _ adv7 R _
adv8 1 adv7 R 1
adv7 _ adv6 R _
adv7 1 adv6 R 1
adv6 _ adv5 R _
adv6 1 adv5 R 1
adv5 _ adv4 R _
adv5 1 adv4 R 1
adv4 _ adv3 R _
adv4 1 adv3 R 1
adv3 _ adv2 R _
adv3 1 adv2 R 1
adv2 _ adv1 R _
adv2 1 adv1 R 1
adv1 _ link R _
adv1 1 link R 1

where 'link' represents the first state of the following instruction.

'<' "rewind" (--ptr) can be implemented similarly by making leftward movements and rewriting the same symbol just read.

'+' "increment" (++*ptr) can be implemented by a ripple-carry from the Least Significant Bit to the Most Significant Bit, borrowing "rewind" states to back-up to normal position. If the LSB is on the left, it would look something like this:

inc8 _ link N 1
inc8 1 inc7 R _
inc7 _ rew1 N 1
inc7 1 inc6 R _
inc6 _ rew2 N 1
inc6 1 inc5 R _
inc5 _ rew3 N 1
inc5 1 inc4 R _
inc4 _ rew4 N 1
inc4 1 inc3 R _
inc3 _ rew5 N 1
inc3 1 inc2 R _
inc2 _ rew6 N 1
inc2 1 inc1 R _
inc1 _ rew7 N 1
inc1 1 overflow N 1

where overflow is a HALT state.

For I/O, the simplest way I can think is to place all input on the tape after the memory area, and expand the alphabet to include a symbol indicating the dividing line between the memory portion and the input portion of the tape. In fact, by expanding the cell size to nine squares, this symbol can serve as an input pointer, advancing as the input is consumed. (So "advance" and "rewind" now need 9 states each.) And another new symbol is written in front of the current memory cell to serve as the memory pointer. Inputting a byte therefore consists of schleping each bit over the entire space between the two tape positions with something like this:

input _ set-memptr L _
input 1 set-memptr L 1
set-memptr _ find-inptr R *
find-inptr _ find-inptr R _
find-inptr 1 find-inptr R 1
find-inptr $ schlep-bit R $
schlep-bit _ schlep-blank L _
schlep-bit 1 schlep-one L 1
schlep-blank $ schlep-blank L $
schlep-blank _ schlep-blank L _
schlep-blank 1 schlep-blank L 1
schlep-blank * deposit-blank R *
schlep-one $ schlep-one L $
schlep-one _ schlep-one L _
schlep-one 1 schlep-one L 1
schlep-one * deposit-one R *
deposit-blank _ etc R _
deposit-blank 1 etc R _
deposit-one _ etc R 1
deposit-one 1 etc R 1

where "etc" represents going to get the next bit in similar fashion.

To perform a loop (all BF loops are "while" loops, so the exit control is at the beginning and the end has a simple goto back to the beginning), we need first to check is the current cell is zero,

zero8 _ zero7 R _
zero8 1 body R 1
zero7 _ zero6 R _
zero7 1 left1 L 1
zero6 _ zero5 R _
zero6 1 left2 L 1
zero5 _ zero4 R _
zero5 1 left3 L 1
zero4 _ zero3 R _
zero4 1 left4 L 1
zero3 _ zero2 R _
zero3 1 left5 L 1
zero2 _ zero1 R _
zero2 1 left6 L 1
zero1 _ exit-loop R _
zero1 1 left7 L 1
left7 _ left6 L _
left7 1 left6 L 1
left6 _ left5 L _
left6 1 left5 L 1
left5 _ left4 L _
left5 1 left4 L 1
left4 _ left3 L _
left4 1 left3 L 1
left4 _ left3 L _
left4 1 left3 L 1
left3 _ left2 L _
left3 1 left2 L 1
left2 _ left1 L _
left2 1 left1 L 1
left2 _ loop-body L _
left2 1 loop-body L 1
...
loop-body-final _ zero8 N _
loop-body-final 1 zero8 N 1

So assuming the machine starts at tape-location 0, and the input is on the tape starting at 0 and going to the right, the "startup code" for this arrangement would be

startup _ place$ L _
startup 1 place$ L 1
place$ _ left270000 L $
left270000 _ left269999 L _
...

Jeez! The output is going to be HUGE! It might be better to treat the BF memory as negative-indexed and reverse all the _L_s and _R_s in 'advance', 'rewind', 'increment', and 'decrement'.


Questions:

Bonuses for optimizations? If I can implement this myself and provide a complete example output, The bonus could be "subtract the difference between your program's output for the example input with the example output". So eliminating states would be far more valuable than shrinking the code. One could possibly achieve a negative score!


Edit: Actually I think this is unreasonable unless the Turing Machine is augmented with non-reading (movement-only or epsilon) transitions. Duplicating every letter of the alphabet just to move over one square is just ridiculously painful. That means this challenge won't link-up nicely with the other one. :(

What about, instead of implementing the compiler, just devise a translation scheme (as above) that leads to a smaller output for a trivial sample program (based on calculating, rather than coding)? "Back of the envelope" compiler.

||||||
\$\endgroup\$
  • \$\begingroup\$ "How much detail on BF do I need to supply? Can I simply reference the BF question?" A link to almost any site that describes the language will do. \$\endgroup\$ – dmckee --- ex-moderator kitten Nov 5 '12 at 16:52
  • \$\begingroup\$ Winning condition? \$\endgroup\$ – Peter Taylor Nov 6 '12 at 13:43
  • \$\begingroup\$ "Longest prefix containing syntactically-correct Malbolge!" :) ... I'd say have none at all. Perhaps the questioner should be required to accept their own example answer? \$\endgroup\$ – luser droog Nov 6 '12 at 18:08
  • \$\begingroup\$ @PeterTaylor Apologies for my last comment. I thought we were on my other answer about the [fun] tag. . . . This one would be a golf: shortest code by character count. But I think a clever system of bonuses could make it interesting. \$\endgroup\$ – luser droog Nov 7 '12 at 10:06
  • \$\begingroup\$ The "Equivalently, you may write a Brainfuck interpreter in TM" option doesn't play very well with being a code golf - how are you going to count the length of the TM? \$\endgroup\$ – Peter Taylor Nov 7 '12 at 11:15
  • \$\begingroup\$ @PeterTaylor Since the TM question specified 5-tuples, I think it's sufficient to count the tuples (== transitions). You can reduce states by increasing the alphabet (or vice versa), but the transitions would remain constant, I think. \$\endgroup\$ – luser droog Nov 8 '12 at 5:25
  • \$\begingroup\$ Can we delete this because the sandbox lags so much and this hasn't been touched in 5 years? \$\endgroup\$ – programmer5000 Apr 13 '17 at 17:42
  • \$\begingroup\$ I'd like to adopt (work on and post) this challenge if you don't want to. Would I be able to? If you do not respond to this message within two weeks, by community guidelines, I am allowed to take it over. \$\endgroup\$ – MD XF Aug 18 '17 at 3:23
  • \$\begingroup\$ Yes, please. If you can do something with it, strike while the iron is hot. \$\endgroup\$ – luser droog Aug 18 '17 at 4:19
1
\$\begingroup\$

Polygon prefixes

Polygons are named after the number of sides that they have. A pentagon has 5 sides, an octagon has 8 sides. But how are they named? What's the name for a 248-sided polygon?

All polygons are suffixed with -gon. There are specific prefixes for each polygon depending on the number of sides. Here are the prefixes for the lower numbers:

3 - tri
4 - tetra
5 - penta
6 - hexa
7 - hepta
8 - octa
9 - nona
10 - deca
11 - undeca
12 - dodeca
13 - triskaideca
14 - tetradeca
15 - pentadeca
16 - hexadeca
17 - heptadeca
18 - octadeca
19 - nonadeca
20 - icosa

Polygons with 21 to 99 sides have a different system. Take the prefix for the tens digit (found on the left column), the ones digit (right column below), and then stick a "kai" between them to get (tens)(ones)gon.

20 - icosi       | 1 - hena
30 - triaconta   | 2 - di
40 - tetraconta  | 3 - tri
50 - pentaconta  | 4 - tetra
60 - hexaconta   | 5 - penta
70 - heptaconta  | 6 - hexa
80 - octaconta   | 7 - hepta
90 - nonaconta   | 8 - octa
                 | 9 - nona

The 3-digit sided polygons are named in a similar fashion. A 100-sided polygon is called a hectogon. Take the hundreds digit, find it on the column for ones digits, then stick a "hecta" to its right. Now number off the tens and ones like above: (hundreds)hecta(tens)(ones)gon. If the hundreds place digit is a 1, don't put the prefix behind "hecta".

So, given an integer (3 <= n <= 999), return the name of an n-sided polygon. n-gon is not a valid answer :P

As with all code golf, shortest code wins.


Is the description good? Would it be harder if I instead asked for the number of sides, given a name?

||||||
\$\endgroup\$
  • 1
    \$\begingroup\$ What is a 101-sided figure called? "hectahenagon"? Is "hena" from the column for ones digits you mention? If so, then what is a 111-sided figure called? I'd say "hectaundecagon", but then that comes from a column where "hena" is not present. \$\endgroup\$ – Gaffi Feb 11 '13 at 11:15
  • \$\begingroup\$ @Gaffi: Yep, it's hectahenagon, from what Google says. \$\endgroup\$ – beary605 Feb 11 '13 at 16:03
  • \$\begingroup\$ Can we delete this because the sandbox lags so much and this hasn't been touched in 4 years? \$\endgroup\$ – programmer5000 Apr 13 '17 at 17:43
  • \$\begingroup\$ I am going to take this if you allow me or if you don't respond \$\endgroup\$ – Christopher May 30 '17 at 1:13
1
\$\begingroup\$

Self-Golfing Code?

I don't know if I just didn't search hard enough, but I couldn't find any challenge regarding self-golfing code, or rather, any code that can deterministically reduce another set of text code to a much smaller program, yet still compile/run.

For example, take this:

int main() {
std::cout<<"Hello world 1!"<<std::endl;
std::cout<<"Hello world 2!"<<std::endl;
std::cout<<"Hello world 3!"<<std::endl;
std::cout<<"Hello world 4!"<<std::endl;
std::cout<<"Hello world 5!"<<std::endl;
}

And output this (as one possible solution):

#define A std::cout<<"Hello world 
#define B !"<<std::endl;
#define C B A
int main() {
A 1 C 2 C 3 C 4 C 5 B
}

Alternative:

Sub MySub()
Dim aNumber As Integer
Dim someString As String
aNumber = 123
someString = "abc"
MsgBox aNumber
MsgBox someString
End Sub

into (again, as one possible solution)

Sub m()
Dim a As Integer
Dim s As String
a = 123
s = "abc"
MsgBox a
MsgBox s
End Sub

Do we have a challenge for this?

If not, here are some rules I envision:

  • Golfing code need not be in the same language as code to be golfed.
  • Since compilers/running of code varies, newly golfed code must still run under same environment.
  • Possible challenge scoring (multiple options -- thinking code golf):
    • 1: Shortest golfing code wins (not my favorite, since you can minimally shorten the base code, yet still write the shortest program).
    • 2: Shortest output of a set of pre-defined code (potentially limiting if participants are unfamiliar with the options available)
    • 3: Combination of length of golfing code and the output result of the same as input. (Ratio, summation, etc.) -- This I think is my preferred option.
    • 4: Multi-player Ratio of golfed size of other participants' own code versus their original submission. (Similar limitations to that of point #2.)
||||||
\$\endgroup\$
  • 1
    \$\begingroup\$ Sounds more like an auto-golfer than obfuscation. Seems like it would be very hard to make it a fair contest unless you pick a language to golf, and even then it had better be a simple language (no platform dependency issues or compiler options). \$\endgroup\$ – Peter Taylor Feb 13 '13 at 15:15
  • \$\begingroup\$ @PeterTaylor My examples are golfing, but either would work. Perhaps golfing would be simpler, then? I agree that the options for usable languages makes this a bit messy... Would one challenge per language be acceptable? (i.e. aligned with most challenges that are language-agnostic) \$\endgroup\$ – Gaffi Feb 13 '13 at 17:36
  • 2
    \$\begingroup\$ Language-agnostic to mean means that you can write a program to do it in any language. Since the language to be golfed can be different from the submitted program, I don't see any incompatibility between making the problem "Write a program to golf Piet" and being language-agnostic. \$\endgroup\$ – Peter Taylor Feb 15 '13 at 0:18
  • \$\begingroup\$ @PeterTaylor So then you see no problem with one question per language on which to operate? Are there any proposed scoring algorithms you particularly like/dislike? \$\endgroup\$ – Gaffi Feb 15 '13 at 12:02
  • \$\begingroup\$ That depends on what you mean. If you're planning to post 10 questions at once, yes, that would be a problem. But I don't see a problem with posting a well-defined "Auto-golf Piet" and following it up two months later with "Auto-golf Perl 5". \$\endgroup\$ – Peter Taylor Feb 16 '13 at 10:19
  • \$\begingroup\$ Scoring is an issue. The halting problem means that it's impossible to write an optimal solution, so the scoring must take into account how good the solution is. I think option 3 is the best, and you'll want a big test set (maybe a few kB taken from a real-world open source project) with coverage of the language features. \$\endgroup\$ – Peter Taylor Feb 16 '13 at 10:22
  • \$\begingroup\$ Can we delete this because the sandbox lags so much and this hasn't been touched in 4 years? \$\endgroup\$ – programmer5000 Apr 13 '17 at 17:43
  • \$\begingroup\$ Btw, your first example doesn't work. You can't have unmatched quotes in preprocessor directives. Don't know why. \$\endgroup\$ – MD XF Jan 13 '18 at 18:03
  • \$\begingroup\$ I honestly think this would be fine if you did something like solely maco-golfing, making it somewhat language agnostic because of gcc -E. \$\endgroup\$ – Zacharý Nov 10 '18 at 14:36
1
\$\begingroup\$

Missile Command

I'm making this CW, because it needs lots of help. I've been toying with this idea for a while. Think "battleship" to get in the right mind-frame. But, instead of ships, what you lay down are tiles which represent a Befunge-style program. This program controls the behavior of guided missiles ejected from the spawn tile. The goal is to program a missile which will obliterate an opponent's program block, as well as guard its own control block.

Haven't nailed-down the board size. 20x20 seems a little cramped.

         1         2
12345678901234567890
____________________1  4x20 program block
____________________2
____________________3
_______@____________4
....................5  12x20 arena
....................6
....................7
....................8
....................9
....................01
....................1
....................2
....................3
....................4
....................5
....................6
___________@________7  4x20 program block
____________________8
____________________9
____________________02

Tiles

@ spawn

Program control.

I'm imagining these to change direction of the code for "boustrophedon" writing.

this,then\
 txen,siht

haven't thought it all though, yet.

/

\

Movement.

F forward move forward one square

B back move back one square

L left turn left 90°

R right turn right 90°

So the submissions would be 4x20 code blocks which compete in a king-of-the-hill style.

||||||
\$\endgroup\$
  • \$\begingroup\$ If this is deterministic, won't it be "Last person to submit their program wins"? \$\endgroup\$ – Peter Taylor Jun 7 '13 at 8:39
  • \$\begingroup\$ That is a danger, yes. I'm hoping ways around it can be found. There could be a random operator. And proximity detection, or something. \$\endgroup\$ – luser droog Jun 7 '13 at 8:46
1
\$\begingroup\$

Find all of the Scrabble numbers:

A scrabble number is a number n whose scrabble representation can score n points. As an example consider 12: its English spelling twelve has value 12 when it is placed on a stretch of six blank tiles. Since the highest ever reported 1 word scrabble score barely exceeds 2000 points, that will be the upperbound for this challenge.

Score and quantities for English:

2 blanks |  x1  |  x2  |  x3  |  x4  |  x6  |  x8  |  x9  |  x12 |
    1    |      |      |      | LSU  | NRT  | O    | AI   | E    |
    2    |      |      | G    | D    |      |      |      |      |
    3    |      | BCMP |      |      |      |      |      |      |
    4    |      | FHVWY|      |      |      |      |      |      |
    5    | K    |      |      |      |      |      |      |      |
    8    | JX   |      |      |      |      |      |      |      |
   10    | QZ   |      |      |      |      |      |      |      |

Considerations for either bonus points to scoring or extra requirements:

  • Respect the board, only using gaps between double/triple letter and double/triple word scores that occur on a standard scrabble board.
  • Respect the tile count for each letter.
  • There are non-English versions of scrabble, maybe it should be 'language-agnostic' (lol, but seriously is there a reason to accept only English submissions?).
  • Should the 2 blanks be allowed?
||||||
\$\endgroup\$
  • \$\begingroup\$ What about tiles which were already on the board and so wouldn't score anything? As for language: one approach would be to make it take the names of the tiles (and perhaps the values and counts of the letters) as input; this would also prevent the problem from being effectively one of Kolmogorov complexity. \$\endgroup\$ – Peter Taylor Jun 19 '13 at 22:50
  • \$\begingroup\$ I don't believe that tiles on the board already would pose an issue. If you assume that the board may be prepared with any subset of the tiles beforehand (some may be impossible, but checking that is out of scope) all that is relevant to the problem is which are placed to complete the word. All the tiles points are counted, even the earlier placed, but only the new 7 (or less) tiles may qualify for triple/double-word/letter scores. w.r.t. kolmogorov, If I wanted to make it programming challenge instead of codegolf (so that isn't an issue) then there needs to be a scoring system right? \$\endgroup\$ – Kaya Jun 19 '13 at 23:33
  • \$\begingroup\$ Yes, if it isn't codegolf then it needs a scoring system. I'm not sure what you could use as an alternative scoring criterion, though: it's simple enough logic that pretty much any implementation would be IO-bound, so speed doesn't work; and big-O based tends to be less straightforward than you might think. \$\endgroup\$ – Peter Taylor Jun 21 '13 at 11:05
1
\$\begingroup\$

Sort all lines according to their corresponding Levenshtein Distance to the first line.

Shamelessly borrowed from: http://golf.shinh.org/p.rb?Levenshtein+Distance+Sort+FIXED

For a definition of the Levenshtein Distance, look here: http://en.wikipedia.org/wiki/Levenshtein_algorithm

Rules:

Takes input from stdin. Must work for all possible input. Get points for:

Smallest character count. Using Languages that are difficult to golf in. I think character count / the average values from here (http://golf.shinh.org/lranking.rb) might suffice?

||||||
\$\endgroup\$
  • \$\begingroup\$ There are a number of ambiguities in the problem description. What is the correct behaviour if the input is empty? In the general case, should the first line be included in the lines which are sorted and output? Should the sort be by ascending or descending edit distance? How should ties be broken? \$\endgroup\$ – Peter Taylor Jun 25 '13 at 20:23
  • \$\begingroup\$ As for handicapping: are you going to prohibit built-in or library-provided edit distance functions? If not then the averages you link are not especially relevant: PHP handily wins the existing edit distance question by virtue of its built-in function. \$\endgroup\$ – Peter Taylor Jun 25 '13 at 20:27
  • \$\begingroup\$ (That existing question does also raise the possibility of yours being closed for not being sufficiently different). \$\endgroup\$ – Peter Taylor Jun 25 '13 at 20:28
1
\$\begingroup\$

Fastest Code: checking if interval pairs overlap

Given an unsorted input of many interval pairs (50+), write the fastest algorithm to determine if they do not overlap.

An interval pair is said to overlap if interval x and interval y are overlapping.

Example input 1:
interval x , interval y

10-25, 50-60
10-15, 25-60

Output:
Can be in any true false format.

false (They overlap)

reasoning:

a.x overlaps b.x
a.y overlaps b.y

Example input 2:

10-25, 50-60
20-30, 25-30

Output:

true (they do not overlap)

reasoning:

a.x overlaps b.x
a.y does not overlap b.y

Scoring:

[not sure...]
brute force gives a worst case n^2 runtime
||||||
\$\endgroup\$
  • 1
    \$\begingroup\$ It's hard to understand what the program is supposed to do. It's better to give three separate self-contained test cases than to mix them together with extra identifiers which won't be in the actual input. But if I understand correctly, there's nothing difficult here at all. It's just interval overlap testing (two ifs) done twice for no obvious reason. \$\endgroup\$ – Peter Taylor Jul 5 '13 at 19:45
  • \$\begingroup\$ The problem is that there will be a very large input. I'm thinking > 50 lines. \$\endgroup\$ – EAKAE Jul 5 '13 at 20:50
  • \$\begingroup\$ I'm not sure whether or not to score it based on time, or worst case runtime. \$\endgroup\$ – EAKAE Jul 5 '13 at 20:59
  • 1
    \$\begingroup\$ Instead of asking for overlap, ask for disjoint: "Check if a family of intervals is disjoint". I also think it would be more interesting if you give intervals in interval notation but I you should at least specify whether or not the endpoints are included. \$\endgroup\$ – Justin Dec 21 '13 at 7:41
1
\$\begingroup\$

Countdown: Federal Holidays in the United States

Inspired by this question:

Christmas Countdown

Write a program or script that will countdown to the nearest U.S. federal holiday, at any given time, and will switch the display to an appropriate greeting during each holiday.

The following holidays must be tracked, and announced:

Holiday                         Date                    Greeting
==========================================================================================
New Year's Day                  Jan. 1                  Happy New Year!
Martin Luther King, Jr. Day     3rd Mon. in Jan.        Happy Martin Luther King, Jr. Day!
President's Day                 3rd Mon. in Feb.        Happy President's Day!
Memorial Day                    Last Mon. in May        Happy Memorial Day!
Independence Day                Jul. 4                  Happy Independence Day!
Labor Day                       First Mon. in Sept.     Happy Labor Day!
Columbus Day                    2nd Mon. in Oct.        Happy Columbus Day!
Veterans Day                    Nov. 11                 Happy Veterans Day!
Thanksgiving                    4th Thu. in Nov.        Happy Thanksgiving!
Christmas                       Dec. 25                 Merry Christmas!

The strings listed under "Holiday" and "Greeting" are all free. Shortcuts like "Merry X-mas!" or "Happy 4th of July" will count against you - the full and proper holiday names are free, so there's no good reason not to use them.

The following strings are also free, only when used as a label for time units or in advertising the next upcoming holiday:

days
hours
minutes
seconds
milliseconds
until
time

On any given non-holiday, the program must show a count-down timer which displays time remaining at least down to the second, and updates the display with an accurate value (according to the system clock) at least once per second. Time remaining until a holiday must be counted as the time until midnight (00:00:00) on that day.

How the days, hours, minutes, and seconds (and milliseconds, if you choose) are displayed is up to you, so long as all mandatory items are present and it is clear which numbers represent which value. Again, the strings defining units of time are free so there's no really good reason not to use them. (Though you won't be penalized for not using these strings, so long as it is still unambiguous which time units are which.) The program should also make apparent which holiday is being counted down towards.

On any given holiday, the program must cease displaying the countdown timer and instead display the appropriate greeting for that holiday from 00:00:00 until 23:59:59.

After a holiday is over, at 00:00:00 the next day, the holiday greeting must go away and be replaced with the countdown timer for the next holiday.

Answers must include:

  • Name of language
  • Score (length of golfed code, minus free characters)
  • Golfed code
  • Total length of golfed code
  • Total number of free characters used
  • Un-golfed code, with descriptive comments

The program must be capable of running accurately (according to the system clock) at any time, and must be able to run indefinitely. The only limitations to this should be those imposed by the host computer or the nature of the programming language.


Are there any additions/deletions/modifications that should be made to these rules?

I'm considering changing some of the greetings, but I'm not quite sure what to.

  • "Happy Martin Luther King, Jr. Day!" is just a mouthful and feels awkward, but shortening it to "Happy MLK Day" feels weird too - any other suggestions?
  • I'm not quite sure "Memorial Day" should really be preceded by "Happy" - thoughts?
  • Any others?
||||||
\$\endgroup\$
  • \$\begingroup\$ I think it would be more interesting if the strings were not free, but you still required exact match. I would like to see the compression scheme used by contestants. \$\endgroup\$ – John Dvorak Dec 7 '13 at 12:04
  • \$\begingroup\$ @JanDvorak This is meant to be code-golf, not kolmogorov-complexity. \$\endgroup\$ – Iszi Dec 7 '13 at 22:11
  • \$\begingroup\$ This challenge proposal has been inactive for over a month. I would like to take ownership of the challenge and make it ready for posting. Please let me know within the next 14 days if you have any objections and would still like to finish and post this challenge yourself. \$\endgroup\$ – user10766 Nov 3 '14 at 2:01
1
\$\begingroup\$

Quine with syntax highlighting


I don't really have much of an idea how to properly pose a quine challenge, or what the common syntax highlighting rules are (or aren't) for various languages. So, I figured I'd just toss this concept up here for consideration and let the community flesh it out if they think it's a good idea.

||||||
\$\endgroup\$
  • \$\begingroup\$ I'm pretty sure some languages don't even have syntax to highlight \$\endgroup\$ – John Dvorak Dec 13 '13 at 20:12
  • \$\begingroup\$ @JanDvorak Perhaps this would not quite be an "all languages" challenge, then - only languages which naturally lend themselves to syntax highlighting would be eligible. \$\endgroup\$ – Iszi Dec 13 '13 at 20:19
  • \$\begingroup\$ You also can't use a language that cannot render any decent GUI. Also, specifying the amount of syntax highlighting the program needs to generate will be hell. \$\endgroup\$ – John Dvorak Dec 13 '13 at 20:36
  • \$\begingroup\$ I don't think this question is feasible, due to the output restrictions and due to the difficulty in defining the minimum required syntax highlighting. \$\endgroup\$ – John Dvorak Dec 13 '13 at 21:09
  • \$\begingroup\$ I like this idea. I think you could specify an adequate level of highlighting with just keywords, strings or characters and numeric literals each having their own color. \$\endgroup\$ – Οurous Feb 28 '18 at 21:13
1
\$\begingroup\$

McDonald's Drive-Thru

Changes from original:

  • Provided some clarification of requirements with regards to impossible ordering quantities.
  • Added specification to include total cost of order.
  • Added specification to prefer lowest cost in case of a tie for number of packages.

TODO:

  • Verify package sizes and pricing to be used for this challenge.
  • Add pricing to output samples.
  • Edit or remove "not have any limitations" rule. As currently written, it may force otherwise unnecessary bloating of code in some languages. (e.g.: PowerShell can handle numbers as uint64 to work with extremely large quantities, but it defaults to int32.)

We want to write a program to help McDonald's Drive-Thru employees assist their customers in ordering Chicken McNuggets. Chicken McNuggets only come in packs of 4, 6, 9, or 20. However, customers may not always be considering this when they pull up to the speaker.

For example, a customer might want to order 50 McNuggets but they really don't care what sort of packaging they come in - they just want to make sure they get 50 McNuggets one way or another. We want to help the customers get the best value out of their order - that is, to compose an order large enough to accommodate their needs in as few packages as possible with little to no excess.

Users will provide a request for n Chicken McNuggets. Your program's task is to provide the user with the sizes and numbers of McNugget packages needed to fulfill the order exactly. If the exact order cannot be fulfilled, the system must output an order which would meet the customer's needs with as little excess as possible. The system must also provide the total cost of the order.

Rules

  • For values of n which can be ordered exactly, output how many of each pack must be ordered to achieve the requested quantity.
  • For impossible orders (1,2,3,5,7,11), print "[requested quantity] is impossible. Have [nearest valid quantity >n]:" followed by the normal output for the nearest possible quantity >n.
  • Impossible orders cannot be hard-coded. The program must be able to determine whether fulfilling an order exactly is possible without being explicitly told that 1,2,3,5,7, and 11 are impossible.
  • Output must exclude any package sizes which do not need to be ordered.
  • Output must be in descending order of package size.
  • Output must include the sum total cost of all the packages. (Tax not included.)
  • Further layout and formatting of the output is up to you, so long as it is unambiguous.
  • Program must not have any limitations beyond those inherent to the system or programming language.
  • If there are multiple ways to assemble the order in the least number of packages, output the method which has the lowest total price.

Examples:

Input: 8
Output:

2x4

Input: 43
Output:

1x20 1x9 1x6 2x4

Input: 11
Output:

11 is impossible. Have 12: 2x6

Relevant Numberphile Link


My main concern is that this problem may be too similar to this thread:

Work out change

Otherwise, are there any changes that should be made to this?

||||||
\$\endgroup\$
  • 2
    \$\begingroup\$ My recommendation is to minimize the total cost of the order, rather than the number of packages. Based on these prices: fastfoodmenuprices.com/mcdonalds-prices, the costs are $2.99, $3.89, $4.29, and $5.00. This website lists the "9 piece" as "10 piece", I think that might be an error. \$\endgroup\$ – PhiNotPi Dec 14 '13 at 0:01
  • \$\begingroup\$ Why the restriction #3? \$\endgroup\$ – John Dvorak Dec 14 '13 at 6:12
  • \$\begingroup\$ I agree that it's too similar to the existing question. In addition, "nearest valid quantity" isn't unique, and you don't give any hint as to how to break ties. \$\endgroup\$ – Peter Taylor Dec 14 '13 at 10:17
  • 1
    \$\begingroup\$ @PeterTaylor Tiebreaker is specified as ">n", where "n" is the quantity requested by the user - that is, we want to give the user an option that will have at least as many nuggets as they want to order. \$\endgroup\$ – Iszi Dec 14 '13 at 23:37
  • \$\begingroup\$ @JanDvorak Essentially, to up the difficulty a notch. I figure it's a little trickier to catch the invalid quantities in the process of figuring out the answer if you can't write a simple if statement to match against the known quantities. \$\endgroup\$ – Iszi Dec 14 '13 at 23:42
  • \$\begingroup\$ @PhiNotPi Not sure if that's an error on the site, or a regional difference. The information I posted was based on the linked Numberphile video, which was made in the U.K.. It's also possible they may have changed the menu since then. Presuming that larger packages hold better value in terms of cost-per-nugget than smaller ones, the problem as stated should work itself out to the same goal as you've suggested. However, it might help to differentiate the challenge from the suggested duplicate if we add the total price into the expected output. \$\endgroup\$ – Iszi Dec 14 '13 at 23:45
  • \$\begingroup\$ My question is: how are you going to measure that? How large part of this knowledge are we disallowed from encoding? Can we memorize all but one? Can we special-case 1,2,3? Or, is it that anything goes as long as it either can be generalised to other Frobenius problems, or is inclusive, not exclusive? \$\endgroup\$ – John Dvorak Dec 14 '13 at 23:47
  • \$\begingroup\$ @JanDvorak The program should be able to work out for itself whether or not a given quantity is invalid - that's all there is to it. By its nature, I suppose that means solutions would be able to also handle other Frobenius problems. In fact, I was actually considering a separate "return the largest impossible quantity" problem, where users input several integers and the program outputs the largest quantity that cannot be achieved by adding multiples of those integers. \$\endgroup\$ – Iszi Dec 14 '13 at 23:53
  • \$\begingroup\$ Provided some updates to address comments. \$\endgroup\$ – Iszi Dec 15 '13 at 2:34
  • \$\begingroup\$ @Iszi Minimizing cost should serve as a tiebreaker for when there are multiple solutions with the minimum packaging. For example, look at N=36. The solution {0*4,0*6,4*9,0*20} works, but {1*4,2*6,0*9,1*20} is cheaper. (I used the costs {{4,2.99},{6,3.89},{9,4.29},{20,5.00}}) \$\endgroup\$ – PhiNotPi Dec 15 '13 at 3:07
  • \$\begingroup\$ @PhiNotPi Ah, I think I misunderstood when Peter said there wasn't a specifier for the tiebreaker. For some reason, I was thinking it was not possible for there to be a tie of that sort. Adding the price aspect definitely helps sort that out, then. Thanks. \$\endgroup\$ – Iszi Dec 15 '13 at 3:15
  • \$\begingroup\$ FWIW, it was my misreading. I failed to see the ">n". \$\endgroup\$ – Peter Taylor Dec 21 '13 at 12:01
1
21 22
23
24 25
92

You must log in to answer this question.

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