490
\$\begingroup\$

What is the Sandbox?

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

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

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

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

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

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

| |
\$\endgroup\$

2956 Answers 2956

1
48 49
50
51 52
99
1
\$\begingroup\$

Posted.

| |
\$\endgroup\$
  • \$\begingroup\$ It would ease readability if all of the test cases were in a single code block, with empty lines in between. Then you can add the explanations afterward for cases that really need it. \$\endgroup\$ – fireflame241 Jun 23 at 17:43
  • \$\begingroup\$ Is there a limit to the depth of the tree? \$\endgroup\$ – fireflame241 Jun 23 at 17:44
  • \$\begingroup\$ The problem statement involves a bunch of high-level math terms, which can deter some people. If possible, the challenge would be more approachable if you add an alternate definition, e.g. relating isomorphism to permutations (kinda) of the underlying set. For the explanation of the first case, it would be good to rewrite each line using normal infix notation, e.g. (x+y)+z = x+(y+z) and x+(-x) = 0. \$\endgroup\$ – fireflame241 Jun 23 at 17:49
  • \$\begingroup\$ @fireflame241 I hid the technical details. And could you please explain why I should put a limit to the depth? In what ways does that make the challenge better? ;) \$\endgroup\$ – Trebor Jun 24 at 1:25
  • \$\begingroup\$ I was just wondering. A golfer might be able to optimize for a limit depth of 2, but it's more interesting to have an arbitrary rank \$\endgroup\$ – fireflame241 Jun 24 at 1:29
  • \$\begingroup\$ @fireflame241 After some thoughts, it is clear that every theory can be translated to one that has a limit depth of 2 ;) Also every practically interesting case happens at depth 2. So I think I'll add that. \$\endgroup\$ – Trebor Jun 24 at 1:53
  • \$\begingroup\$ Now that this has been posted to main, could you delete this proposal to create more space for new answers? \$\endgroup\$ – caird coinheringaahing 2 days ago
1
\$\begingroup\$

Write an expect program

If you're not already familiar, expect is a Tcl extension that makes it easier to script interactions with programs. It allows you to spawn a process, send lines to it, and wait for expected output before continuing.

Challenge

The aim of this challenge is to write a very simple implementation of expect in as few bytes as possible (code golf). It should parse a script, with commands separated by newlines. Then it should use this script to interact with a program.

Here are the commands for this implementation:

  • spawn <cmd>: spawn a process.
  • write <line>: write a line into the process' input.
  • expect <line>: expect a substring from the process' output. No timeout is necessary, if the line never appears it is OK for the program to hang.
  • print <line>: print something to stdout.

You can assume that only one spawn will be found in the script, and that it will appear before any write or expect. If your language of choice doesn't have the ability to spawn processes, you can write a helper program in a different language that can pipe input and output through your main program. How you do this is left up to you.

Example script:

spawn /bin/bash
write whoami
expect root
write uname -a
expect Linux
print i am root on Linux

Output:

this is Linux

or

spawn /bin/bash
write uname -a
expect Windows
print this is Windows

(no output.)

Restrictions

In order to keep things fresh, the use of the standard expect utility or any libraries that emulate expect functionality (such as pexpect on Python or jest on Node) are not allowed. The idea is that the bulk of the functionality should be written in the program and not handled in a library.

| |
\$\endgroup\$
  • \$\begingroup\$ Will the script always have 4 commands, namely those 4 in that order? \$\endgroup\$ – Adám Jun 30 at 3:52
  • 1
    \$\begingroup\$ While prohibiting the standard expect utility is probably unambiguous, prohibiting expect-like libraries could potentially be problematic because there's no objective way to judge if any given feature is expect-like. I could claim that addition is expect-like, and you'd be hard pressed to counter that. \$\endgroup\$ – Adám Jun 30 at 3:55
  • \$\begingroup\$ The script could have more commands. I will update the examples to reflect that change. As far as the library restrictions, I could remove them - I do see where it could lead to being a problem. Perhaps I could make it more unambiguous by mentioning specific libraries (one that comes to mind is python-pexpect.) \$\endgroup\$ – nununoisy Jun 30 at 16:10
  • \$\begingroup\$ Can we make any assumptions about the order of the commands? \$\endgroup\$ – Adám Jun 30 at 18:06
  • \$\begingroup\$ Yes, I forgot to mention that spawn will come before any command that needs the process. It should be updated now. \$\endgroup\$ – nununoisy Jun 30 at 20:23
  • \$\begingroup\$ What should be done if the expect string is not found? \$\endgroup\$ – user202729 Jul 10 at 3:26
  • \$\begingroup\$ It was mentioned above but for clarity: 'No timeout is necessary, if the line never appears it is OK for the program to hang.' \$\endgroup\$ – nununoisy Jul 10 at 19:58
1
\$\begingroup\$

Count faces in ASCII art

Here's a 2x2 ASCII art face:

oo
__

Here's a 3x3 ASCII art face:

o o
   
___

Here's a 4x4 ASCII art face:

o  o
    
    
____

Your task is to count faces in an ASCII art.

