485
\$\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\$

2929 Answers 2929

1
48 49
50
51 52
98
1
\$\begingroup\$
| |
\$\endgroup\$
  • \$\begingroup\$ Comment: while this problem is solvable in polynomial time, I guess the code-golf submissions are going to take exponential time. \$\endgroup\$ – user202729 Jul 16 at 6:40
  • \$\begingroup\$ @user202729 Do you actually have a polynomial tome algorithm? \$\endgroup\$ – Ad Hoc Garf Hunter Jul 16 at 12:23
  • \$\begingroup\$ Yes. -- -- -- -- -- -- \$\endgroup\$ – user202729 Jul 16 at 13:29
  • \$\begingroup\$ @user202729 What is it? \$\endgroup\$ – Ad Hoc Garf Hunter Jul 16 at 13:34
  • \$\begingroup\$ Iterate over substrings of the string, then check if it satisfies with f(left, right, prefix) = (can eraser[:prefix] be formed from string[left:right] by repeated erase operations?) At most this is O(n^6). \$\endgroup\$ – user202729 Jul 16 at 13:38
  • \$\begingroup\$ I cannot understand your notation so I do not understand your algorithm, but I will say it seems to me that checking whether an eraser erases a string should naïvely take O(2^n) since in strings like "ototoo" it matters which "oto" you erase first thus you have to branch between the possible choices. \$\endgroup\$ – Ad Hoc Garf Hunter Jul 16 at 14:22
  • \$\begingroup\$ The notation is like Python, string[left:right] is character from left..right (inclusive), eraser[:prefix] is eraser[0:prefix]`, characters are 0-indexed. \$\endgroup\$ – user202729 Jul 16 at 14:32
  • \$\begingroup\$ It's possible to compute each f(left, right, prefix) value from O(n) other values (dynamic programming) and there's only O(n^3) possible parameters. \$\endgroup\$ – user202729 Jul 16 at 14:33
  • \$\begingroup\$ @user202729 Ok, It looked like python but it didn't make any sense as python code, might you actually write this in python? It still doesn't make a whole lot of sense and even then feels like it should be O(2^n) because of "can [...] be formed from [...] by repeated erase operations?" seems to be an O(2^n) check to me. \$\endgroup\$ – Ad Hoc Garf Hunter Jul 16 at 14:37
  • \$\begingroup\$ f=lambda left, right, prefix: string[left:right]==eraser[:prefix] or (left!=right and (string[right-1]==eraser[prefix-1] and f(left, right-1, prefix-1) or f(left, right, len(eraser) or any(f(left, middle, prefix) and f(middle, right, 0) for middle in range(left+1, right)))), something like that, with caching. \$\endgroup\$ – user202729 Jul 16 at 14:42
  • \$\begingroup\$ Looks like this problem (or a similar one) has already appeared somewhere else. See codeforces.com/blog/entry/14090 \$\endgroup\$ – user202729 Jul 16 at 14:46
  • \$\begingroup\$ @user202729 Ok so I've spent a little while unpacking that algoirthm in the blog post and it seems to be O(2^n) unless there is some invariant I am missing. I will say I still do not have the slightest understanding of your algorithm. \$\endgroup\$ – Ad Hoc Garf Hunter Jul 16 at 15:22
  • \$\begingroup\$ About the blog: if you understood it then there is no way it can be 2^n because there are only n^2 different states (possible parameter values) of the dp function . \$\endgroup\$ – user202729 Jul 17 at 2:44
  • \$\begingroup\$ @user202729 The issue is that calculating a cell is not contsant time sometimes we are required to solve the entire problem again on a smaller string to fill in a cell. You can make schemes where the number of these cells is linear witht he size of the program, hence exponential time overall. however at this point I have found a dynamic programming algo that does this in O(n^4), so it doesn't matter much to me any more. \$\endgroup\$ – Ad Hoc Garf Hunter Jul 17 at 3:23
1
\$\begingroup\$

Ant Storage Labyrinth

Description

Using a simplified model, the place where ants store their food can be thought of as an \$n\times n\$ matrix. Each entry of the matrix is an integer that encodes how full that specific spot is, according to the following correspondence:

  • 0 denotes an empty spot (the ants can add two more units of food),
  • 1 denotes a half-filled spot (the ants can add one more unit of food),
  • 2 denotes a filled spot (no more food can be stored in there).

Imagine an ant carrying \$f\$ units of food, that enters the "storage room" at a specific position (row \$i\$, column \$j\$ of the matrix). The ant can move one unit left, right, up or down with each step, and it can drop \$2-q\$ units of food at each spot it walks over (where \$q\$ is the initial capacity of that spot – either 0, 1 or 2 as described above). Your task is to find the length of the shortest path the ant can choose in order to store all \$f\$ units of food.

Example

Let's say that the ant carries \$4\$ units and enters the following storage room (\$6\times 6\$ matrix) at position \$(3,3)\$ (1-indexed):

$$\left[\begin{matrix}0&2&2&2&2&2\\2&1&2&2&2&1\\1&2&\color{red}{1}&2&1&1\\2&1&2&2&2&2\\2&2&2&2&2&2\\1&2&2&1&2&2\\\end{matrix}\right]$$

It drops \$1\$ unit right where it starts (\$3\$ left), then it has four optimal choices:

  • 3 moves to the right, and 1 up,

    $$\longrightarrow\left[\begin{matrix}0&2&2&2&2&2\\2&1&2&2&2&1\\1&2&\color{green}{2}&\color{red}{2}&1&1\\2&1&2&2&2&2\\2&2&2&2&2&2\\1&2&2&1&2&2\\\end{matrix}\right]\longrightarrow\left[\begin{matrix}0&2&2&2&2&2\\2&1&2&2&2&1\\1&2&\color{green}{2}&\color{green}{2}&\color{red}{1}&1\\2&1&2&2&2&2\\2&2&2&2&2&2\\1&2&2&1&2&2\\\end{matrix}\right]\longrightarrow\left[\begin{matrix}0&2&2&2&2&2\\2&1&2&2&2&1\\1&2&\color{green}{2}&\color{green}{2}&\color{green}{2}&\color{red}{1}\\2&1&2&2&2&2\\2&2&2&2&2&2\\1&2&2&1&2&2\\\end{matrix}\right]\\\longrightarrow\left[\begin{matrix}0&2&2&2&2&2\\2&1&2&2&2&\color{red}{1}\\1&2&\color{green}{2}&\color{green}{2}&\color{green}{2}&\color{green}{2}\\2&1&2&2&2&2\\2&2&2&2&2&2\\1&2&2&1&2&2\\\end{matrix}\right]\longrightarrow\left[\begin{matrix}0&2&2&2&2&2\\2&1&2&2&2&\color{green}{2}\\1&2&\color{green}{2}&\color{green}{2}&\color{green}{2}&\color{green}{2}\\2&1&2&2&2&2\\2&2&2&2&2&2\\1&2&2&1&2&2\\\end{matrix}\right]$$

  • 2 moves to the left, and 2 up,

  • 1 move up, 2 left, and one up,

  • 1 move up, 1 left, 1 up, 1 left.

All of these require \$4\$ steps, so the final answer is \$\boxed{4}\$.

Test cases

In progress. I need help coming up with interesting test cases / maybe a verification program.

| |
\$\endgroup\$
1
\$\begingroup\$
                    Question Posted
                    Question Posted
                          
| |
\$\endgroup\$
  • \$\begingroup\$ So what's the scoring citeria? \$\endgroup\$ – HighlyRadioactive Jul 18 at 23:57
  • \$\begingroup\$ @HighlyRadioactive The maximum string length found between the RNA representation of MN908947.3 and the DNA or RNA representation of some other non-coronavirus organism. Or the maximum length multiplied by three of the maximum string found in common between the representation of a protein of MN908947.3 and that of a living non-coronavirus organism. \$\endgroup\$ – user58988 Jul 19 at 2:36
  • \$\begingroup\$ Then a random brute-force solution would win as long as it's acturate. \$\endgroup\$ – HighlyRadioactive Jul 19 at 2:41
  • \$\begingroup\$ Or is this not a code-challenge, but a programming puzzle? \$\endgroup\$ – HighlyRadioactive Jul 19 at 2:41
  • \$\begingroup\$ Yes possible is a programming puzzle, code is only for find string equal ... but strings are long and the algo seems to me at last O(n^2) \$\endgroup\$ – user58988 Jul 19 at 3:13
  • 1
    \$\begingroup\$ Code Golf Stack Exchange is a site for recreational programming competitions, not general programming questions. Challenges must have an objective scoring criterion, and it is highly recommended to first post proposed challenges in the Sandbox. \$\endgroup\$ – HighlyRadioactive Jul 19 at 3:15
  • \$\begingroup\$ Obiective score exist, i explain it above for the remain free of downvote that \$\endgroup\$ – user58988 Jul 19 at 3:21
  • \$\begingroup\$ What program would win then? \$\endgroup\$ – HighlyRadioactive Jul 19 at 3:22
  • \$\begingroup\$ The winner is the one who finds in GenBak the genetic code or a protein of a being that is not a coronavirus (but it can be a virus), that has L genomic lenght as calculate above for genome or for proteine, more big respect to sarscov19 virus (the one name MN908947.3 in GenBank) ). \$\endgroup\$ – user58988 Jul 19 at 3:23
  • \$\begingroup\$ How would multiple programs compete? \$\endgroup\$ – HighlyRadioactive Jul 19 at 3:25
1
\$\begingroup\$

The ASCII character countdown!

Your task is simple: Choose any printable ASCII character that's not chosen in the previous answers. And then, you need to print your chosen character in your program to standard output. (You can ONLY print your chosen character, without printing other garbage to STDOUT)

The catch

Let's say you picked x as your chosen character, and your answer is the answer numbered y. You have to insert y x's into the previous source code, at any position you like. For the first answer, the previous answer is the empty program.

An example

Answers have to start with the number 1. So for example, I chose the character #, and I posted a 1 byte answer in /// that prints the # mark.

#

And then, the second answer (numbered 2) has to insert 2 of their picked x character into the previous source code, such that the modified code will print their x character. So assume this is written in Keg:

x#x

And then, the third answer has to do the same, and so on, until 95 is reached.

The winning criterion & other rules

  • The first user whose answer stays without a succeeding answer for a month wins the challenge. If that's not satisfied, the first person who reaches the number 95 wins the challenge.
  • You are not allowed to put any other character in your code other than printable ASCII characters.
  • You need to wait for an hour before posting a chaining answer.
  • You need to wait 2 answers before you post a new answer after your submission.
  • Please make sure your answer is valid. If yours is not valid, chaining answers aren't allowed to be posted.
  • The answers are allowed to be in different languages.
  • Each submission doesn't have to be in a unique language.
  • You could only insert y x's into the source code.
| |
\$\endgroup\$
  • \$\begingroup\$ Can the answers be in different langauges? \$\endgroup\$ – fireflame241 Jul 20 at 4:03
  • 1
    \$\begingroup\$ What is the motivation for the number 95? \$\endgroup\$ – fireflame241 Jul 20 at 4:03
  • \$\begingroup\$ This isn't a radiation hardening challenge, as those require programs to still work / do something different if any single character is removed. \$\endgroup\$ – Lyxal Jul 21 at 9:15
  • 1
    \$\begingroup\$ @fireflame241 Because there are 95 ASCII characters of course... \$\endgroup\$ – user202729 Jul 21 at 12:50
  • \$\begingroup\$ Must we only insert y xs, or may we also insert other (printable ASCII) characters apart from our chosen character? If the latter, are the additional characters limited to those not already used in previous answers? \$\endgroup\$ – Dingus Jul 21 at 15:02
  • \$\begingroup\$ "I chose the character ?" -> "I chose the character #"? \$\endgroup\$ – user202729 Jul 22 at 6:10
  • \$\begingroup\$ "has to insert their picked x character into the previous source code," -> edit this part too. \$\endgroup\$ – user202729 Jul 22 at 6:11
  • \$\begingroup\$ @Dingus Now you may only insert y xs. \$\endgroup\$ – user92069 Jul 23 at 0:56
  • 1
    \$\begingroup\$ "I chose the character ?" has crept back in. Other than that it's clear now. (Seems difficult too, but maybe not in the golfing langs - I don't know.) \$\endgroup\$ – Dingus Jul 23 at 2:18
1
\$\begingroup\$

Error Once, Hello World Twice

Your task here is to write a Hello World program that, (no, this is not Do X Without Y!) contains two exact copies of the same string. to avoid trivial solutions like print "Hello World!"# your program must error out with only one copy.

This is code-golf, so shortest answer in bytes wins.

Sandbox

  • Wording?
  • Tags?
  • Length?
  • Interesting enough to be posted?
| |
\$\endgroup\$
  • \$\begingroup\$ I double the source code, you print hello world? (I'm not saying this is a dupe, I'm asking if that accurately summaries the challenge.) \$\endgroup\$ – Lyxal Jul 25 at 11:28
  • \$\begingroup\$ @Lyxal Yep. (15chars) \$\endgroup\$ – HighlyRadioactive Jul 25 at 12:04
  • \$\begingroup\$ What if, rather than erroring out with one copy, make it so that it's valid if it prints out anything other than "Hello world"? \$\endgroup\$ – Beefster Jul 30 at 16:40
  • \$\begingroup\$ @Beefster Maybe... But that's probably not what I'm intending. I might consider later. \$\endgroup\$ – HighlyRadioactive Jul 31 at 10:25
  • \$\begingroup\$ @HighlyRadioactive this also reminds me of my 2 cats in a quine challenge from a while ago. My main concern here is that "erroring out" is nebulous and different for every language. You could also make it so that the program must print nothing unless it's duplicated. \$\endgroup\$ – Beefster Jul 31 at 16:13
1
\$\begingroup\$

Successive operator sequences

A successive operator sequence (made up terminology) is a sequence of the form \$a(n + 1) = a(n) \text{ op } n\$ where op cycles through a set of operators and \$a(n)\$ represents the \$n\$th term of the sequence.

For examples, if we set the operators to addition, multiplication and subtraction and \$a(1) = 1\$. then we will get the following sequence (which is also A047908):

a(1)                    = 1
a(2) = a(1) + 1 = 1 + 1 = 2
a(3) = a(2) * 2 = 2 * 2 = 4
a(4) = a(3) - 3 = 4 - 3 = 1
a(5) = a(4) + 4 = 1 + 4 = 5
a(6) = a(5) * 5 = 5 * 5 = 25

Task

Write a program/function to output the \$n\$th term of a successive operator sequence given its initial term and operators.

Operators your program/function must support:

  • multiplication
  • addition
  • subtraction
  • integer division (rounded towards negative infinity)

Input Format

The operators are inputted as a string or array of character where each character represents an operator, you may choose your own mapping of character to operator.

Scoring

This is so shortest bytes wins.

Testcases

# first term, operators, n  ->  nth term
0,   ["+", "-", "*", "/"], 6   ->  4
1,   ["+", "*", "-"],      1   ->  1
1,   ["+", "*", "-"],      3   ->  4
1,   ["+", "*", "-"],      10  ->  199
1,   ["*", "+", "-"],      7   ->  -1
50,  ["*", "+", "-"],      1   ->  50
50,  ["*", "+", "-"],      4   ->  49
-10, ["*", "/", "-"],      5   ->  -32
-10, ["*", "/", "-"],      3   ->  -5
1,   ["+", "+", "*"],      5   ->  16
2,   ["+", "*"],           5   ->  36
0,   ["+"],                3   ->  3

Inspired by the sequence A047908

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Suggested test cases: only one operation; duplicate operations (like ["+","+","-"]); more than 4 operations. Also, should integer division round toward zero, toward negative infinity, or something else? \$\endgroup\$ – Zgarb Jul 18 at 19:10
  • \$\begingroup\$ Does each string have to be one byte? \$\endgroup\$ – fireflame241 Jul 19 at 19:26
  • \$\begingroup\$ @fireflame, they have to be a single character not a single byte. \$\endgroup\$ – Mukundan314 Jul 20 at 15:23
  • \$\begingroup\$ Why rounding division towards negative infinity? A lot of languages round integer division towards zero and this will add complexity just to do that. Notice that A047908 doesn't use division at all so why add it and make it a problem? Maybe even make it optional which way your answer does it as long as it's stated. \$\endgroup\$ – Noodle9 Jul 27 at 17:59
1
\$\begingroup\$

CoGo Rally

There's a game called Robo Rally, in which players "program" their robots five moves ahead, then simultaneously perform the moves, one at a time. The robots move over a "factory floor" grid, with the aim being to reach certain points on the board, in sequence, before the other robots do the same.

Game Rules

For the purposes of this challenge, the rules will be simplified as follows:

  • Each robot starts with 6 lives
  • Each robot has a different, randomly assigned starting position (out of a fixed set of starting positions)
  • The aim of the game is to reach all three checkpoints in the assigned order, before any other robot does the same.

Movement Options

Each turn, your robot can make any one of the following movements:

  • Rotate Clockwise 90 degrees
  • Rotate Counter-clockwise 90 degrees
  • Rotate 180 degrees
  • Move Forward One
  • Move Forward Two
  • Move Forward Three [can only be used once until the next checkpoint is met]
  • Reverse One (and stay facing the same way)
  • Stay Still and gain 1 life, up to the maximum of 6

Your moves are pre-programmed in blocks of five, so choose carefully! The board may well be in a very different state in five moves time to what you think it will be.

Additionally, each movement is assigned a priority from 1-100. When you choose your block of five movements (you may use each movement any number of times, except the "move forward three", to form your five total movements) and the order they will occur in, you are also given five random numbers 1-100 to assign - one to each movement. Higher numbers will take priority where movements would cause two robots to enter the same space, for example.

Board Items

The board contains the following items:

  • Floor - the default tile on the board. No special effect.
  • Walls - block a robot's path. If a robot moves forward or backward into a wall, it wastes that move (i.e. stays still, but doesn't gain a life). If the robot used "Move Forward Two", for example, it may be possible that the Robot can only move Forward One, and then stops infront of a wall, wasting the second part of the movement.
  • Laser gun - fire in a straight line in a specific direction until they hit a wall or a robot. If a robot is ontop of a laser gun, it will be hit but the laser won't fire further. While moving forward two or three, a robot may pass over the path of a laser gun without being affected by it.
  • Conveyor Belts - at the end of a turn (single movement option), a conveyor belt will move the robot one space in the direction the conveyor is pointing. Doesn't block lasers. Conveyor belts NEVER ROTATE ROBOTS, even if they move the robot in a different direction to the one it is facing. While moving forward two or three, a robot may move over a conveyor belt without being affected by it.
  • Checkpoints (1,2,3) - act as a save point on the Robot's path and also heals all of a robot's lives and resets their use of the "Move Forward Three" action, the first time the checkpoint is visited. Checkpoints must be visited sequentially to be activated. Acts as a piece of floor in all other respects. Robots must END THEIR TURN ON THE CHECKPOINT, after interaction with other Robots; and not just pass over it.
  • Holes - move the robot back to the previously visited checkpoint, or start position. Robot loses half its remaining life, rounded down. Holes act immediately, as soon as the robot enters the space - it doesn't wait for the "board interactions" part of the turn order.

Interactions

Objects interact as follows:

  • If a Robot moves into a space where another robot already exists, the other robot is shoved (moved) in the direction that the first robot was moving, one space; unless there is a wall or laser in the way. This effect may stack if multiple robots are in a line (i.e. all robots are shoved one space). This may cause a robot to fall into a hole or onto a conveyor belt.
  • Moving off the edge of the board has the same effect as moving into a hole
  • If a Laser fires and hits a robot, the robot stops the laser beam, and takes one damage.
  • If a robot is facing another robot in a straight line with nothing blocking in between (i.e. no walls or other robots), the target robot takes 1 damage
    • Therefore If two robots are facing towards each other with nothing blocking in between (i.e. no walls or other robots), both robots take one damage.

Turn Order

  1. determine (program) 5 movement options
  2. determine Priorities (1-100) for these five turns
  3. The programmed actions occur:
    a. The first movement occurs for each player, in priority order from highest to lowest. Holes are acted on immediately (a robot cannot pass over a hole).
    b. Robot Interactions are resolved (e.g. if one robot shoves another one)
    c. Board Items act (lasers, conveyor belts, checkpoints)
    i. If a robot loses all of its lives, it returns to the previous checkpoint (or start) with half lives (rounded up) and must sit out the remainder of the round d. Robots fire
    i. If a robot loses all of its lives, it returns to the previous checkpoint (or start) with half lives (rounded up) and must sit out the remainder of the round e. Repeat for the remaining 4 movements
  4. Repeat until one robot has reached all three checkpoints sequentially, or all robots have lost their lives

The Challenge

Your robot must take the board (as a 2D array), and a seed for the Random number generator; and play the game on the given board.

The board is guaranteed to be solveable (there will always be a path from the start to each of the checkpoints)

Sample Board

enter image description here

enter image description here

The above board would be represented in an array as follows:

[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,LU,0,0,0,0,0]
[0,0,0,0,0,LL,2,LR,0,0,W,0]
[H,CL,CL,CL,CL,CL,CL,CL,CL,CL,0,0]
[0,0,0,0,0,CR,CR,CR,CR,CR,CR,H]
[0,W,0,0,0,0,0 ,0,0,0,0,0]
[0,W,0,0,0,0,W,0,W,0,0,0]
[1,W,0,0,0,0,CR,CR,CD,0,W,3]
[0,W,CR,CR,CR,0,CU,H,CD,W,0,0]
[0,LL,CR,CR,CR,CR,CU,CU,CL,0,0,0]
[0,0,S,S,S,S,0,0,W,0,0,0]

Where

Cx = Conveyor (x=Up, Down, Left, Right)
Lx = Laser gun (x=Up, Down, Left, Right)
S = Start
1,2,3 = Checkpoints
W = Wall
H = Hole
0 = Floor

Sandbox Questions

Should this be , where you implement your robot in the least code possible; or , or something else? If KotH, I've never set one before so some advice would be appreciated!

| |
\$\endgroup\$
  • \$\begingroup\$ (if this is code golf) is it guaranteed that there exists a solution on every boards? Or only boards such that a solution exists are valid input? \$\endgroup\$ – user202729 Jul 28 at 10:38
  • \$\begingroup\$ Whether KotH or codegolf, the board will always be solvable (i.e. In all cases all of the checkpoints will be accessible, and there will be at least one path from any starting point to each of the checkpoints) \$\endgroup\$ – simonalexander2005 Jul 28 at 10:40
1
\$\begingroup\$

Posted: Legendre's (Unsolved) Conjecture

| |
\$\endgroup\$
  • \$\begingroup\$ I did post such a challenge once which was well-received, though with language restriction. But posing an unsolved problem as a challenge directly is always risky as you already wrote. Also, a challenge being "simplistic" isn't a problem by itself, but involving prime numbers might be a problem, as it gives very little room for golfing in most languages (either requiring trial division boilerplate or having a built-in). \$\endgroup\$ – Bubbler Jul 28 at 4:20
  • \$\begingroup\$ Regarding the last point -- yes, there was similar challenges before -- and if it stays unsolved for long-enough you can assume that it won't be proven while people are still interested in the challenge. And if someone, while trying to solve the challenge, manages to prove the conjecture then it is good. \$\endgroup\$ – user202729 Jul 28 at 10:41
  • \$\begingroup\$ No, not KC. -- -- \$\endgroup\$ – user202729 Jul 28 at 10:42
1
\$\begingroup\$

Paper folding. Posted HERE

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

The Dungeon Number Sequence

Introduction

The dungeon numbers are introduced by Numberphile, denoting a chain of base conversions. A dungeon number is denoted in the form $$a_{b_{c_{d_\cdots}}}$$ where all numbers involved are integers with at least two digits. When interpreting the values, each base conversion \$a_b\$ is treated as from base \$b\$ to base-10.

There are two types of dungeons, one starting from \$10\$ to \$n\$ from top to bottom, i.e. $$10_{11_{12_{\cdots_n}}}$$ increasing \$1\$ for each deeper layer, and one starting from \$n\$ to \$10\$ from top to bottom, i.e. $$n_{(n-1)_{(n-2)_{\cdots_{10}}}}$$ decreasing \$1\$ for each deeper layer. Each dungeon has two interpretations, top down, i.e. $$(((10_{11})_{12})_\cdots)_n$$, and bottom up, i.e. $$10_{(11_{(12_{(\cdots_n)})})}$$, producing 4 dungeon number sequences in total.

Example

Considering $$10_{(11_{(12_{13})})}$$. The conversion is bottom up. First \$12_{13}\$ is converted to \$15_{10}\$. Then \$11_{15}\$ is converted to \$16_{10}\$. Finally \$10_{16}\$ is converted to \$16_{10}\$, and this is the value for \$n=13\$.

Challenge

Write a program or function, given an integer \$n>=10\$ as input, output either the value of the dungeon number sequence at \$n\$, or the whole sequence from \$10\$ up to \$n\$ inclusive. You may choose any sequence from the 4 sequences, but you must state which you have chosen. You must not hardcode the values; your code must work theoretically for all integer \$n>=10\$.

Values

n                                  10  11  12  13  14  15  16  17   18   19    20
---------------------------------------------------------------------------------
Type 1 (((10_11)_12)_...)_n        10  11  13  16  20  30  48  76  132  420  1640
Type 2 10_(11_(12_(..._n)))        10  11  13  16  20  25  31  38   46   55    65
Type 3 (((n_(n-1))_(n-2))_...)_10  10  11  13  16  20  28  45  73  133  348  4943
Type 4 n_((n-1)_((n-2)_(..._10)))  10  11  13  16  20  25  31  38   46   55   110

Sample IO

  • Type 1 (\$(((10_{11})_{12})_\cdots)_n\$)

    15 => 30
    20 => 1640
    25 => 19563802363305
    
  • Type 2 (\$10_{(11_{(12_{(\cdots_n)})})}\$)

    15 => 25
    20 => 65
    25 => 943
    
  • Type 3 (\$(((n_{(n-1)})_{(n-2)})_\cdots)_{10}\$)

    15 => 28
    20 => 4943
    25 => 1092759075796059
    
  • Type 4 (\$n_{((n-1)_{((n-2)_{(\cdots_{10})})})}\$)

    15 => 25
    20 => 110
    25 => 3577
    

Winning Criteria

This is a challenge, so shortest code for each language wins. No default loopholes.

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

Where are the traps?

Related: Trapped Knight Sequence The Path Of The Wildebeest

Background Partially copied from my related challenge

The trapped knight sequence is a finite integer sequence of length 2016, starting from 1, and has the following construction rules:

  1. Write a number spiral in the following manner:
17 16 15 14 13 ...
18  5  4  3 12 ...
19  6  1  2 11 ...
20  7  8  9 10 ...
21 22 23 24 25 ...
  1. Place a knight on 1.
  2. Move the knight to the grid with the smallest number it can go that has not been visited before, according to the rules of chess (i.e. 2 units vertically and 1 unit horizontally, or vice versa).
  3. Repeat until the knight gets stuck.

It is known that the sequence ends at 2084 where the knight is trapped. But here is a twist. Suppose a knight can step back to the previous grid whenever it is stuck, and choose the grid with the next smallest number possible. By doing so, the sequence can be further extended until it is stuck again at 2720. Then, the knight steps back and choose another path, which further extends the sequence until it is stuck again at 3325...

Then, we call these numbers at which the knight is being trapped "traps". So we now know that the first few traps are at 2084, 2720, 3325, ... and it continues to infinity.

Challenge

Write a shortest program or function, receiving an integer \$N\$ as input, output the first \$N\$ traps in the extended trapped knight sequence.

Values

The first 100 terms of the sequence are as follows.

  2084,   2720,   3325,   3753,   7776,   5632,   7411,   8562,  14076,   8469, 
  9231,  22702,  14661,  21710,  21078,  25809,  27112,  24708,  19844,  26943,
 26737,  32449,  31366,  45036,  37853,  37188,  43318,  62095,  67401,  68736,
 70848,  62789,  63223,  69245,  85385,  52467,  71072,  68435,  76611,  84206,
 81869,  70277,  81475,  83776,  70767,  84763,  99029,  82609, 103815,  86102,
 93729, 100614, 108039,  82111,  99935,  85283, 109993, 119856, 119518, 116066, 
109686,  92741, 124770,  92378, 104657, 125102, 107267, 107246, 117089, 117766,
 99295, 121575,  98930, 117390, 123583, 112565, 122080, 111612, 111597,  97349,
105002, 130602, 133509, 153410, 127138, 143952, 153326, 157774, 122534, 136542,
163038, 134778, 140186, 162865, 171044, 159637, 171041, 174368, 184225, 152988

Winning Criteria

The shortest code of each language wins. Restrictions on standard loopholes apply.

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

Posted: Antisymmetry of a Matrix

| |
\$\endgroup\$
  • \$\begingroup\$ Mathematica: AntisymmetricMatrixQ (of course, a non-built-in solution can be much shorter). \$\endgroup\$ – my pronoun is monicareinstate Jul 30 at 13:12
1
\$\begingroup\$

Identify the tonic from a key signature

Objective

Given a key signature in major, output its tonic.

Input

An integer from -14 to +14, inclusive. Its absolute value is the numbers of flats/sharps. Negative number represents flats, and positive number represents sharps. Note that theoretical keys are also considered.

Mapping

Note the use of Unicode characters ♭(U+266D; music flat sign), ♯(U+266F; music sharp sign), 𝄪(U+1D12A; musical symbol double sharp), and 𝄫(U+1D12B; musical symbol double flat).

-14 → C𝄫
-13 → G𝄫
-12 → D𝄫
-11 → A𝄫
-10 → E𝄫
-9 → B𝄫
-8 → F♭
-7 → C♭
-6 → G♭
-5 → D♭
-4 → A♭
-3 → E♭
-2 → B♭
-1 → F
0 → C
1 → G
2 → D
3 → A
4 → E
5 → B
6 → F♯
7 → C♯
8 → G♯
9 → D♯
10 → A♯
11 → E♯
12 → B♯
13 → F𝄪
14 → C𝄪

Output must be a string. Whitespaces are permitted everywhere.

Rule

  • Invalid inputs fall in don't care situation.
| |
\$\endgroup\$
  • \$\begingroup\$ "Or a sequence of bytes representing a string in some existing encoding"? (I think this should be the default, but I don't remember seeing any meta post about it) \$\endgroup\$ – user202729 Aug 4 at 6:06
1
\$\begingroup\$

Surround a string with "friendliness pellets"

Input a String and surround it with a ellipse of alternating "friendliness pellets"(0)

Idea originally from Lyxal.

Challenge

Given a single line String of length \$<100\$, print the string with an ellipse of alternating pellets(0) around it. The ellipse must be 11 lines in height.

The first line of the ellipse must have at least 1 pellet.

The middle line of the ellipse must be at least 13 characters long. There must be a padding of one space on each side of the text.

Strings smaller than 9 characters must be padded with spaces equally on both sides to fit the above specification. The right side is allowed to have one extra space if the string is of even length.

The template for the ellipse is as follows:

      00000..... 6 spaces
    0 4 spaces 
  0   2 spaces
 0    1 space
0     no spaces

If the string's length is greater than or equal to 9; the first line must have \$\text{length}-8\$ pellets.

Example Input and Output

Input:

Hello World!

Output:

       0000  
     0      0  
   0          0
  0            0
 0              0
 0 Hello World! 0
 0              0
  0            0
   0          0
     0      0
       0000

Input

0

Output

       0
     0   0  
   0       0
  0         0
 0           0
 0     0     0
 0           0
  0         0
   0       0
     0   0
       0

Input

The quick brown fox

Output

       00000000000 
     0             0  
   0                 0
  0                   0
 0                     0
 0 the quick brown fox 0
 0                     0
  0                   0
   0                 0
     0             0
       00000000000

Input

In this world, it's KILL or BE killed

Output

      00000000000000000000000000000
    0                               0
  0                                   0
 0                                     0
0                                       0
0 In this world, it's KILL or BE killed 0
0                                       0
 0                                     0
  0                                   0
    0                               0
      00000000000000000000000000000

Input

hi there

Output

      0
    0   0
  0       0
 0         0
0           0
0 hi there  0
0           0
 0         0
  0       0
    0   0
      0

Example code

a=[4,2,1,0] # space length to create circle

str=gets.chomp;
l = str.length;
# print first line of pellets
print " "*6
if l<=9 then puts "0" else puts "0"*(l-8) end
    
# initial pattern
for n in a do 
    print " "*n +"0"+" "*(5-n)
    print " " if l<=9
    print " "*(l-8) if l>9
    puts " "*(5-n) +"0"

end
    
# display string with spaces
if l<9 then puts "0"+" "*((11-l)/2).floor + str + " "*((12-l)/2).ceil + "0" else puts "0 #{str} 0" end

#initial pattern but reversed
for n in a.reverse do 
    print " "*n +"0"+" "*(5-n)
    print " " if l<=9
    print " "*(l-8) if l>9
    puts " "*(5-n) +"0"
end
    
# last line(same as first line)
print " "*6
if l<=9 then puts "0" else puts "0"*(l-8) end


| |
\$\endgroup\$
  • \$\begingroup\$ Suggested test case: In this world, it's KILL or BE killed. Also, a reference program would be a good addition. \$\endgroup\$ – Lyxal Aug 5 at 9:11
  • \$\begingroup\$ Done! hysterical Flowey laughter \$\endgroup\$ – Razetime Aug 5 at 10:54
  • \$\begingroup\$ Setting a maximum number of characters would be unambiguous, rather than 'length lesser than your console's width'. \$\endgroup\$ – Dingus Aug 5 at 10:57
  • \$\begingroup\$ I made the threshold to be lesser than 100. \$\endgroup\$ – Razetime Aug 5 at 11:01
  • \$\begingroup\$ This is exactly how I imagined the challenge would look like. Good job! I look forward to seeing you post it when it's time to do so! \$\endgroup\$ – Lyxal Aug 5 at 11:01
  • 1
    \$\begingroup\$ The specific rules that define the ellipses should be described explicitly, not inferred from either the test cases or the example code. For instance, it appears that all ellipses are expected to be 11 lines high, but this is nowhere stated. \$\endgroup\$ – Dingus Aug 5 at 11:23
  • \$\begingroup\$ Ok, I fixed that in the question. \$\endgroup\$ – Razetime Aug 5 at 11:25
  • \$\begingroup\$ (not a problem with the challenge, just a general comment) The circle looks ugly... (you can change the challenge to be "draw an ASCII art of a you circle surrounding something -- with some circle-drawing algorithm or specification -- but I think there's already some similar challenge? Besides, the current version is easier) \$\endgroup\$ – user202729 Aug 5 at 11:38
  • \$\begingroup\$ I'm not sure whether one exists. Bresenham's Algorithm geeksforgeeks.org/bresenhams-circle-drawing-algorithm exists, but I feel like that would be a very different type of question. \$\endgroup\$ – Razetime Aug 5 at 11:45
  • \$\begingroup\$ The ellipse spec is still not detailed enough. It looks like you have set spacing rules for each line - what are they? Is it allowed to make the ellipse wider than the minimum size needed to contain the string? \$\endgroup\$ – Dingus Aug 5 at 13:09
  • 1
    \$\begingroup\$ I added an ellipse template, annd padding rules. \$\endgroup\$ – Razetime Aug 6 at 2:12
  • \$\begingroup\$ Related/dupe. \$\endgroup\$ – Dingus Aug 7 at 12:35
  • \$\begingroup\$ Yes, very close, but not exactly the same. \$\endgroup\$ – Razetime Aug 9 at 4:52
  • \$\begingroup\$ Sure, the specific shapes/characters are different. But the underlying challenge of surrounding a string with an ASCII shape (a horizontally and vertically symmetric one, at that) is the same. \$\endgroup\$ – Dingus Aug 9 at 23:37
1
\$\begingroup\$

Non-ASCII Hello World

Inspired by this post

Background

Usually, people accuse modern golfing languages for looking like Unicode line noise. Some of them ban all unicode characters in the submissions' source code in their challenges, in order to allow only practical languages to appear among their submissions.

Let's do the other way around: We'll ban all printable ASCII characters and only allow unicode to appear in the source code (which very effectively bans all practical languages, since I'm a practical language hater).

Task

Your task is basically outputting Hello, World!, but none of the printable ASCII characters may appear in your source code.

Rules

  • By printable ASCII, I mean all characters with the codepoints in the range of [32, 127].

  • Tabs (or the char with the codepoint 8, depending on your language's codepage) and newlines (or the char with the codepoint 10, depending on your language's codepage) don't count as printable, therefore they may appear in the source code.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ This does seem to kill the hopes of a few esolangs as well. \$\endgroup\$ – Razetime Aug 9 at 4:51
1
\$\begingroup\$

LaTeX Fractions

Inspired by a TeX SE question.

LaTeX uses \frac{a}{b} to represent a/b, which is very unintuitive. Now you have a piece of paper (as in "research paper") which happens to use the a/b format, and your task is to convert it to the LaTeX format.

[to be continued]

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ @RahulVerma Nested fractions? \$\endgroup\$ – HighlyRadioactive Aug 10 at 13:17
1
\$\begingroup\$

Posted: Poker for Two

Posted on main here.

| |
\$\endgroup\$
  • \$\begingroup\$ or would it be better for my controller to follow poker etiquette by not revealing any card that isn't in a showdown?: When I've played poker (albeit digitally) the winner has the choice whether they show or hide their cards. That way, people can show if they were serious about their hand or hide the fact they bluffed. Allowing this system would also potentially add another interesting aspect to the challenge: do I reveal my "hand" or not. \$\endgroup\$ – Lyxal Aug 3 at 7:17
  • \$\begingroup\$ Also, I recommend you deal with replacement - that's how usual poker works: the deck is shuffled after each round. \$\endgroup\$ – Lyxal Aug 3 at 7:19
  • \$\begingroup\$ This game has no draws, so why shuffle after each round? That practically nullifies the effect of "no replacement" and has the bad effect of quantising the game to c possibilities for each bot's card. If you want each round's cards returned to the pack to be shuffled for the next round, you might as well deal floats in the range 0.0 to 1.0. (Or ints 0...c-1 with a very large c.) \$\endgroup\$ – Rosie F Aug 4 at 6:19
  • \$\begingroup\$ @Lyxal It seems to me that, if a player were allowed to reveal or not reveal their card, "not revealing" dominates "revealing", so nobody would choose to reveal, so I might as well just not reveal, and save everyone the bother of indicating their choice. Any objections? \$\endgroup\$ – Rosie F Aug 4 at 6:22
1
\$\begingroup\$

De-interleave log lines

You've inherited a server that runs several apps which all output to the same log.

Your task is to de-interleave the lines of the log file by source. Fortunately, each line begins with a tag that indicates which app it is from.

Logs

Each line will look something like this:

[app_name] Something horrible happened!

App tags are always between square brackets and will contain only alphanumeric characters and underscores. All lines will have an app tag and the app tag will always be the first thing on the line.

Example

An entire log might look like this:

[weather] Current temp: 83F
[barkeep] Fish enters bar
[barkeep] Fish orders beer
[stockmarket] PI +3.14
[barkeep] Fish leaves bar
[weather] 40% chance of rain detected

Which should output three different logs:

[weather] Current temp: 83F
[weather] 40% chance of rain detected
[barkeep] Fish enters bar
[barkeep] Fish orders beer
[barkeep] Fish leaves bar
[stockmarket] PI +3.14

You are not given the names of the app tags ahead of time. You must determine them only by analyzing the log file.

Rules and Scoring

  • This is , so shortest code wins.
  • Standard rules and loopholes apply
  • Use any convenient IO format, provided that each line is represented as a string, not a parsed tag + message.

| |
\$\endgroup\$
0
\$\begingroup\$

Write a compiler/interpreter for ...

Inspired by the lisp challenge here.
It is a series of puzzles.

I don't like to see a simple eval solution, so:

  • interpreting the language is fine
  • translating the language to a different language is fine.

I think this is specific for each language.

Only the syntax and the basic commands.
Also specific.

Winning criteria should not be code golf.
The goal should be that you can "learn" an other language by looking at the code.

Languages that might be good candidates:

  • Lisp
  • APL
  • J
  • Brainfuck (already posted)
  • Whitespace
  • Forth
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ This only works for languages which are small and well defined. BF fits those criteria. Whitespace does too. The others may not. Lisp and Forth have so many dialects that you would have to specify exactly which dialect to support; Lisp, Forth, APL and J might have too many built-ins to fit in an answer: there are character limits. \$\endgroup\$ – Peter Taylor May 12 '13 at 15:16
  • \$\begingroup\$ You don't have to provide all the built-ins, but that is why it is here. \$\endgroup\$ – Johannes Kuhn May 12 '13 at 15:38
  • \$\begingroup\$ What defines the "basic commands"? \$\endgroup\$ – ASCIIThenANSI Aug 31 '15 at 17:54
  • \$\begingroup\$ I don't know? Maybe that you can do the basic stuff with it like +,-,print,... \$\endgroup\$ – Johannes Kuhn Aug 31 '15 at 18:22
  • 1
    \$\begingroup\$ I suggest a programmer can implement the tiniest subset of those languages in order to be Turing-complete, as these are non-trivial subsets that can theoretically simulate the rest of the language... \$\endgroup\$ – user85052 Jun 28 '19 at 4:17
  • \$\begingroup\$ Which human is learning the programming language by looking at the code? \$\endgroup\$ – MilkyWay90 Aug 26 '19 at 3:23
0
\$\begingroup\$

Find Maximum number of 4+ letter words from Scabble Tiles

The challenge is to find the most words with 4 or more letters you can make with one set of scrabble tiles.

The tile distribution is as follows:

2 Blank Tiles
A 9  N 6    +====+===========+
B 2  O 8    | 01 | K J X Q Z |
C 2  P 2    | 02 | B C M P F |
D 4  Q 1    | 02 | H V W Y * |
E 12 R 6    | 03 | G         |
F 2  S 4    | 04 | L S U D   |
G 3  T 6    | 06 | N R T     |
H 2  U 4    | 08 | O         |
I 9  V 2    | 09 | A I       |
J 1  W 2    | 12 | E         |
K 1  X 1    +====+===========+
L 4  Y 2
M 2  Z 1

Valid words are any words that are 4+ that are available in this file, the official scrabble dictionary.

Tiles cannot be used twice. This means you can only have 1 word with a K, J, X, Q, and/or Z unless you use a blank tile to represent one of these letters.

I'm not sure how I'd do scoring on this. I want shorter code to score better, but I don't want a short piece of code that finds a lot less words to score better than a longer piece that finds many more words.

| |
\$\endgroup\$
  • \$\begingroup\$ Meh. I don't like dependency on external files; are we allowed to load it, or even embed it into the source code? \$\endgroup\$ – John Dvorak Dec 17 '13 at 20:00
  • \$\begingroup\$ as for finding more vs. shorter code, you could demand all words be found \$\endgroup\$ – John Dvorak Dec 17 '13 at 20:19
  • \$\begingroup\$ @JanDvorak Any way to use it. It's a text version of the official scrabble dictionary, it seemed to be the most fitting word list for the task. "All words being found" might be hard, considering there are probably many combinations of words that would deplete all the tiles. It's a maximum of 25 words, (25 words, 4 letters each, 100 tiles), but I don't know if it's possible to use all tiles with just 4 letter words. After so many words, you might not have enough tiles to make an actual word, which means you'd either have to go back or accept that you're not using all the tiles. \$\endgroup\$ – Rob Dec 17 '13 at 20:23
  • 5
    \$\begingroup\$ As currently described, this is a no-input task, which means that the answer can be precomputed and then the program only needs to decompress it. Consider rewriting it to take input (either of the word list or of the tiles available). \$\endgroup\$ – Peter Taylor Dec 18 '13 at 8:01
  • \$\begingroup\$ I suggest taking a list of tiles as input, loading the list of words from a predefined file and requiring all combinations / best combination to be found. Of course, if the input is the full list of tiles, the computation is going to take ages. I might allow preprocessing the word list outside the program itself (up to a certain point; a linearithmic growth?) \$\endgroup\$ – John Dvorak Dec 18 '13 at 8:32
  • 1
    \$\begingroup\$ I suggest modifying this so that input is a list of tiles, limited to a full rack or less (therefore 4-7 tiles, since our minimum word length is 4). Input should be assumed to be valid based on the standard set of tiles (e.g.: it wont' have something like 3 J's or 4 G's). This would have some practical use for a player in a scrabble game to figure out their next move (though it does not take into account tiles available to them which are already on the board). \$\endgroup\$ – Iszi Dec 18 '13 at 21:14
  • \$\begingroup\$ Alternative mode: Input is a list of tiles, maximum 96 (so that at least 4 are remaining in the set). Output only includes words (minimum 4 letters) which can be created without those tiles. This would be interesting as it provides words that may yet be created (though, again, not taking into account usable tiles on the board) at a given point in the game. \$\endgroup\$ – Iszi Dec 18 '13 at 21:15
  • \$\begingroup\$ Output needs to be decided as either a list of all possible words, or only the highest-scoring word(s). Another enhancement may be to require that the list be sorted descending in order of score (if output is all words), then ascending alphabetically. There's no reason to take each program's output into account for scoring. Since everyone is expected to use the same dictionary, all programs' outputs should be identical (except perhaps in sorting, if that's left out of the spec). So, this should be Code Golf. \$\endgroup\$ – Iszi Dec 18 '13 at 21:15
  • \$\begingroup\$ It's also worth noting that, as currently written, the task could just be to filter the given dictionary down to words which have 4 or more letters. By its very nature, the Scrabble dictionary should already exclude any words that cannot be made with a Scrabble set. \$\endgroup\$ – Iszi Dec 18 '13 at 21:18
  • \$\begingroup\$ @Iszi it's not "what are all the words you can make", it's "what are all the words you can make, where every letter used depletes a tile". There's a max of 25 words if you can use all 100 tiles. \$\endgroup\$ – Rob Dec 19 '13 at 16:40
  • \$\begingroup\$ I think I misunderstood the problem, then. I thought it was "all the words possible using a set of tiles" not "all the words possible, using only one set of tiles". Still, my point about code golf remains. There is an absolute maximum to the number of words (each with 4 or more letters) you can make with a single Scrabble set, and a finite number of permutations which can be used to hit that maximum. Every program written with this goal should end up with the same (or nominally similar) output. \$\endgroup\$ – Iszi Dec 19 '13 at 16:56
0
\$\begingroup\$

Test for Irreducible Complexity (Check for Redundant Characters)

I may need some additional help coming up with the full spec for this competition. As of right now, this is just a concept.

Many interesting questions, such as the "42" question in this sandbox, involve finding the longest program which is not reducible. This means that no set of characters can be removed and still allow the program to function as desired.

The basic idea is that your program will test a Base Program to make sure that it contains no redundant characters. The input will consist of:

  • Base Program (in the same language as your answer)
  • Expected Output

Your program will simply evaluate all possible subsequences of the Base Program and verify that none of them give the Expected Output.

This challenge actually has a utility value to several other challenges. For example, it verifies the results of a "longest non-reducible"-type challenge. In addition, it could make sure that a golfed solution cannot be golfed further.

I assume that the winning criteria will be fastest program, as cycling through all the possibilities takes a long time.

Problems

A sequence of length N has 2^N subsequences. Even if each evaluation is done very quickly, it might be unfeasible to test any program with more than 20 or so characters in a reasonable amount of time.

| |
\$\endgroup\$
  • \$\begingroup\$ Problem: some subsequences of legitimate answers may be pretty dangerous to the environment. You don't want to eval just everything. \$\endgroup\$ – John Dvorak Dec 23 '13 at 16:59
  • \$\begingroup\$ @JanDvorak Yes that actually is a serious problem. To what extent is it possible to fix that? \$\endgroup\$ – PhiNotPi Dec 23 '13 at 17:04
  • 1
    \$\begingroup\$ Forbidding any program with dangerous subsequences? :-) \$\endgroup\$ – John Dvorak Dec 23 '13 at 17:05
  • 1
    \$\begingroup\$ A more reasonable (but very difficult) solution would be the requirement to implement a sandbox. \$\endgroup\$ – John Dvorak Dec 23 '13 at 17:07
  • \$\begingroup\$ Even without dangerous behavior, the halting problem will be an issue: it's hard to tell whether a shortened program will terminate at all, especially for every conceivable input. \$\endgroup\$ – MvG Jan 7 '14 at 23:49
0
\$\begingroup\$

Popularity Contest: Implementation of a Hash Table

Create a class in some OOP language for a hash table that supports getting, setting, and removing values. You can't use the built in hash table/dictionary/map implementation. Highest votes in one week wins.

A key is any valid string. A value is any valid string, number, or boolean.

Example functionality:

hash.set("key","value");
hash.get("key"); // returns "value"
hash.set("key", 1234);
hash.get("key"); // returns 1234
hash.set("key2",hash.get("key"));
hash.get("key2"); // returns 1234
hash.delete("key");
hash.get("key"); // returns null/undefined/none/etc. or throws an error
hash.get("key2"); // still returns 1234

Definition of a hash table (from Wikipedia):

In computing, a hash table (also hash map) is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.

The hash table cannot be simply an array that is searched in linear time. It must be an actual hash table that uses a hash function to map the keys to the value.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Popularity contest and shortest don't mix. That aside, the spec is too vague. What is a "value"? What assumptions can be made about hashcodes? If the language makes all types nullable, should null be permitted as a key? What should the type be in languages which have co- and contravariance? And for that matter, what qualifies as a "hash table", bearing in mind that people will try to exploit any loophole? \$\endgroup\$ – Peter Taylor Jan 2 '14 at 23:16
  • \$\begingroup\$ @PeterTaylor Thank you for the feedback! Please see my edits, and let me know what you think. Could you meant about co/contravaraince? I looked at the wikipedia article about it but I'm not really sure how that has anything to do with this question. \$\endgroup\$ – hkk Jan 2 '14 at 23:37
  • \$\begingroup\$ I think it's still vulnerable to the loophole of "I have a hashtable with one bucket" (i.e. it's really a list of (key, value) pairs which I traverse in linear time). The thing about variance is to do with static typing of the elements of the map. E.g. in Java Map<String, Integer>'s get method has signature public Integer get(Object); in C#, a Dictionary<string, int>'s Get method has signature public int Get(string). The edited version makes it clear enough that the hashtable isn't expected to be genericised. \$\endgroup\$ – Peter Taylor Jan 3 '14 at 0:08
0
\$\begingroup\$

Wordlist detector

You are to write a program which, given a list of words, constructs a regular expression to match all these words but nothing else. Both your program and the constructed regular expressions are to be as short as possible.

Input and Output

Input comes on standard input and consists of one line giving n, the total number of words, followed by n lines with one word each. The number of words will be less than 1000, the length of each word less than 30. Words will consist only of lower case ASCII letters, i.e. a-z. You may choose to ignore the first line and use EOF instead to end the list.

Output shall be written to standard output. It consists of a single line, giving a POSIX extended regular expression to match these words and no others. Since input for this regex is not restricted to letters only, elements like . or [^…] won't make too much sense, which limits the language in a natural way. You may choose whether you want to terminate the line with a newline or not. Programs may choose to print multiple lines of output, in which case only the last one will be used for scoring. So you might print intermediate results and continue searching for improvements.

Test cases

Each submission may be accompanied by one regular expression. When scoring the submissions, I'll use this regular expression to reconstruct a word list from it. The code to do this reconstruction can be found at the end of this post. The reconstructed word list must fit the input specification above in terms of word count and length. It would be nice if your own program would be able to regenerate that regular expression from the word list, but that is not a strict requirement. But please don't paste bogus programs just to submit a challenging regular expression, though.

These test cases will be collected and fed to all programs for scoring.

Scoring

The final score of each program will be the program size plus the size of all its generated regular expressions for the inputs collected from submitted answers, including the example from this question. So short code which produces too long results might get beaten by longer code which generates shorter expressions.

Does this still qualify as ?

Submissions which generate an incorrect regular expression for one of the test cases will be disqualified, as will those which don't terminate in the allotted time. You can use the input reconstruction program below to check whether a produced regular expression does encode the correct word list.

Requirements

All submissions are welcome, but in order to include your submission in the tournament, it must be executable with reasonable effort on my Linux machine. It shouldn't depend on any exotic libraries, or any specialized ones which take too much work away from your own program. It must operate in reasonable time, say no more than five minutes per input. Your output must be reproducible, so if you use randomization at some point, please seed the randomizer, and please don't terminate an improove loop by a timer measuring execution time or some such.

Tournament times

I'll run the first major tournament two weeks after posting this question. I'll include a table of the results in this question. I'll try to run tournaments repeatedly as late submissions arrive, but I'll not promise any regular schedule.

Example

An very simple example application would be in Python 3 (53 chars):

print('|'.join(input() for i in range(int(input()))))

And here is a test case which could be posted along with the program, although this program obviously doesn't generate exactly this concise output:

bann?ana|ap(fel|ple)|s[ou]n|[hs](a|ou)nd

The expansion of that expression could be turned into the following example input, which need not be posted as part of an answer since it can be deduced from the regular expression:

10
banana
bannana
apfel
apple
son
sun
hand
hound
sand
sound

Regex expander program

And here is a program to turn regular expressions into word lists, again written in Python 3.

#!/bin/env python3
concat = set(('',))
altin = set(('',))
altout = set()
prev = None
stack = []
regex = iter(input())
for ch in regex:
    if ch == '(':
        stack.append((concat, altin, altout))
        altin = concat
        altout = set()
        prev = None
    elif ch == ')':
        concat.update(altout)
        prev, altin, altout = stack.pop()
    elif ch == '|':
        altout.update(concat)
        concat = altin
    elif ch == '[':
        ch = regex.__next__()
        cls = []
        while ch != ']':
            if ch == '-':
                crange = range(ord(cls[-1]), ord(regex.__next__()) + 1)
                cls.extend(map(chr, crange))
            else:
                cls.append(ch)
            ch = regex.__next__()
        prev = concat
        concat = set(w + c for w in prev for c in cls)
    elif ch == '?':
        concat.update(prev)
        prev = None
    elif ch >= 'a' and ch <= 'z':
        prev = concat
        concat = set(w + ch for w in prev)
    else:
        raise Exception("Illegal input")
if stack:
    raise Exception("Unclosed group")
concat.update(altout)
words = sorted(concat)
print(len(words))
print('\n'.join(words))

This is restricted to the part of regular expression syntax which I expect for this answer. If you have good reason to use something I did not consider, feel free to do so although I will likely have to update this code to cope with it. If you find a bug, please let me know.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ This is just Meta regex golf under the constraint that the two lists between them cover all possible words. Given that some people are tackling that existing question on that basis, this would qualify for closing as a duplicate. \$\endgroup\$ – Peter Taylor Jan 8 '14 at 8:45
0
\$\begingroup\$

Code-Golf: Write a number as an expression that's as short as possible

The goal of this code-golf is to create a program that takes a number as input (using STDIN, command line arguments, or prompting for input), and outputs that number, but written as an expression that's as short as possible. So, 10000 should become 10^4. If there is no way to write an expression that's shorter than the number, then output just the number.

Other rules

  1. No network access.
  2. You're not allowed to execute an external program.
  3. Only use the operators +, -, *, / and ^ (that's raising power, not XOR).
  4. Order of operations must be taken in account. Use parentheses if necessary.
  5. This is a code golf, so the code with the smallest amount of characters wins.
  6. The input will always be smaller than 2^32.

Test cases

500000000   -->    5*10^8     or    10^9/2
999999      -->    10^6-1
10          -->    10
4294967295  -->    2^32-1
16384       -->    2^14
| |
\$\endgroup\$
0
\$\begingroup\$

Rhymalator

(at the point, it's just something that came to me before i wake up, so it may need some adjusting, and i'd like some feedback as to if this could be fun)


The code challenge is to write a program that takes as input a calculation in Reverse Polish Notation and outputs the result. It must at least implement + - * /. It So far so easy, but to make it fun and "artistic", the following restriction applies:

  • The source code must rhyme when read. Example in PHP

    $iterator = str_split($a);
    foreach ($iterator as $key=>$value){
        if ($key > 3){
            ++$virtue;
        }
    }
    

    (the rhyme is on value-virtue)

  • Lines whitout readable characters count as whitespace (the two lines with } in the example)

| |
\$\endgroup\$
  • \$\begingroup\$ How does that example rhyme...? \$\endgroup\$ – Doorknob Jan 25 '14 at 12:54
  • \$\begingroup\$ @DoorknobofSnow well, i'm not really a poet, that's why i propose it as a challenge for others :p. if you have a better example i'll replace it \$\endgroup\$ – Einacio Jan 27 '14 at 15:58
0
\$\begingroup\$

Implement Kalah

The game of Kalah is a two-player board game in the Mancala family. Your implementation must:

  • Identify the active player ("Player 1" or "Player 2")
  • Display board state (in format specified below)
  • Accept input to allow that player to move (using index system below)
  • Announce a winner ("Player N wins")

Overview

Each player has a line of six spaces, called houses, and one additional space called a store. Each space holds seeds, which move from house to house in a counter-clockwise direction. The objective is to fill your store with seeds.

You must represent the board in the following two-row format with stores offset, where HH is a house and SS is a store:

SS HH HH HH HH HH HH
   HH HH HH HH HH HH SS

The top row represents the number of seeds in player #1's spaces, and the bottom row represents the seeds in player #2's spaces. The S in each row is the respective player's store (player #1's is top-left, #2's is bottom right). Single-digit values should include a leading space.

In this challenge, user-input will identify each house numerically. Use a left-to-right, indexed-from-one scheme for both sides:

S 1 2 3 4 5 6
  1 2 3 4 5 6 S

Note that the players' stores are not numbered, because seeds placed in the store never move out.

Rules

Wikipedia has a good summary of the game and its rules:

  1. At the beginning of the game, three seeds are placed in each house.

  2. Each player controls the six houses and their seeds on his/her side of the board. His/her score is the number of seeds in the store to his/her right. [Clarification: from our perspective, player 1's store is to the left, player 2's store is to the right.]

  3. Players take turns sowing their seeds. On a turn, the player removes all seeds from one of the houses under his/her control. Moving counter-clockwise, the player drops one seed in each house in turn, including the player's own store but not his/her opponent's.

  4. If the last sown seed lands in the player's store, the player gets an additional move. There is no limit on the number of moves a player can make in his/her turn.

  5. If the last sown seed lands in an empty house owned by the player, and the opposite house contains seeds, both the last seed and the opposite seeds are captured and placed into the player's store. [Clarification: moves that end on an opponent's empty house end normally without a capture.]

  6. When one player no longer has any seeds in any of his/her houses, the game ends. The other player moves all remaining seeds to his/her store, and the player with the most seeds in his/her store wins.

Example

(Parenthetical text should not appear in actual output.)

Player 1
 0  3  3  3  3  3  3
    3  3  3  3  3  3  0
> 2                      (prompt arrow and line break
                          are purely optional)
 Player 2
 1  1  0  3  3  3  3
    4  3  3  3  3  3  0
> 4

Player 2  (P2 gets a bonus turn from rule #4)
 1  0  3  3  3  3  3
    4  3  3  0  4  4  1
> 5

Player 1  
 1  0  3  3  3  4  4
    4  3  3  0  0  5  2
> 4

Player 1  (P1 captures P2's seeds in space 1)
 6  0  4  4  0  4  4
    0  3  3  0  0  5  2
...

Player 2
12  0  0 10  0  1  0
    0  0  0  0  0  1 13
 > 6

Player 1 wins            (because the non-finishing players gets
                          all remaining seeds on their side, it's 23-14)

Meta question: Would this be improved by removing some of the rules?

| |
\$\endgroup\$
  • \$\begingroup\$ Do the players run the game once and then take it in turns to take moves, with the process ending only when the game ends? Or do they run the program once per move? \$\endgroup\$ – Peter Taylor Jan 30 '14 at 10:06
0
\$\begingroup\$

[This is the first time I'm using the sandbox. I want to get feedback/suggestions before posting the question.]

Make a spider web (standard, orb type) that fills frame in the ratio of n:m, where n, m are input integers. You may use the example below as a model (but you don't need to use labels).

spider web

Your web should have multiple radii, at least 4 of which attach directly to the frame. The remaining radii should attach to the outer outline (perimeter) of the web. The web should have at least 15 radii. The mesh spacing should be more or less uniform spacing (although occasional weaving mistakes" or crossings are encouraged and will receive a bonus).

This is code-golf, so the shortest code (minus bonuses) wins.


Bonuses (to be removed from the number of characters in your code). Bonuses are awarded for the following features that reflect the architecture of an actual web (as opposed to a perfectly symmetric rendering). They are somewhat greater than usual as an incentive for attention to detail and realism.

-mesh spiral instead of concentric circles: 40 pts

-assymmetric web: 31 pts. (e.g. height of capture area greater than width)

-irregularly spaced radii: 42 pts

-distinct segments between radii (straight or crooked, but not the arc of a circle): 32 pts

-outer and inner outline clearly distinct from the spiral: 41 pts

-irregular outer outline: 20 pts

-2 or more easily observable reverses in spiral: 40

The accept will be awarded on Feb. 20, 2014.

| |
\$\endgroup\$
  • \$\begingroup\$ If there are bonuses then it isn't code-golf, by definition. It's not clear what output formats are acceptable. I'm not sure what you mean by "distinct segments between radii". "2 or more easily observable reverses" seems problematic: the ease of observing reverses is subjective, and might in addition depend on input and/or on the random numbers obtained. The weighting for the bonuses seems very arbitrary: is there any justification for it? \$\endgroup\$ – Peter Taylor Feb 3 '14 at 11:49
  • \$\begingroup\$ Re: bonuses, I should probably decide on the features I want included in the web, thereby eliminating bonuses altogether. Distinct segments means that there should be 2 straight mesh segments between radius n and radius n+2 (not sure whether this should be required in instructions to be updated.) Will give reverses more thought. \$\endgroup\$ – DavidC Feb 3 '14 at 12:02
0
\$\begingroup\$

Write a PHP Code Golfer

Since my currently daily programming is in PHP, I tend to try the challenges on the site using that language, but frequently I large program because of the verbosity of the language. And then I have to strip it for presentation...

But this is not a tips question, it's an eviscerating challenge.

The objective is to write a program in the language of your choice that takes a PHP file and outputs a golfed valid PHP file with the same functionality.

The scoring will be the average reduction in percent of the result of running the program with 3 selected files (not yet selected, I was thinking of some open source library)

The output file should run on at least 5.4 (so shorthand arrays, function dereference, traits are available)

Since the score is the difference between the ungolfed and golfed files, techniques beyond minifying are encouraged, such as using code subtitution, eval, compression, $$ (variable variables), dereferencing...


Scoring example: The 3 sources have 450, 1200 and 3500 chars respectively

Answer 1
results lenghts: 250, 1000, 3300
reduction: 200, 200, 200 (44%, 17%, 6%) average: 22%

Answer 2
results lenghts: 350, 1050, 3150
reduction: 100, 150, 350 (22%, 13%, 10%) average: 15%

In this case Answer 1 would win, even tough both answers got the same total reduction (-600 chars)

| |
\$\endgroup\$
  • \$\begingroup\$ It's a specialisation of codegolf.stackexchange.com/q/3652/194 , so would likely be closed as a duplicate. \$\endgroup\$ – Peter Taylor Feb 4 '14 at 22:44
  • \$\begingroup\$ @PeterTaylor I saw it. is similar, but I include an objetive goal and score. have any idea on how to make it more unique? \$\endgroup\$ – Einacio Feb 5 '14 at 2:43
  • \$\begingroup\$ "Making it shorter" is too broad, can I just delete some comments? If not, can I only shorten one variable and it's ok. It's not very interesting like this... \$\endgroup\$ – Fabinout Feb 5 '14 at 9:56
  • \$\begingroup\$ @Fabinout the objective is golfing the code. If you only remove some characters, I doubt you'll get a good score \$\endgroup\$ – Einacio Feb 5 '14 at 15:27
  • \$\begingroup\$ Alright, the criterion is the size of the output source code. good clarification. \$\endgroup\$ – Fabinout Feb 5 '14 at 15:55
  • \$\begingroup\$ Sum the bytes with the percents or separately? Also, no matter what sources you choose, make sure to paste the code into your questions; who knows when the code in the library will change? \$\endgroup\$ – Justin Feb 6 '14 at 19:11
  • \$\begingroup\$ i'll edit the bit about scoring (with examples) tomorrow (when i come back to work). I'll post the test sources as a pastebin, but I'll wait to choose them until the question is polished enough and someone consider it interesting enough \$\endgroup\$ – Einacio Feb 6 '14 at 19:34
  • \$\begingroup\$ Is there anyone more with questions? is still possible that it will be marked as a duplicate? or can i choose the sources and publish it? \$\endgroup\$ – Einacio Feb 13 '14 at 19:22
0
\$\begingroup\$

Create diagonal code

Your task is to create a program that outputs d=s*sqrt(2).

Specs:

  • Your program must be at least 4 lines long;

  • d=s*sqrt(2) cannot be hardcoded as is (so using ascii, compression, encoding, etc. is allowed and encouraged);

  • For each line of code n, pick up the nth character. The string obtained this way must be a valid program in a programming language of your choice, that must be different from the one you used for the main program. The obtained program must compile successfully, but it can throw errors, exceptions, etc.;

  • If at the nth line there is no nth character, you can consider that character as a whitespace or a newline. This cannot be done for the first 4 lines, which must be long at least n non-whitespace characters.

  • Your main program must end successfully (no errors, exceptions, etc.);

  • Internet access is forbidden;

  • Most upvoted answer in 2 weeks wins.

Happy coding!


I was unsure about making this a with several bonuses (polyglot answer, secondary program still valid, etc...).


Some bonuses for the code-challenge version:

Your valid answer starts with 0 points. You gain:

+10 if the secondary answer hides a third answer in it;
+15 for any other hidden answer;
+5 for every hidden answer that runs and ends successfully, without any problem;
+10 if your main answer is a polyglot;
+15 for every hidden answer that is a polyglot;


Which version would you prefer? Is there something you would change/improve in this question?

I personally like the one, but the KISS principle (Keep it simple, stupid!) reminds me that I may be wrong.

| |
\$\endgroup\$
  • \$\begingroup\$ It's trivial to make the diagonal program be just whitespace (many scripting languages will accept this as a program) or H (valid program in H9Q+). \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:26
  • \$\begingroup\$ Nowhere does it say that the diagonal program must output your magic string: it doesn't even have to execute correctly. Your amendment doesn't really fix things: I can now have the second line be #H, the third be #HH, etc. \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:37
  • \$\begingroup\$ You're right; Don't know why, on a second read I messed up the meaning of your comment. Anyway, I suppose this excludes code-challenge unless I/we don't find a way to avoid such trivial solutions. I guess popularity-contest would still be ok, since more interesting solutions could be found, right? \$\endgroup\$ – Vereos Feb 26 '14 at 9:41
  • \$\begingroup\$ I think my views on popularity-contest in general are well known. On further reflection, there are enough languages in which any string of bytes is a valid program that I don't think this question can work as is. If you want to save it, I think you need to look at doing something like a very difficult double-quine. \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:49
  • \$\begingroup\$ Thinking about quines and diagonals (which was the "spirit" of the question), what about a sort of mini-quine? The main program would have to display d=s*sqrt(2) only, and its diagonal must reproduce the code used to display the magic string (no comments allowed). It could be tagged code-golf or code-challenge. \$\endgroup\$ – Vereos Feb 26 '14 at 11:04
0
\$\begingroup\$

Create a Karnaugh-map calculator

Given an input of a truth table, generate a corresponding K-map.

Input:

Input will be of the form 10110001 where each bit is a row of a truth table. Count from the left to the right; so that input would be a table of:

i2i1i0 f
0 0 0|1
0 0 1|0
0 1 0|1
0 1 1|1
1 0 0|0
1 0 1|0
1 1 0|0
1 1 1|1

Max 4 variables will be inputted

K-maps (a small explanation):

K-maps are a way of simplifying boolean-algebra expressions.

Let's say we have 4 variables: a, b, c, d. Let the truth-table be 1110101001111111 (and the columns on the truth table be labeled, from left to right: a, b, c, d). Arrange the variables like so:

   cd
ab\   00 01 11 10
   00
   01
   11
   10

Note the grey-code counting scheme.

Fill in the table with the corresponding values from the truth table:

   cd
ab\   00 01 11 10
   00 1  1  0  1
   01 1  0  0  1
   11 0  1  1  1
   10 1  1  1  1

Group the values in rectangles whose dimensions are the largest possible powers of two. Note that this table signifies a torus, so wrap over the left and right edges.

enter image description here

The expression for the truth table is the ors of the and of the unchanging elements. For this, that would be:

Purple group: ¬b ∧ ¬c (for 0's, make them 1 by notting the value)
Green group: ¬a ∧ ¬d
Black group: a ∧ d
Blue group: b ∧ ¬d

Expression: (¬b ∧ ¬c) ∨ (¬a ∧ ¬d) ∨ (a ∧ d) ∨ (b ∧ ¬d)

Output:

  • Generate a 2D K-map (for more variables, add on either side) and show the grouping. K-map must be of the form I used. For less variables, remove rows or columns and change the list on the top left corner.
  • assume alphabetical ordering on the variables, that is, the first variable is a, second: b, third: c, and so on.
  • Also show the expression. Rather than use the unicode characters, the following is permissible:

    ~ instead of ¬
    * instead of ∧
    + instead of ∨
    


Edit: Possible duplicate: More fun with gates: Karnaugh simplification

| |
\$\endgroup\$
  • \$\begingroup\$ I think the grouping is not unique and therefore I might choose the most basic grouping (i.e. none). \$\endgroup\$ – Howard Feb 26 '14 at 9:02
  • 1
    \$\begingroup\$ Although @Howard's concern is partially answered by "rectangles whose dimensions are the largest possible powers of two", it's not obvious to me why you haven't also circled the entire row 10 and the bottom-right quadrant. \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:29
  • \$\begingroup\$ @PeterTaylor You're right - didn't read that line. But still my main concern is correct: it is not unique. Or as your remark shows it is not optimal if you choose all rectangles. \$\endgroup\$ – Howard Feb 26 '14 at 9:33
  • \$\begingroup\$ Also for higher number of variables you have to either go to n dimensional K-maps or you won't find all possible rectangles (they are no longer adjacent in the matrix). \$\endgroup\$ – Howard Feb 26 '14 at 9:38
  • \$\begingroup\$ @PeterTaylor In priority: Biggest rectangles, then least number. That is a big rectangle, but it is redundant with the others because every 1 in it is already circled. \$\endgroup\$ – Justin Feb 26 '14 at 16:44
  • \$\begingroup\$ @Howard Good point. I'll restrict it to 4 or less variables. \$\endgroup\$ – Justin Feb 26 '14 at 16:47
  • \$\begingroup\$ For the expression: rather than using A and V, why not * and +? That's fairly conventional use of field notation to represent GF(2). \$\endgroup\$ – Peter Taylor Feb 26 '14 at 17:11
  • \$\begingroup\$ Ahem. OR is, of course, not the same as + in GF(2). But * and + is still the conventional notation for operations over the Boolean semiring. \$\endgroup\$ – Peter Taylor Feb 28 '14 at 15:31
1
48 49
50
51 52
98

You must log in to answer this question.

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