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

2915 Answers 2915

1
47 48
49
50 51
98
1
\$\begingroup\$

Compress a grandmaster chess position

Background

Compress a position from a grandmaster chess game to as few bits as possible on average. A strong submission will probably use that these positions come from real games by top players, and so will make chess sense and strategic sense, rather than just being random legal chess positions. As illustration, a study found that grandmasters do well at memorizing positions from real games using "chunking" but with only perform at novice level memorizing random boards.

The is related to but different from Smallest chess board compression, which scores on the worst-case scenario, and Smallest chess game compression, which compresses full games. (Sandbox: Let me know if this is too similar)

Task

You must write a compressor, which maps a chess position onto a sequence of bits, and a decompressor that returns its to the original position. You can vary the length of the bit sequence by position, and this will likely be important to getting a good score.

The position to compress will just be a the placement of pieces on the chess board. You do not to encode whose move it is, castling rights, or en-passant. It will be given in FEN string format with only the piece placement part, for example:

2krn2r/pppb4/4pq2/3pN2p/5P2/2PBP3/PP4P1/R2QK2R

The chess position for this FEN

Each letter corresponds to a piece (pawn="P", knight="N", bishop="B", rook="R", queen="Q", and king="K"). White's pieces use uppercase letters and Black's are lowercase. Slashes separate the descriptions of each of the rows from top to bottom, that is the 8 files doing from 8 (where black's pieces start) to down to 1. Numbers are used for blocks of that many empty spaces that are horizontally adjacent.

Scoring

You will be scored on the average length of your compressed bit sequence on 10,000 random game positions. They will chosen at random from games played by grandmasters, restricted to move 5 or later. [Will work out more details when generating this data.]

This Pastebin (TODO) contains 10,000 FEN strings to use as a training set that you can use to get a preliminary score. The final score will be based on a separate secret test set of 10,000 FEN strings.

Your code must correctly decode every game in the position. Be sure that it can handle all positions, such as ones with weird underpromotions, which might appear in the test set but not the training set. (Sandbox: How to handle submissions that break this? A default penalty score for games failed? Ask to resubmit?)

Your compression and decompression must complete within 5 minutes on all the games. (Sandbox: Allow to compress all games at once? Do one game at a time but store state to allow "learning"? Include a memory limit?)

The length of your code is immaterial to this challenge.

| |
\$\endgroup\$
  • \$\begingroup\$ How long (in number of positions) would a naive program that hardcodes all of the (recorded) existing grandmasters games be? (if that's not large enough, it would make the challenge trivial) \$\endgroup\$ – user202729 May 17 at 11:49
  • \$\begingroup\$ @user202729 That's a good question, I definitely don't want code to be use that the test set comes from an actual database, so I'd either needed to make that non-viable or ban it. \$\endgroup\$ – xnor May 17 at 12:31
  • \$\begingroup\$ Does the time requirement have to be as strict as 30 games per second? (a certain question of the part also mentions "every game in the position", I assume that's a mistake) (I have no idea how to prevent storing a database of grandmaster games though) \$\endgroup\$ – my pronoun is monicareinstate May 17 at 16:00
  • \$\begingroup\$ @myp I think that this requirement means that it can compress each game in 5 minutes. \$\endgroup\$ – user202729 May 18 at 0:50
  • \$\begingroup\$ @user202729 I had meant total for all the games, but I'll probably loosen it. \$\endgroup\$ – xnor May 18 at 2:19
1
\$\begingroup\$

Permutation primes

A permutation prime is a prime such that at least one of its uniquified permutations (not equal to itself) of its digits is a prime.

Given a number, check if this number is a permutation prime.

Reference program

Here is a reference program I made.

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

The golfing skills are strong with this one

Task

Consider the base string s = "The golfing skills are strong with this one", an adaptation of the quote "The force is strong with this one" by Darth Vader, an infamous character of the Star Wars saga (sandbox, am I correct?).

You have to output the string s with as many characters as there are bytes in your source code. If your code is longer than s, extend s by concatenating it repeatedly as many times as needed.

Your program must be non-empty.

Input

You may or may not take the string s as input for your program. (Sandbox, maybe it is more interesting to not allow the string as input?)

Output

A string as specified in the Task.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Many languages, 0 bytes. PHP and /// polyglot, 1 byte: T. If the code is too long, is the string really intended to be The golfing skills are strong with this oneThe golfing skills are strong with this oneThe golfing skills are strong with this one? \$\endgroup\$ – my pronoun is monicareinstate May 20 at 16:42
  • \$\begingroup\$ @mypronounismonicareinstate do you see a problem with the string being like that? What would you suggest? Also, probably should not allow the string to be used as input and require a non-empty program \$\endgroup\$ – RGS May 20 at 16:46
  • 1
    \$\begingroup\$ That is perfectly acceptable, it's just that the transitions aren't very smooth (oneThe). If you can take the string as input, solutions won't have to depend on this specific string, so it would probably be a bad idea. (I mean, a[:5] isn't a very interesting answer) \$\endgroup\$ – my pronoun is monicareinstate May 20 at 16:51
  • \$\begingroup\$ @mypronounismonicareinstate I failed to understand what variation you think is a bad idea. Do you think it is a bad idea to accept it as input or a bad idea to not accept it as input? \$\endgroup\$ – RGS May 20 at 16:52
  • \$\begingroup\$ I think it is a bad idea to accept it as input. \$\endgroup\$ – my pronoun is monicareinstate May 20 at 16:53
1
\$\begingroup\$

Halting problem for simplified Brainfuck

Given a simplified Brainfuck program, you must determine whether it halts. Your program must always halt in finite time on valid inputs.

Simplified Brainfuck is a language that operates on a zero-initialized tape that is infinite in both directions. All cells contain integers from 0 to 255, and operations are performed modulo 256. There are the following instructions:

+ increment the current cell
- decrement the current cell
< move 1 cell to the left along the tape
> move 1 cell to the right along the tape
[ if the current cell is zero, skip past the next ]
] go to the previous [

Loops ([]) can't be nested.

This is tagged , so the shortest answer wins.

| |
\$\endgroup\$
  • \$\begingroup\$ Do you mean "Given a simplified Brainfuck program and an input of such program"? \$\endgroup\$ – Domenico Modica May 21 at 5:00
  • \$\begingroup\$ @DomenicoModica No, this language has no IO. Do you think I should mention that explicitly? \$\endgroup\$ – my pronoun is monicareinstate May 21 at 5:02
  • \$\begingroup\$ Oh, I don't know, I was too hasty ahahah... Anyway If the tape was finite surely it would be solvable \$\endgroup\$ – Domenico Modica May 21 at 5:07
  • \$\begingroup\$ I think it is indeed solvable with doubly infinite tape, since the region that the pointer touches within an iteration of a loop is limited (which means we have finite number of states in that region). It's pretty hard to describe the algorithm though. \$\endgroup\$ – Bubbler May 21 at 5:56
  • \$\begingroup\$ That is what I had in mind. Handling two loops in different directions is also non-trivial. \$\endgroup\$ – my pronoun is monicareinstate May 21 at 6:00
  • \$\begingroup\$ I don't think handling multiple loops is that non-trivial. Consider first loop first, the answer is false if it is infinite loop, otherwise run it to the end and run all commands before the second loop. Then consider the second loop just like the first, etc. \$\endgroup\$ – Bubbler May 21 at 6:49
  • 1
    \$\begingroup\$ Actually I think the challenge is not very interesting as[code-golf], because it's necessary to simulate the algorithm anyway and it can be proven (I think) that the number of steps the program takes (if it halts) is no more than \$2^{2^{2^{2^n}}}\$ (where n is the program length), so it will be no longer than an interpreter but takes impractically long to run. \$\endgroup\$ – user202729 May 22 at 8:48
  • \$\begingroup\$ @user202729 Is there proof of an upper bound of time? I feel it's unsolvable \$\endgroup\$ – l4m2 May 27 at 1:38
  • 1
    \$\begingroup\$ @l4m2 This is solvable because loops can't be nested. The body of each loops moves by a constant number of steps X, and if the program doesn't halt than it'll either repeat the same state twice (if X==0) or crosses the bound of the written tape part (because there's only a fixed number of written cells and then repeat states (there's only a finite number of cells touched by the loop body) \$\endgroup\$ – user202729 May 27 at 4:07
1
\$\begingroup\$

Posted: Stepping Through Time

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

Quickly calculate \$ n! \bmod p \$

The idea is extremely simple: Given two positive integers \$ n \$ and \$ p \$, calculate the result of \$ n! \bmod p \$, where \$ p \$ is a prime.

Scoring

Your score is the highest \$ p \$ you can achieve within \$ 10 \$ seconds, by running the program \$ 10 \$ separate times. More specifically, each run-through will contain two inputs \$ n \$ and \$ p \$. You are to solve \$ n! \bmod p \$, where \$ n \$ is a random number in the range \$[1, p]\$.

You must use this program to generate the \$ 10 \$ test cases. So for example, if \$ p = 13 \$, the test case would look like this:

n, p
9, 13
3, 13
10, 13
13, 13
7, 13
13, 13
8, 13
9, 13
6, 13
4, 13

Rules

  • Make sure that each test case is run separately, meaning you are not allowed to make use of previous test cases
  • Multi-threading is disallowed
  • Official times will be tested on my machine; make sure to include specifcations on how to run it

This is , so the highest score wins!

Sandbox

  • Any loopholes that need to be addressed?
  • Is there an easy, trivial solution to this?
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ To force independent calculation you should invoke the program 10 separate times. Although it remains possible to store data in files or similar, it would be pretty obvious. \$\endgroup\$ – user202729 May 22 at 8:58
  • 1
    \$\begingroup\$ As far as I know the best-known time complexity is asymptotically \$ \widetilde O (\sqrt p)\$, although the implementation is rather tedious and uninteresting. \$\endgroup\$ – user202729 May 22 at 9:00
  • 1
    \$\begingroup\$ Your example test case has p=10 which isn't prime \$\endgroup\$ – xnor May 22 at 10:31
  • \$\begingroup\$ @xnor Fixed, thanks. \$\endgroup\$ – dingledooper May 22 at 15:53
1
\$\begingroup\$

Cheat activated

Background

The game Grand Theft Auto: San Andreas went down to history also thanks to its wide selection of cheats. They're almost 90 and anyone who has ever touched this game, no doubt he tried them all!
One cheat is activated (on PC) typing in-game a secret keyword, and then boom, a jet pops out of thin air or perhaps all pedestrians look like Elvis Presley or some other rowdy effect...

They always come with this confirmation message:

enter image description here

Rockstar choosed to store them hashed, so due to collision, in addition to the intended ones there are many other strings that trigger every cheat.

Therefore I propose to solve this downside!

Task

Write a full program that prints CHEAT ACTIVATED if and only if the last part of a string is a cheat code.

Cheat codes

THUGSARMOURY
PROFESSIONALSKIT
NUTTERSTOYS
INEEDSOMEHELP
TURNUPTHEHEAT
TURNDOWNTHEHEAT
PLEASANTLYWARM
TOODAMNHOT
DULLDULLDAY
STAYINANDWATCHTV
CANTSEEWHEREIMGOING
TIMEJUSTFLIESBY
SPEEDITUP
SLOWITDOWN
ROUGHNEIGHBOURHOOD
STOPPICKINGONME
SURROUNDEDBYNUTTERS
TIMETOKICKASS
OLDSPEEDDEMON
DOUGHNUTHANDICAP
NOTFORPUBLICROADS
JUSTTRYANDSTOPME
WHERESTHEFUNERAL
CELEBRITYSTATUS
TRUEGRIME
ALLCARSGOBOOM
WHEELSONLYPLEASE
STICKLIKEGLUE
GOODBYECRUELWORLD
DONTTRYANDSTOPME
ALLDRIVERSARECRIMINALS
PINKISTHENEWCOOL
SOLONGASITSBLACK
FLYINGFISH
WHOATEALLTHEPIES
BUFFMEUP
LEANANDMEAN
BLUESUEDESHOES
ATTACKOFTHEVILLAGEPEOPLE
LIFESABEACH
ONLYHOMIESALLOWED
BETTERSTAYINDOORS
NINJATOWN
LOVECONQUERSALL
EVERYONEISPOOR
EVERYONEISRICH
CHITTYCHITTYBANGBANG
CJPHONEHOME
JUMPJET
IWANTTOHOVER
TOUCHMYCARYOUDIE
SPEEDFREAK
BUBBLECARS
NIGHTPROWLER
DONTBRINGONTHENIGHT
SCOTTISHSUMMER
SANDINMYEARS
KANGAROO
NOONECANHURTME
MANFROMATLANTIS
LETSGOBASEJUMPING
ROCKETMAN
IDOASIPLEASE
BRINGITON
STINGLIKEABEE
IAMNEVERHUNGRY
STATEOFEMERGENCY
CRAZYTOWN
TAKEACHILLPILL
FULLCLIP
IWANNADRIVEBY
GHOSTTOWN
HICKSVILLE
WANNABEINMYGANG
NOONECANSTOPUS
ROCKETMAYHEM
WORSHIPME
HELLOLADIES
ICANGOALLNIGHT
PROFESSIONALKILLER
NATURALTALENT
OHDUDE
FOURWHEELFUN
HITTHEROADJACK
ITSALLBULL
FLYINGTOSTUNT
MONSTERMASH

Input

  • A string \$s\$ over the alphabet:
    [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]

Output

  • Print CHEAT ACTIVATED if there exist a cheat code \$c\$ such that \$c\$ is a suffix of \$s\$
  • Nothing otherwise

This is , so the shortest code wins.

| |
\$\endgroup\$
  • \$\begingroup\$ Do we have to output the specific Cheat activated string, or just a truthy/falsy value indicating whether or not a valid cheat code exists? (I also don't think \$i\$ is a good name for a string; is that intentional?) \$\endgroup\$ – my pronoun is monicareinstate May 21 at 4:27
  • \$\begingroup\$ @my pronoun is monicareinstate Yes, that specific string, it's a little simulation. And yes, you're right \$s\$ is the canonical name, I choose "i" for input, but never mind \$\endgroup\$ – Domenico Modica May 21 at 4:39
  • 1
    \$\begingroup\$ I think that restricting the output to Cheat activated is unnecessary since it doesn't really add anything to the challenge. Consider allowing just a truthy or falsey value as output. \$\endgroup\$ – math junkie May 21 at 19:01
  • \$\begingroup\$ @math junkie I'm aware that in terms of logic it's useless. But that comes if only the "recognition part" is considered being the intended challenge. From my idea, generating Cheat activated it's also a part of it... I worded it badly in the task part \$\endgroup\$ – Domenico Modica May 21 at 20:08
  • 1
    \$\begingroup\$ 18HOLES is in the cheat codes list, yet the input states that there will be no number. Is this intended? \$\endgroup\$ – dingledooper May 22 at 21:20
  • \$\begingroup\$ @dingledooper No, my mistake, I thought I had removed it in the last edit \$\endgroup\$ – Domenico Modica May 22 at 23:07
1
\$\begingroup\$

Convert an integer to Chinese numerals

Your task is to convert an integer from 1 to \$10^{52}-1\$ (inclusive).

The characters from 1 to 10 with their Unicode code points are:

一 1 U+4E00
二 2 U+4E8C
三 3 U+4E09
四 4 U+56DB
五 5 U+4E94
六 6 U+516D
七 7 U+4E03
八 8 U+516B
九 9 U+4E5D
十 10 U+5341

Number greater that that are composed like this:

十一 11
十二 12
...
二十 20
二十一 21
二十二 22
...
百 100
百一 101
...
百十 110
...
百九十九 199
二百 200
...
九百九十九 999
千 1000
...
九千九百九十九 9999
一万 10,000

This is where it gets interesting, because numbers bigger than 10,000 are groups in groups of four, expressed with 十, 百 and 千. These are the powers we're going to use in this challenge:

十 10 U+5341
百 100 U+767E
千 1000 U+5343
万 10^4 U+4E07
億 10^8 U+5104
兆 10^12 U+5146
京 10^16 U+4EAC
垓 10^20 U+5793
秭 10^24 U+79ED
穣 10^28 U+7A63
溝 10^32 U+6E9D
澗 10^36 U+6F97
正 10^40 U+6B63
載 10^44 U+8F09
極 10^48 U+6975

Let's go through an example with 123456789123456789 as the input (other algorithms are possible)

  • identify groups of four digits, starting from the right: 12,3456,7891,2345,6789
  • convert each group: 十二 三千四百五十六 七千八百九十一 二千三百四十五 六千七百八十九
  • insert the appropriate multipliers: 十二京三千四百五十六兆七千八百九十一億二千三百四十五万六千七百八十九

Notes

  • A leading ー MAY be dropped before 千 and 百 and MUST be dropped before 十.

IO format

The input can be an integer in any reasonable format. You can use a string/sequence of characters or a number type, if your language supports it. 128-bit numbers are not large enough, by the way.

Testcases

input output
1 一
2 二
3 三
4 四
5 五
6 六
7 七
8 八
9 九
10 十
15 十五
20 二十
31 三十一
100 百
123 百二十一
1000 千
8346 八千三百四十六
10000 一万
50010 五万十
100000 十万
123456789123456789 十二京三千四百五十六兆七千八百九十一億二千三百四十五万六千七百八十九
1234567891234567891234567891234567891234567891234567 一千二百三十四極五千六百七十八載九千百二十三正四千五百六十七澗八千九百十二溝三千四百五十六穣七千八百九十一禾予二千三百四十五垓六千七百八十九京一千二百三十四兆五千六百七十八億九千百二十三万四千五百六十七

Standard code-golf rules apply. The shortest code in bytes wins.

References

| |
\$\endgroup\$
  • \$\begingroup\$ I assume this is meant to be code-golf? While the tag is technically enough, I think it is better to have a brief inclusion of that in the body of the challenge. \$\endgroup\$ – FryAmTheEggman May 29 at 18:44
  • \$\begingroup\$ @FryAmTheEggman yes it should be codegolf. \$\endgroup\$ – corvus_192 May 29 at 19:41
  • \$\begingroup\$ It'd be helpful if you include the code points for the Unicode characters. \$\endgroup\$ – Surculose Sputum May 29 at 21:13
  • 1
    \$\begingroup\$ As someone who is actively learning Japanese, they're called Chinese numerals because they were taken from China's numeral system. Japanese numerals are a whole different, extremely complicated thing. \$\endgroup\$ – Ethan Slota May 29 at 21:51
  • \$\begingroup\$ "A leading ー MAY be dropped before 千 and 百". They MUST be dropped in Sino-Korean numerals, tho. \$\endgroup\$ – Dannyu NDos Jun 1 at 4:07
  • \$\begingroup\$ What about 恒河沙, 阿僧祇, 那由他, 不可思議, and 無量大數? \$\endgroup\$ – Dannyu NDos Jun 1 at 4:12
  • \$\begingroup\$ Mathematica has IntererName[#, "Words", Language -> "Chinese"]&, but, unfortunately, it can't handle numbers this large :(. \$\endgroup\$ – my pronoun is monicareinstate Jun 2 at 11:55
  • \$\begingroup\$ Can we take input in base 10000? (Usually done when doing big integer multiplication with int32 so seems somehow reasonable) \$\endgroup\$ – l4m2 Jun 19 at 4:26
1
\$\begingroup\$

The Double-Castle Numbers™

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

Posted.

| |
\$\endgroup\$
  • \$\begingroup\$ Duplicate? \$\endgroup\$ – xnor Apr 30 at 4:04
  • \$\begingroup\$ @xnor it's more closely related, as this has the additional source restriction that programs must be a magic square. Also, diagonals don't matter. \$\endgroup\$ – Lyxal Apr 30 at 4:21
  • \$\begingroup\$ @dingledooper here's another example of when source code was required to be a magic square. I think your current scoring method is fine. \$\endgroup\$ – Lyxal Apr 30 at 4:23
  • \$\begingroup\$ Ah, my mistake. I'd suggest using saying other than Magic Square in the title given that the differences are substantial. \$\endgroup\$ – xnor Apr 30 at 4:48
  • \$\begingroup\$ @xnor Ok, I'll think of a better title! \$\endgroup\$ – dingledooper Apr 30 at 4:58
  • \$\begingroup\$ Can I use custom SBCS for the codepoints? Also, I don't see any reason to ban null bytes (and banning it will be banning a random feature in a golfing language). \$\endgroup\$ – Bubbler May 8 at 5:43
  • \$\begingroup\$ @Bubbler Sure, I've edited the question. \$\endgroup\$ – dingledooper May 8 at 6:03
1
\$\begingroup\$

Divide into 2 isosceles triangles

Given the measures of two of the interior angles of a triangle (x and y; the other angle can be easily calculated with 180 - x - y), draw a line segment that cuts this triangle into two isosceles triangles. You need to output the angle measures of both of your triangles.

However, because the base angles are the same, you only need to output the list [apex angle, base angle] of the divided triangles for both of the isosceles triangles. You can output the divided triangles in any order.

An example

Say your input is 100, 60.

Let's take a look at the complete triangle first. The triangle looks approximately like this.

   100

60            20

Now we try to divide one of the angles such that two divided triangles are both isosceles triangles.

       100

(40,20)           20

Now our bottom triangle is an isosceles triangle, since both of the base angles
of the bottom triangle are 20. The angle measures of the bottom triangle
looks approximately like this.

       140
20             20

Now, is the top triangle an isosceles triangle?

    100
          40
40

It is an isosceles triangle, because two of the angle measures are 40.

Therefore, for [100, 60], you need to output [[100, 40], [140, 20]].

Example cases

[20, 40] -> [[140, 20], [120, 40]]
[45, 45] -> [[90, 45], [90, 45]]
[36, 72] -> [[72, 36], [36, 72]]
[108, 36] -> [[108, 36], [36, 72]]
| |
\$\endgroup\$
1
\$\begingroup\$

Complete the landscape

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

Example Landscape

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

All tiles

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

Inconsistent tiles

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

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

0: Field
1: Road
2: City

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

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

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

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

Your task is to take in a rectangular matrix where every element save one is one of the 19 tiles given above. This landscape will be consistent, as defined above. You should take in this input and output the array that would represent the tile(s) which would be able to fill the single empty space in the input matrix, keeping the landscape consistent.

details to be added

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

King+queen vs king checkmate

You are given a chess position, represented either in FEN or as a two-dimensional diagram like this (the example test cases will be using the latter format):

...k....
........
...K....
.....Q..
........
........
........
........

In the examples, K represents the white king, Q represents the white queen, k represents the black king and . represents blank space. You may choose different consistent values instead of these characters. You may also input the diagram as a list of lists or in any other way that is allowed by default for two-dimensional arrays.

It is white's move. The position will always be reachable from the starting position by a sequence of valid moves.

You have to find the minimum number of moves White must do to checkmate Black, assuming perfect play by Black.

Test cases

Incomplete: too many test cases for 1 and no test cases for >1.

...k....
........
...K....
...Q....
........
........
........
........

Output: 1

k.......
........
..K.....
........
........
........
........
.Q......

Output: 1

k.......
..KQ....
........
........
........
........
........
........

Output: 1

| |
\$\endgroup\$
  • \$\begingroup\$ I know it would be a lot different, but have you considered the more general question that allows any (valid) disposition of the three pieces? Then the task would be to find the minimum number of moves to checkmate... Isn't it a bit "tautological" to input a position of which I already know it only takes one move to checkmate? -I most probably know also what this move is- \$\endgroup\$ – Domenico Modica Jun 8 at 16:02
  • \$\begingroup\$ Moreover if it happens to be only 1 move from checkmate (or also, if you want, if the moves can be all determined), with this broader task you could totally ask what this (these) move is (are). \$\endgroup\$ – Domenico Modica Jun 8 at 16:11
  • 1
    \$\begingroup\$ I think asking for the optimal depth to mate in White moves is a better question (far less simple than this, but still much less complicated than a proper chess engine); I'll change the proposal later; it's late here. \$\endgroup\$ – my pronoun is monicareinstate Jun 8 at 16:30
  • \$\begingroup\$ This is ambitious for code golf! Is the point to build an endgame tablebase? at least as much of it as is needed to solve the given test case positions? Test case: wKa1Qb2 bKf5 WTM wins in 10... \$\endgroup\$ – Rosie F Jul 19 at 19:28
1
\$\begingroup\$

Underfull \hbox (badness 10000)

Every TeX user has been warned many times that their hboxes are terribly underfull or overfull. So much badness! This challenge is to rate how badly underfull or overfull a line of text is for a simplified line wrapper.

Task

You're given a space-separated string or list of words. Output the minimal badness achievable for the first line.

The text needs to be wrapped on a line that's 10 characters wide, but it can only be split on spaces, no in the middle of words. Any letter that spills beyond the width counts for 1000 overfull badness each, and each leftover empty position at the end of the line counts for 1000 underfull badness.

Example

For input "Overfull hbox", we can keep the word "hbox" in the first line for 3000 overfull badness, or wrap it to the second line for 2000 underfull badness which is smaller, so the output is 2000.

0123456789

Overfull hbox
          ^^^
Overfull
hbox    ^^

Note that we don't care about badness of the second line.

Details

The input is a space-separated string or a list of words made of letters a-zA-Z. It won't have any words more than 10 letters long, or be more than 20 characters in total. It won't be empty or have any zero-length words.

Test cases

TODO


Sandbox: Is it OK to have a multiplier of 1000 for theme? Should the underfull and overfull badness penalties be different, like 1000 vs 2000?

| |
\$\endgroup\$
  • \$\begingroup\$ In my opinion, this might be a bit too simple for the big badness theme to be worth it. I feel like most golfing languages might spend nearly half their code multiplying by 1000 (throwing it together in Pyth, I got 1/4 used for multiplying). If it was say, the badness of each of the lines it might feel better. I don't feel terribly strongly about this though. \$\endgroup\$ – FryAmTheEggman Jun 9 at 20:52
  • \$\begingroup\$ @FryAmTheEggman That for the feedback. I'm now thinking the challenge is too simple overall, multiplier or not. What would you think of something like words being able to be broken at certain places in the middle, either explicitly marked or dervied from some property of the letters? \$\endgroup\$ – xnor Jun 9 at 21:14
  • \$\begingroup\$ I think some level of TeX uses hyphens to indicate possible word breaks, but they don't count for the length of words if unused. Adding that may help, while also being on theme? \$\endgroup\$ – FryAmTheEggman Jun 9 at 21:17
1
\$\begingroup\$

Lucky dice rolls

In pen and paper roleplaying games dice are used for various chance calculations. The usual way to describe a roll is \$n\textbf{d}k\$ where \$n\$ is the number of dice and \$k\$ is the number of faces on a die. For example \$3d6\$ means that you need to roll the classical 6-sided die 3 times (or roll 3 dice at the same time). Both \$n\$ and \$k\$ are positive integers.

Usually the values are then summed and they are used for various game mechanics like chance to hit something or damage calculations.

A lucky roll will mean that you have Fortuna's favor on your side (or against you). Luckiness is an integer number that increases (or decreases) the sum in the following way. The roll is modified to \${(n+|luck|)}\textbf{d}{k}\$ and the sum will be the \$n\$ best (or worst) values. Each die is fair, so they will have the same probability for the outcome of the possible values.

The \$luck\$ can be a negative number, in this case you need to get the \$n\$ worst values for the sum.

Input

The integer values for \$n,k,luck\$ in any way.

Output

The expected value for the sum of the (un)lucky roll. The expected value is \$\sum{x_{i} p_{i}}\$ where \$x_{i}\$ is the possible outcome of the sum and \$p_{i}\$ is the probability for \$x_{i}\$ occuring, and \$i\$ indexes all possible outcomes.

Examples

n,k,luck    expected value
1,6,0       3.5
2,6,0       7
2,6,-1      5.541666666666667
2,6,1       8.458333333333334
2,10,-1     8.525
2,10,1      13.475

Scoring

Shortest code in bytes wins.

Good luck! ;)

| |
\$\endgroup\$
  • \$\begingroup\$ Probably worth including a definition of expected value. To what precision should the output be determined? \$\endgroup\$ – Dingus Jun 10 at 12:50
  • \$\begingroup\$ @Dingus Is it now a bit more understandable? \$\endgroup\$ – Gábor Fekete Jun 10 at 13:29
  • 1
    \$\begingroup\$ Yes, that's good, though I'd suggest tweaking the wording a bit: 'The expected value is \$\sum x_ip_i\$ where \$x_i\$ is a possible value for the sum, \$p_i\$ is the probability of that sum occurring, and \$i\$ indexes all possible outcomes.' Perhaps I should rephrase my question about precision - what numeric formats are acceptable for output? Floats are obviously allowed, but do you require a certain number of decimal places? Is it acceptable to output rationals (for languages that support this)? What about 2 integers representing numerator and denominator, respectively? \$\endgroup\$ – Dingus Jun 11 at 12:13
  • \$\begingroup\$ hmm, that's a valid point, but I don't know which one it should be. \$\endgroup\$ – Gábor Fekete Jun 11 at 12:19
1
\$\begingroup\$

Iterate diagonally over nxn matrix

Given a matrix of size n, output the matrix into another matrix of size n such that:

  • the outputted matrix, when traversed diagonally,will result in the original matrix.

For example, taking this 3x3 matrix, we arrive at our solution: enter image description here

Which is checked by following the line beginning at 1: enter image description here

Specifications:

  • The matrix will always be square
  • You must output a grid with the same size as you were given (e.g. Not as a triangle)
  • Mark the end of each row with a delimiter such as \n or .

Examples:

Example 1

Input:

1 2 3
4 5 6
7 8 9

Output:

1 3 6
2 5 8
4 7 9

We can check the output by iterating over the array diagonally (follow the arrows for steps 1-5), which will give us the original matrix.

  ↗ ↗ ↗
1 ↗ ↗ ↗
2 ↗ ↗ ↗
3  4 5 

Example 2

Input:

a b c d
e f g h
i j k l
m n o p

Output:

a c f j
b e i m  
d h l o
g k n p

We can check this by iterating the array in steps 1-7 which outputs the given array.

  ↗ ↗ ↗ ↗
1 ↗ ↗ ↗ ↗
2 ↗ ↗ ↗ ↗
3 ↗ ↗ ↗ ↗
4  5 6 7

Hint:

Looking at the coordinates, we can see a pattern:

(0,0) -> (0, 1) -> (1, 0) -> (0, 2) -> (1, 1) -> (2, 0) -> (1, 2) -> (2, 1) -> (2,2)
| |
\$\endgroup\$
  • \$\begingroup\$ Do the matrices always consist of one character per cell? \$\endgroup\$ – Trebor Jun 19 at 0:45
  • \$\begingroup\$ they don't have to, but that can be a specification. Thoughts? \$\endgroup\$ – Peter S Jun 19 at 1:20
  • \$\begingroup\$ Perhaps the title could be a bit more descriptive, like "put the contents of a matrix into its antidiagonals". Then you could add a definition of the antidiagonals, and then a description of how you traverse the matrix to get the ordering for the antidiagonalization. \$\endgroup\$ – Giuseppe Jun 19 at 17:42
1
\$\begingroup\$

I am surely the fastest!... asymptotically

Posted.

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

Question posted here

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Suggested test case: [[[0,0,0],[0,1,0],[0,0,0]],[[0,1,0],[1,0,1],[0,1,0]],[[0,0,0],[0,1,0],[0,0,0]]] → 30 (empty cube surrounded by cubes, so some surfaces don't get painted despite being bordered by an empty cube). \$\endgroup\$ – fireflame241 Jul 13 at 17:17
  • \$\begingroup\$ @fireflame241 That's a cool test case! I was thinking of tricky cases, and that's a good one. \$\endgroup\$ – Don Thousand Jul 13 at 19:08
  • \$\begingroup\$ Comment: Actually, when the cubes are allowed to be disconnected, the physical interpretation no longer makes sense (how can the 6 cubes move together despite there's nothing to hold them together?... // That also makes the challenge much harder (requires flood fill to determine the answer) \$\endgroup\$ – user202729 Jul 14 at 7:28
  • \$\begingroup\$ @user202729 I'm not sure I see the issue. The entire object can be floating, and then paint fills the room. \$\endgroup\$ – Don Thousand Jul 14 at 12:05
  • \$\begingroup\$ That's just a general comment, not an issue with the challenge. \$\endgroup\$ – user202729 Jul 14 at 12:10
  • \$\begingroup\$ @user202729 Are you recommending I restrict the challenge to connected objects? \$\endgroup\$ – Don Thousand Jul 14 at 12:36
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\$ – Ad Hoc Garf Hunter 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\$ – Ad Hoc Garf Hunter 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\$ – Ad Hoc Garf Hunter 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\$ – 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
47 48
49
50 51
98

You must log in to answer this question.

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