Here's something closer to an actual specification.

The bottom of any face must be a contiguous horizontal row of underscores, such that cells to the right and to the left of it do not contain underscores. If the row is considered as the bottom row of an ASCII square, then that square forms a face if and only if its bottom row is all underscores, its upper left and upper right corners are os, and the rest is whitespace.

You may assume all lines in the input to be padded on the right with whitespace to an equal length. Faces cannot be smaller than 2x2.

[todo: more test cases]

o o
   oo
_____

Output: 0

Sandbox stuff

Is it clear what is considered a face and what is not?

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

The almost impossible chessboard puzzle

Background

Prisoner 1 walks in, sees a chessboard (8x8) where each square has a coin on top, flipped either to heads or tails. The warden places the key under one of the squares, which prisoner 1 sees. Before prisoner 1 leaves, he must turn over one and only one coin. Prisoner 2 then walks in and is supposed to be able to figure out which squares the key is in just by looking at the arrangement of coins.

The prisoners are granted a reward if prisoner 2 correctly tells the location of the key.

Task

Write two program/functions:

  • One for prisoner 1, which outputs the location of the coin to flip given the current board state and the location of the key
  • One for prisoner 2, which outputs the location of the key given the board state after prisoner 1 doing the flip.

If both the solutions are function they may share code with an auxiliary function, though the solutions may not share any information.

Scoring

This is so shortest bytes wins


Heavily inspired by The almost impossible chessboard puzzle and The impossible chessboard puzzle

Sandbox

  • Should I include the tag
  • Any more tags I should add
  • Is something not clear

Also pretty sure this will require a lot of rewording before it can be asked

| |
\$\endgroup\$
  • \$\begingroup\$ Can the two solutions share code, for example by having two functions that both call a third auxiliary function? \$\endgroup\$ – Zgarb Jul 7 at 9:20
  • \$\begingroup\$ Yes, the two solutions can share code but they cannot share information. Updated the question to reflect that \$\endgroup\$ – Mukundan314 Jul 7 at 9:30
  • \$\begingroup\$ Can the auxiliary function be one of the programs? Can both of the programs be the same (and only counted once for bytes, having different behavior based on whether a second argument is passed)? \$\endgroup\$ – fireflame241 Jul 9 at 0:25
1
\$\begingroup\$

Infinite Mirrors Quine

This challenge is to create a program that prints out code that prints the original. Basically, this program should take an input, check if it's A, and if so, run section A. Otherwise, if it's B, run section B. Finally, if it's neither, print nothing. Section A should print the code in section B, and section B should print the code in section A. Section A's code and section b's code should not be identical. Shortest code wins!

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

Continuous Everywhere, Differentiable Nowhere

Objective

Build the Weierstrass function \$f(x) = \sum_{n=0}^\infty a^n \cos(b^n n x)\$, where \$a \in (0,1)\$, \$b\$ is an odd positive integer, and \$ab > 1 + 1.5\pi\$.

What's the fuss?

The Weierstrass function is an example of a function that is continuous everywhere, but differentiable nowhere.

Format

Using floating-point number is permitted. Though it will be preferred to use a datatype that is able to represent arbitrary real numbers.

Rules

\$a\$ and \$b\$ are up to your choice, as long as they satisfy the conditions.

For every \$x \in \mathbb{R}\$, evaluation of \$f(x)\$ must halt.

Note

The fact that the function above is defined as an infinite series might seem to contradict the rule, but it actually doesn't. The Weierstrass function is computable, implying that it is possible to halt for every input. In particular, if it were to be implemented over floating-point numbers, it suffices to stop summing when the summand becomes denormal.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I really doubt that the Weierstrass function is computable since its domain is real numbers and computer programs can only compute a select few functions on arbitrary real input. The Weierstrass function is very likely computable on some restricted domains like the rational numbers. Really this question has a some issues with the fact that continuity and differentiabilty are usually discussed in the context of real numbers, but does not require that it work on actual real numbers. \$\endgroup\$ – Wheat Wizard Jul 16 at 1:36
  • 1
    \$\begingroup\$ For example as it currently stands I could do something like just output the floating point zero regardless of input. This is approximates some cewdnw function, in fact it comes arbitrarily close to approximating an infinite number of cewdnw functions. For example just the Weierstrass function multiplied by a really small positive number. \$\endgroup\$ – Wheat Wizard Jul 16 at 1:38
  • 1
    \$\begingroup\$ However if you do restrict it to real numbers you run into the problem that very few functions are computable on real numbers. (The issue here is that a program on real numbers must be ready to accept an infinite string of input). I suggest restricting your domain to something like rational numbers, but note that this alters continuity and differntiability in subtle ways so it is not a simple patch. \$\endgroup\$ – Wheat Wizard Jul 16 at 1:41
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\$ – Wheat Wizard Jul 16 at 12:23
  • \$\begingroup\$ Yes. -- -- -- -- -- -- \$\endgroup\$ – user202729 Jul 16 at 13:29
  • \$\begingroup\$ @user202729 What is it? \$\endgroup\$ – Wheat Wizard 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\$ – Wheat Wizard 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\$ – Wheat Wizard 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\$ – Wheat Wizard 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\$ – Wheat Wizard Jul 17 at 3:23
  • \$\begingroup\$ Now that this has been posted to main, could you delete this proposal to create more space for new answers? \$\endgroup\$ – caird coinheringaahing 2 days ago
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\$

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\$ – null 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\$ – null 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\$

Paper folding. Posted HERE

| |
\$\endgroup\$
  • \$\begingroup\$ Now that this has been posted to main, could you delete this proposal to create more space for new answers? \$\endgroup\$ – caird coinheringaahing 2 days ago
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\$

Make yourself a COBOL BASIC for great evil

Task: Make an internal or external DSL that looks as much like a subset of BASIC as possible (the subset's defined below). You can use other people's libraries if you want. Using that DSL, you have to calculate and print the first 20 Fibonacci numbers. (Note for meta: I'm not sure about the Fibonacci numbers part. A different task would do)

Rules:

  • Don't just make a shell script calling a BASIC compiler
  • Each statement must begin with a line number, just like BASIC
  • The DSL should have variables, assigned like LET X = 100. The LET can be optional if you want.
  • There should be if-statements that look like IF condition THEN statement
  • There should be a PRINT keyword, usable with variables and string literals. An example would be PRINT "foo", X, which prints the value of "foo" and then X, or PRINT "foo";X, which prints "foo" and then X without continuing to the next line.
  • There should be a GOTO keyword, so you can beautiful code like 270 GOTO 40 without having to write those god-awful loops.
  • (Optional) Every program ends in an END command. It's optional because subroutines aren't included.
  • There should be basic arithmetic operations like *, +, -, \ included; and relational operators like >, <, = (== in some languages), and <> (!= in some languages).

(Question for meta: Is this subset specific enough?)

Stuff you don't necessarily have to do:

  • Implement subroutines.
  • Worry about line numbers not being in the right order. You can assume programmers are responsible enough to put line 20 after line 10.
  • Implement loops of any kind. GOTO is all you will ever need.
  • Add comments (REM)
  • Add a HOME, CLS, or TEXT command. Assume they've been set already.
  • Implement lists and stuff

Scoring (I'm not sure about this):

  • Shortest program (in the BASIC-like DSL) wins ???
  • Or maybe compare that Fibonacci number generating program to this one (with Levenshtein distances)? (may require corrections and/or polishing):
10 LET A = 1
20 LET B = 1
21 PRINT A
22 PRINT B
30 LET I = 1
50 LET S = A + B
60 PRINT S
70 LET A = B
80 LET B = S
90 LET I = I + 1
100 IF I < 20 THEN GOTO 50
110 END
| |
\$\endgroup\$
  • 3
    \$\begingroup\$ looks as much like COBOL as possible is too subjective for the goal of the challenge. A better challenge would be "write a subset of COBOL" with clear syntax and semantics. \$\endgroup\$ – Bubbler Jul 28 at 2:46
  • 1
    \$\begingroup\$ I guess you added the Levenshtein distance to measure the similarity, but there will be infinitely many valid programs that fulfill a task, both in COBOL and the DSL (especially if the DSL is Turing-complete). How would you check if there exists some pair of programs that are close enough? \$\endgroup\$ – Bubbler Jul 28 at 2:50
  • \$\begingroup\$ Popularity-contest isn't really suitable on this site. \$\endgroup\$ – user202729 Jul 28 at 14:07
  • \$\begingroup\$ @Bubbler How about now? I used BASIC instead of COBOL because it seems to have less keywords and easier syntax. \$\endgroup\$ – user Jul 29 at 15:10
  • 1
    \$\begingroup\$ @user202729 You really do think so? How 'bout Finest Magic Code Square? \$\endgroup\$ – null Aug 24 at 13:48
1
\$\begingroup\$

Posted: Antisymmetry of a Matrix

| |
\$\endgroup\$
  • \$\begingroup\$ Mathematica: AntisymmetricMatrixQ (of course, a non-built-in solution can be much shorter). \$\endgroup\$ – the default. Jul 30 at 13:12
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\$ – null Aug 10 at 13:17
1
\$\begingroup\$

How Many Notches Are On Texas Red's Pistol?

The song, Big Iron, by Marty Robbins, is about an Arizona Ranger who rode into the town of Agua Fria to take the outlaw Texas Red alive (or maybe dead), armed with only the Big Iron (a .45 revolver) on his hip. Texas Red, despite being only 24 years old, is extremely dangerous, having already taken out 20 men who have tried to go after him. As a point of pride, he's carved out a notch on his pistol for each one. The song counts the notches on Texas Red's pistol as "one and nineteen more". After listening to the song a couple times, two questions crossed my mind:

  1. What about the other numbers that add up to twenty?
  2. What if the Ranger wasn't the 21st person to try?

The Challenge

Given a positive integer, N, the total notches on Texas Red's pistol, and another number A (also an positive integer), output a number B such that B + A = N. In the context of the song, it should read "A and B more".

The Catch

The song still has to be intact without sub-dividing any beats. That is, the number of syllables in the phrase "A and B more" must add up to 5. If it doesn't, output the string "oops". You may assume

  • 0 < A < N < 20
  • 1 < N

Examples

N   A   B (output)

20  1   19   ("One and nineteen more.")
19  2   oops ("Two and seventeen more" has 6 syllables)
11  7   4    ("Seven and four more.")

Syllable Counts

The numbers, from one to nineteen, have syllable counts as follows: one (1), two (1), three (1), four (1), five (1), six (1), seven (2), eight (1), nine (1), ten (1), eleven (3), twelve (1), thirteen (2), fourteen (2), fifteen (2), sixteen (2), seventeen (3), eighteen (2), and nineteen (2). No synonyms are accepted, such as "aught more" for "zero more".

Scoring

: Shortest code in bytes wins. Standard loopholes apply.


Meta Stuff:

I hope this is interesting enough. I thought just a normal subtraction problem would be too boring.

Is "oops" a good distinguishing output?

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

Show an integer, in digits of your choice

Input

A string representing digit characters, and a nonnegative integer.

How?

We shall show the integer in positional notation, where the string has the digit characters. Assuming the string is zero-indexed, the \$n\$th character shall represent \$n\$. The length of the string is the base.

For example, "0123456789" will show the integer in the standard decimal representation.

Rules

  • The string is assumed to have at least 2 characters.

  • Invalid inputs fall in don't care situation.

Examples

Beware of the zero!

Binary representation

Given "01" as the string:

$$ \begin{array}{c|c} 0 & “0” \\ 4 & “100” \\ 8 & “1000” \\ 15 & “1111” \\ 16 & “10000” \\ 23 & “10111” \\ 42 & “101010” \end{array} $$

Devanagari representation

Given "०१२३४५६७८९" (U+0966 – U+096F) as the string:

$$ \begin{array}{c|c} 0 & “०” \\ 4 & “४” \\ 8 & “८” \\ 15 & “१५” \\ 16 & “१६” \\ 23 & “२३” \\ 42 & “४२” \end{array} $$

Duodecimal representation

Given "0123456789↊↋" (The last two characters are U+218A and U+218B) as the string:

$$ \begin{array}{c|c} 0 & “0” \\ 4 & “4” \\ 8 & “8” \\ 15 & “13” \\ 16 & “14” \\ 23 & “1↋” \\ 42 & “36” \end{array} $$

Ungolfed solution

Haskell

showIntArb :: String -> Int -> ShowS
showIntArb "" _ = error "showIntArb: No given digit"
showIntArb (d:_) 0 = showChar d
showIntArb ds n = let
    appendDigit ints = if length ints <= n
        then appendDigit $ do
            d <- ds
            int <- ints
            return (d : int)
        else ints
    in showString (appendDigit (fmap return ds) !! n)
| |
\$\endgroup\$
  • \$\begingroup\$ so this is a base encoding question, with symbol replacement, right? \$\endgroup\$ – Razetime Sep 14 at 17:43
  • \$\begingroup\$ @Razetime Yes, exactly. \$\endgroup\$ – Dannyu NDos Sep 14 at 22:51
1
\$\begingroup\$

Haiku Quine

A haiku is a type of poetry originating from Japan following a simple pattern: 5 syllables on the first line, 7 syllables on the second, and 5 syllables on the third. Traditionally, haikus also include some reference to nature or seasons, but we'll ignore tradition for the sake of this challenge.

Your task is to create a quine which has some reasonable pronunciation in the form of a haiku.

For example, consider this loophole-abusing (and thus non-competing) Python quine:

0+0
with open(__file__) as fp:
    print(fp.read())

To be read as:

ze-ro plus ze-ro
with o-pen file as F P
print F P dot read

Rules and Scoring

This is , so the shortest code wins.

  • Standard rules and banned loopholes apply
  • Include a reasonable haiku pronunciation alongside your code (yes, this is inherently subjective and open-ended)

NOTE: may be better as a

| |
\$\endgroup\$
  • \$\begingroup\$ what's the standard for xxd output here? \$\endgroup\$ – Razetime Sep 15 at 3:34
1
\$\begingroup\$

Convert A String To Shorthand

Shorthand has been used for hundreds of years to compress and speed up the speed at which someone can write down what is said.
It does this using several abbreviating methods; three of which will be used here to compress a sentence.

Challenge

When given a sentence, alongside a set of 'briefs', 'prefixes' and 'suffixes' (defined below), print or return the sentence in its compressed form.

Definitions

  • Brief: A word that can be entirely substituted by another string of characters.
    I.E. Would: D, Be: B, Able: Ab. "I would be able...": "I D B Ab
  • Prefix: The beginning of a word that can be substituted by another string of characters; the prefix will either be joined or dis-joined.
    After(Joined): Af. Afternoon = Afnoon.
    Enter/Inter/Intra(Dis-joined): N. Internet = N-net
  • Suffix: The ending of a word that can be substituted by another string of characters; the suffix will either be joined or dis-joined.
    ful/ify(Joined): F. Clarify = Clarf
    ification(Dis-joined): F. Clarification = Clar-f

Input Structure

  1. The first input will be the sentence to be converted
  2. The second input is a collection of the briefs. Each brief is a collection itself, in which the first element represents the shortened form of that brief, while the rest of the elements are all strings that map to the brief. Example: [ [d, would], [m, much, more], [a, at, an] ]
  3. The third and fourth inputs are collections of prefixes and suffixes. The first element of each prefix/suffix is the shortened form, the second element is a flag (of your choosing) that represents whether it is joined or dis-joined. Everything else are the strings that match the prefix/suffix.
    Prefix: [ [af, true, after], [n, false, enter, inter, intra] ]
    Suffix: [ [f, true, ful, ify], [f, false, ification] ]

Sample Input:

"a shipment of letters was delivered to the postshop", [["of", "o"], ["t", "to"], ["was", "os"], ["the", "th"]], [["sh", false, "ship"], ["d", true, "de"], ["po", false, "post"]], [["rs", true, "ers"], ["m", true, "ment"], ["d", true, "ed"]]

Rules, Assumptions and Freedoms

  • You may assume all input is lowercase letters.
  • A brief will always take priority over prefixes and suffixes.
  • you can indicate a dis-joined suffix/prefix however you wish, as long as you mention how you are indicating it.
  • The input may be rearranged however you like, as long as you specify how your input is structured
  • Output may be returned, printed or the nearest equivalent.

Test Cases

"a shipment of letters was delivered to the postshop", [["of", "o"], ["t", "to"], ["was", "os"], ["the", "th"]], [["sh", false, "ship"], ["d", true, "de"], ["po", false, "post"]], [["rs", true, "ers"], ["m", true, "ment"], ["d", true, "ed"]]

a sh-m o lettrs os dliverd t th po-shop

"shorthand was once a common skill among woman", [["was", "os"]], [["sh", false, "ship", "short"], ["cm", true, "com"]], [["mn", true, "mon", "man"]]

sh-hand os once a cmmn skill among womn"

"the electrician will be able to fix it", [["th", "the"], ["l", "will"], ["b", "be"], ["ab", "able"], "t", "to", "it"]], [["el", false, "electr"]], [["sh", true, "cian", "sion"]]

th el-ish l b ab t fix t

| |
\$\endgroup\$
  • \$\begingroup\$ Looks like a nice challenge, I don't think there's much that needs to B clar-f-ed \$\endgroup\$ – Redwolf Programs Sep 7 at 14:12
1
\$\begingroup\$

Keep the symmetry

SANDBOX: I am aware that the language in this challenge, as it stands, is quite... fluffy. If anyone could help me firm it up, I would be grateful. Also, would this be better as a cops-and-robbers style challenge, where the cops are trying to make the output more symmetrical, and the robbers make it less symmetrical?

Given a 2D array of 1s and 0s, flip a 1 to a 0 and output the resulting array.

The output array must be "closer to being symmetrical" than the input.

In the case where the array is already symmetrical, it must still flip a 1 to a 0, breaking as little symmetry as possible - e.g for

1,0,1
1,0,1
1,0,1

In the above case, changing the top-left 1 to a 0 will break symmetry in both directions, whereas changing the middle-left 1 will only break symmetry one way.

The output must be in the same form as the input (so that your program or function could take it in again).

What is symmetry?

I am talking about reflectional symmetry along both the horizontal and vertical axes.

Where the array has an even number of entries in a row/column, the axis is between the two central rows/columns:

1,0,|,0,1
1,0,|,0,1
-,-,-,-,-
1,0,|,0,1
1,0,|,0,1

otherwise it's down the middle of the middle row/column (and the numbers in that row/column count on both sides).

   |  
 1,0,1
-1,0,1-
 1,0,1
   |

Some Examples

Each pair of grids below is input .. output, which then becomes the next input, etc. iteratively:

1,0,0,1      1,0,0,1      1,0,0,1      1,0,0,1      1,0,0,0      0,0,0,0      0,0,0,0
0,0,1,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,1      1,0,0,1      0,0,0,1      0,0,0,0      0,0,0,0      0,0,0,0      0,0,0,0
1,1,1      1,0,1      1,0,1      1,0,1      1,0,1
1,1,1  ..  1,1,1  ..  1,0,1  ..  0,0,1  ..  0,0,0
1,0,1      1,0,1      1,0,1      1,0,1      1,0,1

| |
\$\endgroup\$
  • \$\begingroup\$ Is the program supposed to find the shortest path, or any path? Are we supposed to display each step? Should the choice of flipping a 1 to a 0 be random, or can it be calculated? A reference implementation would be very useful in this question. \$\endgroup\$ – Razetime Aug 26 at 13:03
  • \$\begingroup\$ The program is only supposed to flip one, calculated, bit from 1 to 0 and return the new grid. so iterative calls to the program would ultimately lead to all 0s. I guess I'm unclear exactly how I want the concept to be translated into a challenge, which is why I put the sandbox text at the top \$\endgroup\$ – simonalexander2005 Aug 26 at 13:38
  • \$\begingroup\$ The program must be trying to make the array symmetrical This needs to be defined precisely. What does it mean that the program "tries" to make it symmetrical? That repeated application of the program eventaully gives a symmetrical array? That it does it in a "small" (to be defined) number of steps? Same with as easy as possible: this needs to be defined precisely. I'm afraid I don't get the main idea of the challenge, actually \$\endgroup\$ – Luis Mendo Aug 26 at 17:21
1
\$\begingroup\$

Balanced Beams

Here are some examples of beams that balance:

X Y A   | X Y B Y
--+-----+---+---+
  |         |   |
X X   Y Y   Y X X
--+---- ----+-- +

A X X Y | A B Y Y
+---+---+-+-----+
|   |     |     |
B A | A AAB B   A
+ --+-- --+--   +

X Y X X | Y B   X
+-+-+---+---+----
| | |       |
Y A X Y Y X X X X
+ + + ------+----

The diagram will always be 17 characters wide and the top beam always balances in its centre. The other +s on the top beam indicate the point from which a lower beam hangs and the + on the lower beam indicates the point at which it balances. Your input does not need to include the |s if you don't need them. Lower beams with a width of 1 balance by default of course. The balancing of the top beam has to take the total weight of each lower beam into account.

As you can see, for each example, there are two positions marked A and B where I have forgotten whether they should be an X or a Y.

Please write a program a function which will accept the above diagram as input and output which of X and Y belong in each of the two positions A and B.

Your output should be something along the lines of A=X, B=X although any unambiguous output suffices e.g. you could output the diagram with the A and B substituted accordingly or you could modify the input in-place. You do not have to output values for X or Y, although for each diagram they always have a fixed ratio which will allow all beams to balance.

Other input formats could be acceptable but they need to get suggested as comments to the sandbox post.

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

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

Posted: Prime Power Switch

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

Sandbox Question

Do people think this is worth posting, given it only really requires a prime check along with getting digit prefixes? There are multiple implementations (possibly including hard-coding in some languages) to consider which might be enough. Please vote!


Produce all 83 base-ten right-truncatable primes in as few bytes as possible in the language of your choice.

  • Order is irrelevant, but the production must terminate.
  • You may produce a list, a set, or an equivalent object.
  • You may print them (e.g. space-separated, each on a line, or formatted as a list or set (e.g. {2; 3; 293; 5; ...})
  • You may give the numbers themselves as strings.
  • You may produce an iterator (but evaluating it must terminate).

Right truncatable primes

A right truncatable prime is a prime for which removing any number of trailing decimal digits is also prime.
For example, \$7193\$ is a right truncatable prime since \$719\$, \$71\$, and \$7\$ are all prime.

There are only 83 such numbers in base-ten, when sorted they are:

[2, 3, 5, 7, 23, 29, 31, 37, 53, 59, 71, 73, 79, 233, 239, 293, 311, 313, 317, 373, 379, 593, 599, 719, 733, 739, 797, 2333, 2339, 2393, 2399, 2939, 3119, 3137, 3733, 3739, 3793, 3797, 5939, 7193, 7331, 7333, 7393, 23333, 23339, 23399, 23993, 29399, 31193, 31379, 37337, 37339, 37397, 59393, 59399, 71933, 73331, 73939, 233993, 239933, 293999, 373379, 373393, 593933, 593993, 719333, 739391, 739393, 739397, 739399, 2339933, 2399333, 2939999, 3733799, 5939333, 7393913, 7393931, 7393933, 23399339, 29399999, 37337999, 59393339, 73939133]

This is A024770 in the Online Encyclopedia of Integer Sequences.


For some mathematician-written* Python see https://youtu.be/f2lEB4nMmyI.
* Fair warning, it might well make you cringe.

| |
\$\endgroup\$
  • \$\begingroup\$ I don't really mind prime challenges, just that most people who have been here a while have a stigma against it. Related. \$\endgroup\$ – Razetime Sep 5 at 14:26
  • \$\begingroup\$ The code in the link contains what appears to be a partially censored racial slur, so I think you should probably drop the youtube reference. \$\endgroup\$ – FryAmTheEggman Sep 9 at 21:32
  • \$\begingroup\$ Otherwise I think this is probably interesting enough, as these primes have several other non-prime features. It might be problematic if too many answers are just primality checks wrapped in terminating loops, though? \$\endgroup\$ – FryAmTheEggman Sep 9 at 21:35
  • \$\begingroup\$ @FryAmTheEggman Oh wow, I didn't notice; that's pretty sad. \$\endgroup\$ – Jonathan Allan Sep 9 at 22:15
1
\$\begingroup\$

Move the Knight!

Your knight is on (0, 0) on an infinite (to all of the four edges, not just two) chessboard, and you need to move it to (a, b). You can use arbitrary (but finite) number of moves to do that. Since the chessboard is infinite, you can use squares with negative coordinates.

Since you only have 2 knights (if no promotion occured) to type the program, your program needs to be as short as possible.

Input

The input is two integers, a and b.

Output

You output a sequence of characters, each represents a move. There are eight directions to move, so your output should contain eight distinct characters, each represents one direction. They can be any eight characters, as long as they are all unique.

Test Cases

The characters used here is:

 A B
C   D
  N
E   F
 G H
0 0 -> ""
1 1 -> "GD" or "DEGD" or "DG" etc.
3 3 -> "DDDGGG" (one possible version)
2 3 -> "FGD"

Rules

  • Standard Loopholes are forbidden.
  • This is , so shortest code wins.
| |
\$\endgroup\$
  • \$\begingroup\$ @Razetime I did... "They can be any eight characters, as long as they are all unique." \$\endgroup\$ – null Sep 15 at 12:30
  • \$\begingroup\$ oh, sorry about that. \$\endgroup\$ – Razetime Sep 15 at 12:31
  • \$\begingroup\$ @Razetime I intend to make this challenge have many different, unique, interesting approach, and which one is shorter highly depends on the language. \$\endgroup\$ – null Sep 15 at 12:33
1
\$\begingroup\$

Do my data follow Benford's law or a uniform distibution?

Background

Benford's law, also known as the law of anomalous numbers, describes the distribution of the leading digit in many numerical data sets. Let \$X\$ be the leading digit of an observation (in base 10). According to Benford's law, \$P[X=i]=\log_{10}(1+\frac1i)\$ for \$i=1\ldots 9\$.

For instance take the yearly reputation change of the top 1000 users on CGCC. For a user with reputation change 3522, keep only the leading digit, 3. Repeat this for all users, and you get this distribution, which is far from uniform:

enter image description here

This has been shown to apply to vary different data sets, from town populations to stock prices, and is used to detect tax and election fraud.

On the other hand, for some other data sets, the distribution of the leading digit is a uniform distribution: \$P[X=i] = \frac19\$ for \$i=1\ldots 9\$.

Given some observed frequencies \$(f_i)_{i=1\ldots 9}\$, we shall measure the distance to these two distributions using the sum of the errors in absolute value: \$\sum_i \left|f_i-\log_{10}(1+\frac1i)\right|\$ and \$\sum_i\left|f_i-\frac19\right|\$, respectively.

Task

Take as input a list of non-zero numbers. For each number, keep only the leading digit, which is defined as the first non-zero digit. Compute the observed frequencies of leading digits, and output one of two values, depending on whether the observed frequencies are closer to Benford's law or to a uniform distribution.

Input

Input format is flexible. Note that input may include negative values, as well as non-integers.

Output

Either two consistent values, one for Benford's law and one for the uniform, or a truthy/falsey value.

Test cases

To be added

This is , so shortest answer in bytes wins.

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

Finding the densest crossword puzzles

I love crosswords, and nothing beats a super densely packed puzzle. But how dense can the puzzles get?

Here's a sample puzzle I made a few years ago:

enter image description here

Certainly not great, but can we do better?

Given any list of characters, a crosswordification of that list is a crossword puzzle consisting of characters from that list. For example, given the list ['b','a','d','a','d'], the following is a valid crosswordification:

enter image description here

but this isn't

enter image description here

Clearly, the order of the list is irrelevant.

Given a valid crossword, the area of the crossword is the area of the smallest rectangle containing the crossword. In the above examples, the smallest rectangle containing the crosswords are 3x3 squares, which have area 9.

Challenge

In this challenge, you must write a function which takes two arguments

  • A list-like structure containing english characters

  • A list-like of valid words consisting of english characters

and outputs an integer, representing the minimal area of a crosswordification of the list of english characters, where the second input defines the set of valid words.

I will be using this english dictionary for my test cases. Any code that is used to import/parse the dictionary into a list-like structure won't be counted in the byte-count, just the function.

Test Cases

More to be added:

['d','a','a','a','t','n','m'] -> 7 (adamant is a word)

['k','a','s','a'] -> 6
| |
\$\endgroup\$
  • \$\begingroup\$ Here's what I understand: Our programs need to calculate the smallest possible corssword from the given characters, display the size alone. correct? \$\endgroup\$ – Razetime Sep 17 at 5:04
  • \$\begingroup\$ @Razetime correct \$\endgroup\$ – Don Thousand Sep 17 at 13:51
  • \$\begingroup\$ Do you suspect there is any other way to do this apart from brute forcing all possible arrangements and picking the minimal area one that meets the requirements? \$\endgroup\$ – Sisyphus Sep 18 at 4:40
  • \$\begingroup\$ @Sisyphus yes, but not revealing, as thats part of the challenge \$\endgroup\$ – Don Thousand Sep 18 at 11:17
1
\$\begingroup\$

Posted.

| |
\$\endgroup\$
  • \$\begingroup\$ "one or more of the options for the longest palindromic run of digits in its binary representation can be removed" Does this mean I can remove several runs? For example, 945770 = 11100110111001101010_2 has 110011 as the longest palindromic run, it occurs twice and if I remove both occurrences, the result is 10101010. On the other hand, 944522 = 11100110100110001010_2 has 110011 and 001100 as longest palindromic runs, and removing both gives 10101010. \$\endgroup\$ – Zgarb Sep 12 at 10:25
  • \$\begingroup\$ Don't forget Dennis, Dennis 2.0 or Calvin numbers :P \$\endgroup\$ – caird coinheringaahing Sep 12 at 15:37
  • \$\begingroup\$ @Zgarb No; you should only remove a single run before splitting the remaining digits. I've clarified this in the challenge text. \$\endgroup\$ – sporeball Sep 13 at 0:50
1
\$\begingroup\$

Posted

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I think the notation is fine, you could let people use any 4 distinct characters instead. You should mention that gravity is tward the center of the pattern. \$\endgroup\$ – Razetime Sep 18 at 2:33
  • 1
    \$\begingroup\$ left/right/up/down is more suitable for dominoes, I think. I don't know how walls and splits would change this, but go for it if you're fine with lesser answers. finding if a target domino falls is a different question altogether. \$\endgroup\$ – Razetime Sep 18 at 2:35
  • \$\begingroup\$ @Razetime There's no gravity, the example just happened to go towards the center. The direction relies solely on the pieces (I'll clarify that) \$\endgroup\$ – user Sep 18 at 17:09
  • \$\begingroup\$ You mix a lot of terminology about the directions, i.e. using "north" and "below" in the same description. I think you would be better off editing the descriptions to all use the same convention. Separately, truthy and falsy aren't really good terms to use, since some languages don't have a concept of truth. I'd recommend saying something like "one consistent value for true and anything else for false or the reverse", or something similar. \$\endgroup\$ – FryAmTheEggman Sep 18 at 18:10
  • 1
    \$\begingroup\$ Related, outputting the result after dominoes fall in 1D. \$\endgroup\$ – xnor Sep 18 at 20:56
  • \$\begingroup\$ @FryAmTheEggman I started out with just north/south/east/west, and then changed it after Razetime's comment. I guess I left out some parts. I will change the falsy/truthy part too \$\endgroup\$ – user Sep 18 at 23:39
1
\$\begingroup\$

Secret ">" Stacking Challenge: cheating

Sequel to Secret ">" Stacking Challenge: grading. You can skip the whole Background section if you already read the first one.

Background

Tetris Grand Master 3 has a hidden grading system based on the shape of the stack at the end of the game, which is called Secret ">" Stacking Challenge. It consists of entirely filling the lowest rows except for the zigzag pattern which starts at the left bottom cell and spans the entire width:

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

The board is graded by how many lines follow this exact pattern from the bottom line. Note that the topmost hole in the pattern must be blocked by an extra piece of block. If you consider the #s and .s as the mandatory pattern (blanks can be anything), you can get the score of 19 only if the exact pattern above is matched from the bottom line. Analogously, if the board matches this pattern

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

but not

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

then the score is 4.

For this challenge, consider a board of arbitrary size (other than 20 cells high and 10 cells wide). We can grade the board for the same pattern: for example, if the board has width 4, this is the pattern for score 3:

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

and this is the pattern for score 10:

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

Challenge

Given the board width and the desired score for Secret ">" Stacking Challenge, pick a sequence of tetrominoes and generate the sequence of moves that will achieve the score. The Tetris moves can be represented in any ways that clearly specify where each tetromino is placed in which orientation, optionally along with the board state after each placement.

For the Tetris movement rules, we use simple permissive rule as in this challenge: you can place a tetromino anywhere (even in closed rooms), as long as it doesn't float in the air or overlap with existing pieces. Therefore, if you plan to use coordinates, you need to specify both x and y coordinates (the y coordinate should be counted from the bottom, as the board can grow upwards without bound).

You can assume the width is at least 5 and the score is nonzero. You should theoretically support arbitrarily high score. The generated sequence doesn't need to be minimal.

Standard rules apply. The shortest code in bytes wins.

Output example

For board with 6 and score 2, one possible way is as follows: (As are the tetromino placed at each turn, # are existing pieces on the board, and . are empty cells)

......  ......  ......  ......  ......
A.....  #.....  #.....  .AA...  .##AA.
AA....  ##AA..  ####AA  #.AA..  #.##AA
.A....  .#AA..  .###AA  .#####  .#####

The above is a valid output format (you can choose any distinct chars/values in place of .A#). The following is also valid (although it is less obvious, it is indeed an unambiguous description of tetromino placements):

......  ......  ......  ......  ......
A.....  ......  ......  .AA...  ...AA.
AA....  ..AA..  ....AA  ..AA..  ....AA
.A....  ..AA..  ....AA  ......  ......

And this: (tetromino code, rotation, x and y coordinates from bottom left, 0 indexed)

S 1 0 0
O 0 2 0
O 0 4 0
Z 0 1 1
Z 0 3 1

And anything in between (e.g. showing tetrominos as a canonicalized matrix instead of a code).


Meta

  • For the output format, I originally thought of requiring to output the sequence of board states after each placement, in the sense of but allowing and all frames to be output at once. Do you have a better suggestion for output format?
| |
\$\endgroup\$
1
48 49
50
51 52
99

You must log in to answer this question.

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