567
\$\begingroup\$

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

Sandbox FAQ

Posting

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

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

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

Discussion

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

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

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

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

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

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

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

\$\endgroup\$
0

4469 Answers 4469

1
71 72
73
74 75
149
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\$
4
  • \$\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, 2020 at 5:04
  • \$\begingroup\$ @Razetime correct \$\endgroup\$ Sep 17, 2020 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, 2020 at 4:40
  • \$\begingroup\$ @Sisyphus yes, but not revealing, as thats part of the challenge \$\endgroup\$ Sep 18, 2020 at 11:17
1
\$\begingroup\$

Posted.

\$\endgroup\$
3
  • \$\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, 2020 at 10:25
  • \$\begingroup\$ Don't forget Dennis, Dennis 2.0 or Calvin numbers :P \$\endgroup\$ Sep 12, 2020 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, 2020 at 0:50
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\$
9
  • \$\begingroup\$ Can the answers be in different langauges? \$\endgroup\$ Jul 20, 2020 at 4:03
  • 1
    \$\begingroup\$ What is the motivation for the number 95? \$\endgroup\$ Jul 20, 2020 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, 2020 at 9:15
  • 1
    \$\begingroup\$ @fireflame241 Because there are 95 ASCII characters of course... \$\endgroup\$
    – DELETE_ME
    Jul 21, 2020 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, 2020 at 15:02
  • \$\begingroup\$ "I chose the character ?" -> "I chose the character #"? \$\endgroup\$
    – DELETE_ME
    Jul 22, 2020 at 6:10
  • \$\begingroup\$ "has to insert their picked x character into the previous source code," -> edit this part too. \$\endgroup\$
    – DELETE_ME
    Jul 22, 2020 at 6:11
  • \$\begingroup\$ @Dingus Now you may only insert y xs. \$\endgroup\$
    – user92069
    Jul 23, 2020 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, 2020 at 2:18
1
\$\begingroup\$

Bit delivery in Bin City

posted

\$\endgroup\$
3
  • \$\begingroup\$ It could help a lot to add an illustration for small test cases (how to move each bit in the input to the output), and some test cases with more bytes (both even and odd). Other than that, looks good to me. \$\endgroup\$
    – Bubbler
    Mar 31, 2020 at 1:57
  • \$\begingroup\$ @Bubbler Thanks for the feedback. How's it now? \$\endgroup\$
    – Noodle9
    Mar 31, 2020 at 14:32
  • \$\begingroup\$ Perfect, and +1 for reference implementation. \$\endgroup\$
    – Bubbler
    Mar 31, 2020 at 23:00
1
\$\begingroup\$

Find a 3-Language Polyglot

What I had in mind was that cops would create a polyglot with in 3 languages (languages A, B, and C). When run in A, the program would print the name of language B; when run in language B, the program would print the name of language C; and when run in C, it would print the name of language A.

Cops have to provide the names of these 3 languages, as well as their original polyglot's characters scrambled in no particular order. as well as a valid program in A that has the same behavior as the polyglot (prints the name of B). This program must be able to be created by deleting characters from the original polyglot, i.e., all the letters in it are included in the hidden polyglot.

Given the languages and the scrambled programand the sample program, robbers have to find the polyglot (or a polyglot that has the same behavior as the one the cop wrote).

Rules

  • Any language chosen must be able to be run on TIO, repl.it, ideone, or someplace else online. If the language is obscure, please provide a link to some such website.
  • Any language used must have documentation on Esolangs, Wikipedia, GitHub, or someplace else. Unless the language is very commonly used and has tons of tutorials everywhere, such as Java, Haskell, or C, please provide a link to documentation. Any feature used in the program must be included in that documentation - it shouldn't be something people have to dig through layers of source code to find.

Questions for meta:

  • Is this too easy/hard? Should I not include the extra A program? Should I only make it for 2 languages?
  • Is there anything unclear about the instructions? How can I improve the phrasing?
  • Should cops also give the length of their programs as an extra hint?
\$\endgroup\$
3
  • 1
    \$\begingroup\$ one thing to consider: you would need some way of restricting languages that are allowed. Otherwise people could just make up their own languages or use really, really obscure languages. \$\endgroup\$
    – thesilican
    Aug 18, 2020 at 23:04
  • 2
    \$\begingroup\$ IIRC, the usual way to limit the language list is to specify "the language should be on at least one of Wikipedia, TIO, or esolangs.org", though esolangs is already crazy these days. \$\endgroup\$
    – Bubbler
    Aug 19, 2020 at 5:05
  • \$\begingroup\$ @Bubbler Yup, I've edited my question with some restrictions now \$\endgroup\$
    – user
    Aug 20, 2020 at 15:01
1
\$\begingroup\$

TPK Algorithm

The TPK Algorithm was designed in 1977 Donald Knuth and Luis Trabb Pardo to show off the various functionality of languages at the time. Your task is to implement the most common version of the TPK algorithm. The pseudocode goes as follows (adapted from Wikipedia):

ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item N in sequence S
    call function F on N
    if the result is greater than 400
        print "TOO LARGE"
    else
        print result

F(N) results in sqrt(abs(N)) + 5 * pow(N,3)

F should be implemented as a function in your code, that is, there should be some subsection of you code which consists of a function that takes an input and outputs the result of F for that input. It is acceptable to round the square root operation down to the nearest integer.

Notes: if using decimal square roots, the first value greater than 400 is ~4.301. For integer square roots, the first value is ~4.302. Your program does not need to support non-integer inputs.

This is , so fewest bytes wins!

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

Three points on Poincaré disk

What is Poincaré disk?

Poincaré disk is a projection of 2-dimensional hyperbolic geometry to the 2-dimensional Euclidean plane, or more precisely, onto the open disk \$\{(x,y): x^2 + y^2 < 1^2\}\$.

Objective

It is well-known that three distinct points on the Euclidean plane are either on a unique line or on a unique circle. Let \$S\$ be that line/circle.

The inverse image of \$S\$ is one of line, circle, horocycle, or hypercycle. Determine which.

Classification

The points are assumed to be on the disk.

  • If \$S\$ is a circle that lies on the disk, the inverse image is a circle.

  • Otherwise, if \$S\$ is a circle that shares a tangent with the boundary of the disk, the inverse image is a horocycle.

  • Otherwise, if \$S\$ crosses the boundary of the disk orthogonally, the inverse image is a line.

  • Otherwise, the inverse image is a hypercycle.

Input

The cartesian 2-dimensional coordinates of the points. A coordinate can be given as either two real numbers or one complex number. Other than that, the input type and format doesn't matter. This includes:

  • A tuple of size 3

  • A list of size 3

  • A set of size 3

Invalid inputs fall in don't care situation. This includes:

  • Not exactly 3 points

  • Non-distinct points

  • A point not on the disk

Output

Output type and format doesn't matter either. This includes:

  • Enumeration type of 4 possible values

  • Bit field of size 2

Example

Assuming there were no floating-point errors:

  • \$\{(-½,0),(0,½),(½,0)\}\$ must give a circle.

  • \$\{(-½,½),(0,0),(½,½)\}\$ must give a horocycle.

  • \$\{(-½,0),(0,0),(½,0)\}\$ must give a line.

  • \$\{(1-\sqrt{¾},½),(1-\sqrt{½},1-\sqrt{½}),(½,1-\sqrt{¾})\}\$ must also give a line.

  • \$\{(0,½),(¼,¼),(½,0)\}\$ must give a hypercycle.

  • \$\{(0,0),(¾,0),(0,¾)\}\$ must also give a hypercycle.

\$\endgroup\$
4
  • \$\begingroup\$ Can the coordinates \$(x,y)\$ be represented as a complex number \$x+yi\$? \$\endgroup\$ Oct 11, 2020 at 16:43
  • \$\begingroup\$ @cairdcoinheringaahing Yes. \$\endgroup\$ Oct 11, 2020 at 21:02
  • \$\begingroup\$ It looks like solutions might have trouble with the line and horocycle cases due to float precision, if either they take values like sqrt(2) to finite precision or introduce imprecisions in the calculations. Can some allowance be made for this? I'm not sure how though. \$\endgroup\$
    – xnor
    Oct 12, 2020 at 2:09
  • \$\begingroup\$ @xnor If the input is IEEE floating-point numbers, they are in \$\mathbb{Z}[½]\$ anyway and must be regarded as such. If your language is able to do symbolic computation, you may go ahead. \$\endgroup\$ Oct 12, 2020 at 3:15
1
\$\begingroup\$

Compactify the real numbers to a group (WIP)

Objective

Let \$X = \mathbb{R} \cup \{\infty\}\$. The \$\infty\$ is the point at infinity and doesn't have a signature.

Let \$Y = \{\exp(i\theta) : \theta \in [0,2\pi)\}\$, which is the unit circle on the complex plane.

Make \$X\$ a group by giving \$X\$ a binary operation, so there will exist a function \$f : X → Y\$ that is both an isomorphism and a homeomorphism.

Your code shall implement the binary operation. \$f\$ doesn't need to be implemented to a code.

Group

A set \$G\$ endowed with a binary operation \$*\$ is a group iff:

  • For every \$a,b,c \in G\$, \$(a * b) * c = a * (b * c)\$

  • There exists the identity element \$e \in G\$ such that for every \$a \in G\$, \$e * a = a * e = a\$

  • For every \$a \in G\$, there exists \$b \in G\$ such that \$b * a = a * b = e\$

\$Y\$ is a group, where the binary operation is the multiplication.

Isomorphism

Let \$*\$ denote the binary operation given to \$X\$.

A function \$f : X → Y\$ is an isomorphism iff:

  • \$f\$ is bijective

  • For every \$x,y \in X\$, \$f(x*y) = f(x) × f(y)\$

Note that once appropriate \$f\$ is identified, \$*\$ can be automatically defined as \$x * y = f^{-1}(f(x) × f(y))\$.

Topology

A subset \$A \subset X\$ is open iff, for every \$x \in A\$:

  • If \$x \in \mathbb{R}\$, there exists \$P \subset A\$ such that \$x \in P\$ and \$P\$ is an open interval

  • If \$x = \infty\$, there exists a subset \$P \subset A\$ such that \$x \in P\$ and \$P\$ is the union of two open rays to the opposite directions

A subset \$B \subset Y\$ is open iff, for every \$y \in B\$, there exists a subset \$Q \subset B\$ such that \$y \in Q\$ and \$Q\$ is an open arc.

Homeomorphism

A function \$f : X → Y\$ is a homeomorphism iff:

  • \$f\$ is bijective

  • For every open subset \$A \subset X\$, its image \$f[A]\$ is open in \$Y\$.

  • For every open subset \$B \subset Y\$, its inverse image \$f^{-1}[B]\$ is open in \$X\$.

Rule

You may represent \$\mathbb{R}\$ as a floating-point number. Every floating-point error will be tolerated in this regard.

Example

An example of \$f\$ is:

$$ f(x) = \exp(i × 2 \arctan \frac{x}{2}) $$

where \$\arctan \infty = \frac{\pi}{2}\$, and we identify \$*\$ as:

$$ x * y = 2 × \tan (\arctan \frac{x}{2} + \arctan \frac{y}{2}) $$

where the identity element is \$0\$, and the inverse element of \$x\$ is \$-x\$ when \$x \in \mathbb{R}\$, or \$\infty\$ if \$x = \infty\$.

Ungolfed solution

Haskell

This implementation abuses the fact that IEEE floating-point numbers can encode infinities. Both positive infinity and negative infinity will be treated the same in this regard.

import Data.Semigroup
import Data.Monoid
import Data.Group

newtype CompactR = CompactR Double deriving (Eq, Show, Read)

instance Semigroup CompactR where
    CompactR x <> CompactR y = CompactR $ 2 * tan (atan (x/2) + atan (y/2))

instance Monoid CompactR where
    mempty = CompactR 0

instance Group CompactR where
    invert (CompactR x) = CompactR (negate x)

You implement only <>. The others are just details.

Sandbox questions

This challange turned out to be too easy.

What if I asked about one-point compactification of \$\mathbb{C}\$ instead of \$\mathbb{R}\$?

\$\endgroup\$
1
  • \$\begingroup\$ I think even just f(x,y)=(x+y)/(1+xy) works for the real case \$\endgroup\$
    – xnor
    Oct 14, 2020 at 8:01
1
\$\begingroup\$

Convert hexadecimal to decimal

We have a lot of base conversion challenges. Surprisingly, aside from one closed challenge, there aren't any where the goal is purely to convert hexadecimal to decimal. This is different from challenges like converting hexadecimal to binary, because many languages have features like hexadecimal literals (0x, $, etc.) which can do this in a much shorter or more interesting way.

I/O:

You should create either a program or function, which takes input and output through one of the allowed methods. The input will be a hexadecimal number, consisting of the characters /[0-9a-f]/ (you may choose the capitalization rules).

Scoring:

This is code golf, shortest answer per language wins.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Feedback is of course useful. If the downvote is because this is a dupe or is unnecessary, that would be useful to comment on. Otherwise, I can't fix any issues without knowing what they are. \$\endgroup\$ Oct 17, 2020 at 21:11
1
\$\begingroup\$

Recolour my Table (Abandoned)

\$\endgroup\$
1
  • \$\begingroup\$ Maybe try limiting the table format. Is it top down or sideways? Also can we assume that the original table color (or slight variation to a certain HSL difference, maybe) is the majority of the image? \$\endgroup\$ Feb 6, 2020 at 19:50
1
\$\begingroup\$

Is a coincident point in a pair of rotated hexagonal lattices closest to the origin?

I've deleted from here because I agree it is takes too much time to understand at the moment.

Preface

This is a question where the technique must search or exclude from search all possibilities. As soon as I figure out how to pose it, there will be a separate question for mathematical techniques other than a simple search, so please don't use them here.

Below is quoted from Math SE determining if a coincident point in a pair of rotated hexagonal lattices is closest to the origin?:

A pair of hexagonal lattices with one scaled by the square root of a rational number \$r = \sqrt{\frac{m}{n}}\$ and then rotated will produce a variety of different hexagonal lattices of coincident points.

For the first lattice let

$$x, y = i+\frac{1}{2}j, \ \frac{\sqrt{3}}{2}j$$

and for the second

$$x, y = r\left(k+\frac{1}{2}l\right), \ r\left(\frac{\sqrt{3}}{2}l\right).$$

Per this and this helpful answer the squares of the distances to unit lattice points are given by Loeschian numbers (A003136) equal to \$i^2+ij+j^2\$ so in this case a point \$i, j\$ on the first lattice will coincide with a point \$k, l\$ on the second lattice once rotated by some amount if

$$n(i^2+ij+j^2) = m(k^2+kl+l^2).$$

For example if \$m, n = 13, 7\$ then both \$(i, j) = (5, 6)\$ and \$(6, 5)\$ will coincide with \$(k, l) = (5, 3)\$ at rotation angles of about 5.2 and 11.2 degrees as given by.

$$\theta = \arctan\left( \frac{\frac{\sqrt{3}}{2}l}{k+\frac{1}{2}l} \right) - \arctan\left( \frac{\frac{\sqrt{3}}{2}j}{i+\frac{1}{2}j} \right)$$

However, while the first solution is part of the hexagonal superlattice built on the much closer point \$(i, j), (k, l) = (1, 3), (1, 2)\$ the second point represents the shortest possible coincident distance and therefore a far lower density coincident lattice.

coincident hexagonal lattices

plotting script: https://pastebin.com/pZFCGXbE

Task

Given the rational number (m, n) e.g. (13, 7) and pairs of known coincident lattice points, e.g. (5, 6), (3, 5) or (6, 5), (3, 5) (besides the origin) we want to find out if this is one of the six closest coincident lattice points, or if it is a member of a coincident lattice with points closer.

  • If it's one of the six closest: return some flag letting us know there wasn't anything closer. You may also return either the same point, or one of the other five of identical distance.

  • If it isn't: return one of the six points that was closest along with (but not only) a flag letting us know that a closer point was found and the original point wasn't one of the closest. Reminder that this will be a closer point in a coincident lattice that also contains the original input.

Do this by some combination of searching/testing all possible pairs of lattice points (one from each lattice) to see if they are coincident and closer and potentially excluding blocks of combinations that don't need searching. The problem is finite because one only searches points that aren't obviously farther from the origin.

Feel free to use tricks to exclude large fractions from search as long as they rely on simple rules, for example a point near the origin in one lattice will never be coincident with a point near a distant point in the other.

But if you find yourself considering computations like matrix division or using Eisenstein integers or Euclid's algorithm in the complex plane please save that for the follow-up question.

This is so shortest code wins.

Input

  • Input will have six integers \$(m, n), (i, j), (k, l)\$ as described above, but can have any order or hierarchy, or additional (but uninformative) place holders (e.g. zero padding, blanks...)
  • \$(m, n)\$ will be positive, but the other four can be positive, negative or zero, excluding a \$(0, 0)\$ pair (the origin).

Recipe for making test cases

In addition to the two mentioned above (13, 7), (5, 6), (5, 3) and (13, 7), (6, 5), (5, 3) you can roll your own:

  1. Pick two Loeschian numbers \$L_1\$ and \$L_2\$ and find some integer pairs (i, j), (k, l) that can make them. (Find all integer pairs that produce a given Loeschian number)
  2. Make new pairs by choosing two nonzero integers \$a, b\$, then:

\begin{align} i' & = ai - bj\\ j' & = aj + b(i+j)\\ k' & = ak - bl\\ l' & = al + b(k+l). \end{align}

If \$i, j\$ and \$k, l\$ were coincident, then \$i', j'\$ and \$k', l'\$ will be as well.

(This just says that the coincidence lattice between two hexagonal lattices is also a hexagonal lattice.)

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

As a Web Frontend developer, I feel out of place most of the time coming here. And that is despite the existence of established challenges like One Div in the field of web development. But they aren't here, because objective criteria are hard to do. (Sparing more unkind reasons.)

Maybe the following would be a way to draw others. It's not a One Div challenge, but a way to set different web technologies against one another in a sort of code golf.

To give you an idea, compare these two Codepens:

(To be fair, thebabydino doesn't know at the time of writing there is a challenge, it was a spontaneous idea after seeing her code.)

It was rightly pointed out to me that capturing the idea of good coding practice will probably fail. But let me give you a vision: What if the challenges were not only about learning new coding tricks, but also about identifying the "cheats"?

There is a whole industry out there that tries to make objective rules to ultimately measure code quality. Their work is mostly to tilt against windmills. Maybe there is a way to make a playfull challenge a tool to identify new features for linters.

If good coding wins, so much better for it. If everyone thinks the winner was going squarely against the spirit of good coding practice, professionalism gains a discussion.

(Somehow this reminds me of the discussion about doping in sports.)

I hope to make the playing field understandable also to non-web people, so please bear with me if I add comments that would be obvious to everyone in the profession.

One goal here is performance. There are a lot of champions for the approach to minimize external dependencies loaded into the browser. I am trying to capture this with a "no external request" rule. This is not only about the size of files loaded but also the debt of interpreting extensive JS frameworks. Look at current discussions about web site performance, and you will understand what I am talking about.

Challenge: Recreate the image with web technologies

A real question would contain a raster image in any format. Most likely, they will be PNG or GIF (to show animations).

The code must be runnable on Codepen

You must create a pen and post its URL here. Your own authorship should be on a honors base. Anonymous pens are acceptable, but if your nick is the same here as there, you must use your account.

There are a good number of web development environments around, but they all offer different features. The criterium for selection was the ease to enforce the "no external resources" rule - and popularity, of course.

In addition, the code must be posted in its entirety here.

No external code

The pen must not include any external sources.

  • No import statements in any language
  • no statements that trigger any external requests
  • no external stylesheets or scripts imported via the pen settings

An important case here is the use of JS frameworks that offer server-side rendering, or template languages like JSX. Should their source code be made legal? This sort of code is mostly undistinguishable from code used client-side, with the difference that it must be compiled before it is delivered to the client.

No base64-encoding

No part of the code should be unreadable at first glance. So neither HTML, nor CSS, nor JS are allowed to contain any base64-encoded strings

  • No data: URI that contains the base64 option
  • The use of atob() and btoa() in JS is ok, provided there is no string literal containing a base64-encoded string
  • The use of <canvas> and/or URL.createObjectURL() is certainly ok, provided there is no string literal containing a base64-encoded string
  • The use of Blob or ArrayBuffer to construct images is certainly ok.

The use of preprocessors is allowed

Any preprocessor that is offered by CodePen can be used. What counts for the solution is the source code in that language.

Using Babel as a preprocessor inside CodePen is ok, but the "no imports" rule applies just the same.

Currently the Babel preprocessor offered by CodePen has a fixed configuration. If that changes in the future, it might be valid or not to use an URI to an external config file or npm module or not. That is in the future. The basic idea here is "if it is executed on the server side, or by native browser code, go for it"

Linting must pass

To give languages a fair chance that rely on fixed indents, and to maintain readability, the Javascript part must pass ESLint without any warning or error.

  1. Which preset does the best to enforce good code quality? It was pointed out that there will probably remain a number of loopholes, but I would like to try to get them as few and obscure as possible.
  2. I am not so fluent with linters for other languages. Proposals?

No minification

All code should be pretty.

  • Running prettier must not change the code formatting

    This might not cover all languages. Please review and propose other/additional formatters.

  • No code line can be longer than 80 columns

Matching the source image

I have still to research that. My first instinct is to use ImageMagicks magick compare and set a cutoff value to account for antialiasing and rounding differences, but that does not solve how to capture animations. Maybe capture all frames with Lighthouse?

Wining criterium: aggregated Number of lines of code

The number of lines of source code in markup, stylesheet and script are added. The least number of lines wins.

  • Numbers are counted using sloc. Only the Source output value is relevant. For example on the command line

      sloc pen.css | grep Source
    

    is there a sensible way to scrape the code lines directly from Codepen? Or is this available on the site and I am simply not aware of it?

Please give your answer a header that qoutes the number of lines in each language separately.

\$\endgroup\$
9
  • \$\begingroup\$ While giving 'languages a fair chance' by enforcing no base64 and counting lines of code only is admirable, I think you will find that there are too many ways to cheese it. For example, I could write every line as eval('...' + '...' + '...') to escape minification. It might be better just to use a more conventional scoring criteria (bytes) and drop the base64/formatting requirements. \$\endgroup\$
    – Sisyphus
    Oct 22, 2020 at 2:56
  • \$\begingroup\$ I am not giving up on this so easily. If there is to be a challenge, it should be on the basis that is done with good coding practice. Otherwise, it just makes no sense. Linters should be able to catch a lot of the loopholes, and if not, at least this would be a way for others to learn about them. Isn't this also the goal of this community? My vision would be that if this gains popularity, Linter manufactureres look at "cheating" solutions for improvements to their product. \$\endgroup\$
    – ccprog
    Oct 22, 2020 at 12:06
  • \$\begingroup\$ @ccprog Unfortunately, "good coding practice" is a subjective thing, and we strive for objective scoring criteria. Most answers on the site will happily sacrifice things such as readability and good practice in order to reduce their score. \$\endgroup\$ Oct 22, 2020 at 13:00
  • \$\begingroup\$ @cairdcoinheringaahing Did you see my latest edit? Maybe this can be a productive goal in itself. \$\endgroup\$
    – ccprog
    Oct 22, 2020 at 13:01
  • \$\begingroup\$ @ccprog I was mainly responding to your comment, I was still reading through the full spec as I wrote that. I do very much like the idea of this challenge, and I think it should be fully able to do while still fitting within our site rules (objective scoring criteria etc.). I'm not too familiar with the topic of web technologies, so forgive any mistakes I may make, but one thing sticks out to me as needing improvement when reading this challenge: the attempts to cover things in all languages. Usually, we tend to avoid language-specific challenges on the site, but I think this would be a (cont) \$\endgroup\$ Oct 22, 2020 at 13:05
  • \$\begingroup\$ (cont) good example of where limiting the language would help rather than harm the challenge. From my understanding, it looks as though restricting answers to Javascript would allow you to make the challenge much more objective with the rules about minification and base64, as you won't have to worry about edge cases in esoteric languages such as Jelly or ><> that are commonly used on the site. \$\endgroup\$ Oct 22, 2020 at 13:07
  • \$\begingroup\$ That, on the other hand is unrealistic. Most Javascript code nowadays is somehow cross-compiled, either from other languages (for example the Typescript superset) or through the use of frameworks (Angular, React). I'll have to think more about th "no imports" rule here, as one of the banes of current web development is that a lot of devs loose the sight of whether their code is executed server or client side. \$\endgroup\$
    – ccprog
    Oct 22, 2020 at 13:15
  • \$\begingroup\$ As far as esoteric languages are concerned, there is an implicit stop gag: Forcing Codepen as execution environment. If the language isn't supported there,, the answer fails. And believe me, Codepen is an industry tool, not just any website. Every post there is considered to be a showcase for the developer and counts for his/her professional reputation. \$\endgroup\$
    – ccprog
    Oct 22, 2020 at 13:21
  • \$\begingroup\$ @ccprog I actually have no problem with the challenge as specified. I just think that the winning solutions will cheat the tool(s) you use to score. But if that's ok with you, I don't mind this challenge at all, and will look forward to see the answers. \$\endgroup\$
    – Sisyphus
    Oct 23, 2020 at 1:07
1
\$\begingroup\$

Get the Systematic Chemical Symbol

posted

\$\endgroup\$
2
  • \$\begingroup\$ "prints the corresponding chemical symbol." → "prints the corresponding systematic chemical symbol." \$\endgroup\$
    – Adám
    Oct 21, 2020 at 17:18
  • \$\begingroup\$ You should state clearly that taking a list of digits is also acceptable. \$\endgroup\$
    – Adám
    Oct 21, 2020 at 17:19
1
\$\begingroup\$

C Code Compressor (WIP)

Your task is to create a lossless compression scheme that is optimized for ASCII-only C code. Whitespace and indentation should be preserved.

Your score is the total compressed size of various samples from well known open source C projects. A sample of the largest few files will be taken from one specific commit. Both header files and source files will be included from the following projects:

  • The CPython Interpreter
  • The Linux Kernel
  • Git

Comments will be stripped from the source files for the set of scoring, therefore you do not need to optimize for comments, however you still need to handle them.

Three additional files will also be included in the corpus, which must be handled correctly, but do not contribute to your score:

  • A C source file with comments
  • A Python source file
  • A non-programming plain text file (probably a short story or poem from the public domain. Jabberwocky?)

Scoring

$$ Score = {C + D + L^2 \over O} $$

Where:

  • \$C\$ is the total size, in bytes, of the compressed text
  • \$O\$ is the total size, in bytes, of the original text
  • \$D\$ is the total length, in bytes, of all strings in any predefined dictionary
  • \$L\$ is the length, in bytes, of the longest string in any predefined dictionary

Lowest score wins

Predefined Dictionaries

(Needs refinement)

A predefined dictionary, for the purposes of this challenge, is a collection of predefined output strings of length 2 or greater which are baked into your encoding format.

  • An entry in a predefined dictionary must have at least two different characters to be counted in scoring, so repeating a single character \$n\$ times does not count as a dictionary entry.
  • Leading and trailing whitespace on a predefined string does not count as a distinct entry from one without matching leading or trailing whitespace

A predefined dictionary may, for instance, be helpful for keywords and common identifiers, but it is ultimately up to you what approach you take.

For instance, if you map \x80 to int and \x81 to float, your dictionary score would be \$8\$ for the total length, plus \$25\$ for the longest string (float), for a total of \$33\$. However, mapping runs of tabs and spaces to \xC0-\xFF would not count toward dictionary size in this case.

Rules

  • Standard rules and loopholes apply.
  • Although scoring only depends on how well you can compress C, your algorithm needs to work even when the input text is not valid C; it must work for all ASCII input text.
  • Your algorithm must be deterministic, meaning it should always produce the same compressed text every time for any given input, regardless of external factors such as time.
\$\endgroup\$
4
  • \$\begingroup\$ Once you reveal the test cases, couldn’t I just create an “encoding” where 1 represents the Linux kernel, 2 represents the Git source, etc? And if the test cases aren’t fixed but can change if an answer overfits some, then is there really an objective winning criterion? \$\endgroup\$ Oct 10, 2020 at 7:26
  • \$\begingroup\$ @water_ghosts Optimizing exclusively for the test cases given is one of the standard loopholes \$\endgroup\$
    – Sara J
    Oct 10, 2020 at 13:02
  • \$\begingroup\$ Are you planning on scoring based entirely on compression amount, or also on code size? Seems like it will be a fun challenge, especially is code size is part of it. \$\endgroup\$ Oct 10, 2020 at 22:05
  • \$\begingroup\$ @RedwolfPrograms I've done a compression challenge before and I found that making code size a part of the score got in the way of making things interesting since it typically encouraged calling out to gzip since that takes way fewer bytes than making an actual algorithm. I might consider a code size limitation or work in dictionary size into score though. \$\endgroup\$
    – Beefster
    Oct 28, 2020 at 15:56
1
\$\begingroup\$

Is It A Rainbow Color

Posted in main

\$\endgroup\$
11
  • \$\begingroup\$ "obviously not an index" isn't so clear. Is 7 "obviously not an index" if we use 0-based indexing? \$\endgroup\$
    – Adám
    Oct 27, 2020 at 23:09
  • \$\begingroup\$ Adding to that: In some languages, -1 and false are valid indices. \$\endgroup\$
    – Adám
    Oct 27, 2020 at 23:10
  • \$\begingroup\$ Ok updated it to make it a bit more definitive. \$\endgroup\$
    – Scott
    Oct 27, 2020 at 23:35
  • \$\begingroup\$ Doesn't this give an unfair advantage to languages that use -1 for "not found" when asking for an index? Other languages give the next index after the last valid index. \$\endgroup\$
    – Adám
    Oct 27, 2020 at 23:37
  • \$\begingroup\$ What would you suggest then? I feel no matter what, there's always going to be some languages that are better suited to a particular challenge. I tried to offer as many ways as possible for handling invalid input to be more language-inclusive. \$\endgroup\$
    – Scott
    Oct 28, 2020 at 0:40
  • 1
    \$\begingroup\$ Well, let's take a step back and look at the essence of the challenge. There are two things: a look-up, and the compression of the words. I'd focus on one, i.e. either let "not found" have undefined behavior, or simply be a cover for look-up (given a list and a value, find the index, or … if not found). Since the latter is probably too boring, go with the simple lookup. \$\endgroup\$
    – Adám
    Oct 28, 2020 at 0:44
  • \$\begingroup\$ I strongly recommend removing the invalid-input case and just guaranteeing that the input is valid. It means answers don't have to store all valid inputs in some form to check against them, which gives rooms for more interesting methods of fingerprinting. \$\endgroup\$
    – xnor
    Oct 29, 2020 at 1:35
  • \$\begingroup\$ I feel like we've already have some challenge(s) about mapping a set of n strings to the numbers 1 through n, though I don't quite remember what they were or how to find them. The concept is a good one, but it may have been done already. \$\endgroup\$
    – xnor
    Oct 29, 2020 at 1:38
  • \$\begingroup\$ This is some valuable feedback. I agree that we've had some very similar challenges, how would it work if I rework the challenge to be something along the lines of this: output whether a given color is in the rainbow. The possible inputs would be pre-defined and output can be truthy/falsy \$\endgroup\$
    – Scott
    Oct 29, 2020 at 2:12
  • \$\begingroup\$ I can't help thinking this will boil down to a "let xnor find some magic trick that simplifies it significantly and then adapt it to every other programming language" challenge \$\endgroup\$
    – pxeger
    Oct 30, 2020 at 8:13
  • \$\begingroup\$ I think this actually should have good variety across languages. It's string-based, and different languages have various abilities to use regexes, hashes, conversion to code points, etc, that differ in relative length. This is in contrast to purely arithmetic ones where a single formula can be ported easily. \$\endgroup\$
    – xnor
    Nov 3, 2020 at 4:44
1
\$\begingroup\$

Fix the message on my calculator

My calculator has lots of mathematical buttons, but they're boring; it's much more fun to write messages using letters. You can access the letters of the alphabet with the ALPHA button which turns each button press into a corresponding letter which is noted above each key (or space, in the case of .).

My calculator looks like this*:

 A    B    C    D    E    F
log   ln   ^2  sin  cos  tan
-----------------------------
 G    H    I    J    K    L
 /    ->   (    )    ,   Esc
-----------------------------
 M     N     O
 7     8     9 
-----------------------------
 P     Q     R     S     T
 4     5     6     *     %
-----------------------------
 U     V     W     X     Y
 1     2     3     +     -
-----------------------------
 Z    (Space)
 0       .  

For example, to type HELLO I would press Esc cos -> -> 9 ..

However, recently my ALPHA button was broken, so I can't get to the letters any more. When I try to write a message, only the mathematical symbols get input.

Without ALPHA, the keys do the following:

  • The Esc key does nothing
  • The digit keys, ., (, ), ,, ->, +, -, *, and % enter those strings verbatim
  • The log, ln, sin, cos, and tan keys enter function_name() and place the cursor before the closing bracket
  • The / and ^2 keys enter a / or ^2 respectively, and then move the cursor to before the new symbol, iff the symbol preceding it is one of + - * % ( , ->

For the example above, instead of getting the message HELLO, I would get ->cos(9). Note that since the key for L (Esc) does nothing, it is unfortunately impossible to know that the letter L was pressed, and this information is lost.

Your task is to convert a string of maths operations into the correct text.

Rules

  • Some combinations are ambiguous; for example CGI, CIG, ICG all could have come from (/^2. In this case you can output any or all of them.
  • You should assume the input will always be a valid combination that could have been produced using the rules above.
  • You should never output Ls
  • You may output the string in any case, with an optional trailing newline, but no other extra whitespace.
  • This is . The shortest code in bytes wins.
  • Standard rules and loopholes apply.

Test-cases

More coming soon.

      Input                 Output
----------------------------------------
789                    MNO
log(ln(^2))            ABC
cos((cos((9)           EIEIO
-->-                   YHY
3.14159                W UPUQO
(/^2                   CGI or CIG or ICG
<empty string>         <empty string>

* The % and / keys are both for division on the original calculator, but labelled something like ÷ and ☐/☐. Here I've just replaced them with simple ASCII equivalents. (did you know that both % and ÷ represent a fraction?) Also, there are other keys not shown (including the mentioned ALPHA), but they don't matter for this challenge.


Meta

  • Any feedback or suggestions?
  • Is this clear enough?
  • I considered adding some regular expressions to show more clearly what the rules mean, but decided not to because I though that should be part of the challenge. Was this the right decision?
  • I will probably make another challenge that is the reverse of this - given a list of buttons that were pressed, produce the correct mathematical symbols. It might have made sense to post that challenge first as context for this one, but I thought this one is more interesting
  • Regarding ambiguity: I could change some of the syntax rules to reduce the ambiguity but it would make things a lot more complicated and it couldn't be removed completely without straying significantly from the behaviour of the original calculator
\$\endgroup\$
1
\$\begingroup\$

Set of subsets without subsubsets

You are given two integers \$n\$ and \$k\$, and are to output a random collection of \$k\$ sets \$\mathcal A_1,\ldots,\mathcal A_k\$ such that:

  • each \$\mathcal A_i\$ is a subset of \$\{1, 2, \ldots, n\}\$;
  • no \$\mathcal A_i\$ is a subset of another \$\mathcal A_j\$.

Any collection which satisfies these constraints should have positive probability of being output.

Input/output is flexible.

You may assume that there exists at least one collection which satisfies the constraint; by Sperner's theorem, this is equivalent to the condition \$k\leq \tbinom{n}{\lfloor n/2\rfloor}\$.

Example outputs

The output is random, so these example collections should merely have positive probability of being output.

| n | k | possible output
| 2 | 2 | { {1}, {2} }
| 4 | 3 | { {1}, {2,3}, {3,4} }
| 4 | 6 | { {1,2}, {1,3}, {1,4}, {2,3}, {2,4}, {3,4} }
| 5 | 3 | { {1,2,3,4}, {2,5}, {3,5} }

This is , so shortest code in each language wins.

\$\endgroup\$
3
  • \$\begingroup\$ What does random output do to benefit this challenge? Randomness just adds boilerplate and prevents some languages from competing. That doesn't make randomness bad universally, but it does suggest that there should be a reason you involve randomness. \$\endgroup\$
    – Wheat Wizard Mod
    Nov 28, 2020 at 21:07
  • \$\begingroup\$ @WheatWizard One alternative would be "output any collection of subsets which satisfies the constraints". But that challenge is trivial: it suffices to output k different subsets, all of size \$n\choose {n/2}\$; many challenges have a built-in for this. I included the randomness to sidestep this. \$\endgroup\$ Nov 28, 2020 at 22:35
  • 1
    \$\begingroup\$ @WheatWizard Thinking about it, I now realize there is another alternative: list all acceptable collections of subsets, rather than a random collection. That seemed more tedious to me when I wrote the proposal, but it might actually be better; I'll think about it. Thanks for the comment! \$\endgroup\$ Nov 28, 2020 at 22:37
1
\$\begingroup\$

(Pan)consummate Vs

An integer \$v\$ is said to be consummate if there is an integer \$n\$ and a base \$b\$ such that \$n\$ divided by the sum of its base \$b\$ digits is equal to \$v\$.

An integer \$v\$ is said to be panconsummate if it is consummate in all bases \$b\geq 2\$. Panconsummate numbers are A058226 in the OEIS.

Your task:

Write a full program or function that takes a positive integer \$v\$ and returns two distinct, consistent values, one if \$v\$ is panconsummate, and the other if \$v\$ is not. However, the sum of your code's bytes must be panconsummate as well. Your code must work theoretically for any integer.

Truthy values:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 18, 20, 21, 23, 24, 31, 34, 36, 37, 39, 40, 43, 45, 53, 54, 57, 59, 61, 69, 72, 73, 77, 78, 81, 85, 89, 91, 121, 127, 144, 166, 169, 211, 219, 231, 239, 257, 267, 271, 331, 337, 353, 361, 413, 481, 523, 571, 661, 721, 1093, 1291, 3097

Falsey values:

13, 16, 17, 19, 22, 25, 26, 27, 28, 29, 30, 32, 33, 35, 38, 41, 42, 44, 46, 47, 48, 49, 50, 51, 52, 55, 56, 58, 60, 62, 63, 64, 65, 66, 67, 68, 70, 71, 74, 75, 76, 79, 80, 82, 83, 84, 86, 87, 88, 90, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 122, 123, 124, 125, 126, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 167, 168, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200

Note that panconsummate numbers \$v>3097\$ must be at least \$10^6\$, and the OEIS speculates that the truthy values above are all panconsummate numbers.

.

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

The Slices Puzzle Puzzle

Background

Slices is a puzzle game. Placed on a 2d map is a set of islands; possibly just a single island. Placed on each island is a set of points. The task is to draw a number of straight lines across the islands such that no point can be reached from another without crossing one of the drawn lines, or leaving an island. In other words, you partition the points with lines such that each partition contains at most one point on each island. For each level, you are given a maximum number of lines that can be drawn.

In the game illustrated below, drawing a straight line between the first and second row of points, and then a line between the second and third row of points, would create a valid partition of points.

Game illustration

Task

Your task is to write a solver for this game. The solver takes as input a set of islands, the set of points for each island plus the maximum number of lines which can be drawn. The input and output may be represented in any way, and the input may be hard-coded. Hard-coded input must show that your solution is sufficiently general. Any format will be accepted. For instance, you might implement this as a linear programme in the CPLEX format -- I haven't verified that this is possible -- or you might write some sort of brute force solution in in an imperative language. Maybe some other declarative solution works even more nicely.

Grading

Solutions will be judged by popularity. Things such as number of bytes in the solution, computational complexity (justify this if you want) and elegance could be considered.

\$\endgroup\$
10
  • \$\begingroup\$ 1) Should the lines (separating the points) be straight lines? 2) Allowing hardcoded input is different from our I/O defaults, and may interfere with code golf scoring. 3) Complexity is often hard to measure, and elegance is not an objective winning criterion. My suggestion is pure code-golf, pure fastest-code, or maybe popularity-contest. (For fastest code, you'll need to prepare some test cases, and get ready to run all submissions on your own machine. This is how we achieve objective scoring for speed.) \$\endgroup\$
    – Bubbler
    Dec 10, 2020 at 8:13
  • \$\begingroup\$ @Bubbler The lines should be straight. I would like to allow hard-coded inputs, as this makes it possible to submit a nice linear programme if that is possible. I think I will go for popularity given that there are so many interesting dimensions. I will update the question with this in mind. \$\endgroup\$
    – justinpc
    Dec 10, 2020 at 11:01
  • \$\begingroup\$ @Bubbler What do you think about the task now? \$\endgroup\$
    – justinpc
    Dec 10, 2020 at 11:06
  • 1
    \$\begingroup\$ Regardless of the challenge type, you need to provide some test cases for verifying submissions - at least a couple of easy levels and a couple of harder ones, maybe some that requires drawing lines at unexpected angles. \$\endgroup\$
    – Bubbler
    Dec 11, 2020 at 2:44
  • \$\begingroup\$ @Bubbler Will do. \$\endgroup\$
    – justinpc
    Dec 11, 2020 at 6:51
  • \$\begingroup\$ Computational geometry problems have a lot of nuance. e.g are the points in general position, or can they be collinear? Can a cut just touch a vertex, or must it actually cross an edge? Is an island just the convex hull of its points, or is it given as a polygon? Are the convex hulls (resp. polygons) of the islands guaranteed to be mutually disjoint? \$\endgroup\$ Dec 11, 2020 at 22:49
  • \$\begingroup\$ @user1502040 I will clarify these questions. I would like to make the representation of the solution as general as possible. Can you clarify what you mean by "Can a cut just touch a vertex, or must it actually cross an edge". By edge, do you mean edge of an island? Lines should not intersect with vertices. I should clarify that lines are not line segments, and that they should extend to infinity. \$\endgroup\$
    – justinpc
    Dec 12, 2020 at 5:59
  • \$\begingroup\$ @justinpc Sorry, I can see how that was confusing. I meant the conceptual edge joining two points in the same island. \$\endgroup\$ Dec 13, 2020 at 0:56
  • \$\begingroup\$ @justinpc I know most of your feedback has been discouraging, but I think this would be a fun challenge. Don't be nervous about posting it! \$\endgroup\$ Jan 3, 2021 at 22:25
  • \$\begingroup\$ @user1502040 You're right. It would be a fun challenge. I have been busy recently, and would like to put time into this when I have a spare minute. \$\endgroup\$
    – justinpc
    Jan 4, 2021 at 11:27
1
\$\begingroup\$

Given a list of strings like this (input):

["some test", "{", "some", "_subst", "ring}", "some", "other text"]

Need to combine all the elements in to one for the given substring (input).

For example:

substring = "{some_substring}"

The output list of strings will be

["some text", "{some_substring}", "some other text" ]

Here are few more possible lists of strings:

input_list = ['some test', '{', 'sub', 'string}', 'som other text']
input_list2 = ['some test', '{sub', 'string}', 'som other text']
input_list3 = ['some test', '{', 'sub', 'string}', 'som other text']
input_list4 = ['some test', '{', 'sub', 'string', '}', 'som other text']
input_list5 = ['some test {', 'sub', 'string', '}', 'som other text']
input_list6 = ['some test {', 'sub', 'string', '} som other text']

substring can be any text and it does not need to be wrapped in to round braces. If substring appears multiple times in the input string than it should be replaced as well.

Note: Elements of the string that do not contain part of the input string should be the same instances. So creating a new list from joned string will not work for this problem.

Let say these strings carry additional information like style. So removing or replacing them will remove style as well

Signature of expected function to better understand problem.

def join_variable(input_list, substring):
    # implementation
    return output_list
\$\endgroup\$
5
  • \$\begingroup\$ You need to specify a winning criterion (usually code-golf) \$\endgroup\$ Dec 22, 2020 at 17:00
  • \$\begingroup\$ Not exactly sure what do you mean. What kind of criterion? Can share some examples? \$\endgroup\$
    – Pol
    Dec 22, 2020 at 18:57
  • 3
    \$\begingroup\$ We don't host challenges where the goal is solve the problem. Rather, there must be a way to "score" solutions so they compete with each other. See why. \$\endgroup\$
    – Adám
    Dec 23, 2020 at 0:27
  • \$\begingroup\$ Got it. Alright then. Should I remove it? \$\endgroup\$
    – Pol
    Dec 23, 2020 at 13:34
  • 1
    \$\begingroup\$ You can use code-golf as a scoring criterion, I think - shortest code wins. It's the most commonly used tag here. \$\endgroup\$
    – user
    Dec 23, 2020 at 18:05
1
\$\begingroup\$

Map the alternating group A5 to the rotations of a dodecahedron

8 years ago, the Math Stack Exchange was able to prove, in 523 characters of arcane incantation, that the alternating group A5 (ie all rearrangements of five objects that can be created by swapping two objects an even number of times) is isomorphic to the group of rotations of a dodecahedron that map vertices to vertices, edges to edges, and faces to faces. In my mind, 523 characters is far too many -- we can do better!

Challenge

To solve this challenge, take as input a member a of A5, represented as an even permutation of the first 5 integers, and output a 3x3 rotation matrix that maps a dodecahedron to itself. Your program must be an isomorphism: This means that your program must output a unique rotation matrix for each element a, and for any elements of A5 a, b, c such that a composed with b yields c, then YourProgram(a) * YourProgram(b) = YourProgram(c) (to within floating point precision, of course). Shortest program wins!

Example Input and Output

We present as an example one valid isomorphism, but any valid isomorphism is a permitted answer.

Example Dodecahedron

We assosciate the colored cubes [red, green, yellow, blue, black] with the numbers [1, 2, 3, 4, 5]. Then, for each permutation a in A5, our example outputs a matrix that rotates the figure shown so as to permute the colored cubes according to a.

[1, 2, 3, 4, 5] -> [[1, 0, 0][0, 1, 0],[0, 0, 1]]

[2, 3, 1, 4, 5] -> [[0, 0, 1], [1, 0, 0], [0, 1, 0]] (a 120 degree rotation along the axis (1, 1, 1)

[3, 4, 1, 2, 5] -> [[-1, 0, 0], [0, 1, 0], [0, 0, -1]] (a 180 degree rotation along the y axis ie coming towards the viewer)

[4, 2, 3, 5, 1] -> [[-0.3090170, 0.5, 0.8090170] [0.5, 0.8090170, -0.3090170] [-0.8090170, 0.3090170, -0.5]]

(a 60 degree rotation along the vector (1 / phi, phi, 0)

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

Battleships Board Validation

Do you know the game Battleship? Well, I want to play with my little brother, but before we can begin we need to set up our ships on the board. This is your input.

Now, we need to check that the ships that we set up are valid. This is where you come in to help. Your task is to write a program or function which checks whether the given 2d array (your board/input) is a valid board or not.

The input will be a 2d array, where 1 represents part of a ship and 0 represents part of the ocean.

The rules:

  • There must be:
    • One battleship (size 4)
    • Two cruisers (size 3)
    • Three destroyers (size 2)
    • Four submarines (size 1)
  • Any additional ships are not allowed, and neither are missing ships
  • Each ship must be either vertical or horizontal (aside from submarines, which are a single grid space)
  • The ships cannot overlap, but may be adjacent

Solutions may not use streams.

in addition, you must solve this with a BF function (normally the class will also be called BF) which receives the 2d array(input) and uses a validate function. Afterward, you are free to manipulate the 2d array however you want and add any functions that you want.

here are some more examples that you can use to check your code: is valid:

 {1,1,1,1,0,0,0,0,0,0},
 {1,1,1,1,0,0,0,0,0,0},
 {1,1,1,1,0,0,0,0,0,0},
 {1,1,1,1,0,0,0,0,0,0},
 {1,1,1,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,0},
 {0,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,0,0},

wrong ships, result is false-

 {1,0,0,0,0,1,1,0,0,0},
 {1,0,1,0,0,0,0,0,1,0},
 {1,0,1,0,1,1,1,0,1,0},
 {1,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,1,0},
 {0,0,0,0,1,1,1,0,0,0},
 {0,1,0,0,0,0,0,0,1,0},
 {0,0,0,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},

missing ships, is false->

 {0,0,0,0,0,1,1,0,0,0},
 {0,0,1,0,0,0,0,0,1,0},
 {0,0,1,0,1,1,1,0,1,0},
 {0,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,1,0},
 {0,0,0,0,1,1,1,0,0,0},
 {0,0,0,0,0,0,0,0,1,0},
 {0,0,0,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},

check contact, is true->

 {1,1,1,0,0,0,0,0,0,0},
 {1,1,0,0,0,0,0,0,1,0},
 {1,1,0,0,1,1,1,0,1,0},
 {1,0,0,0,0,0,0,0,0,0},
 {1,0,0,0,0,0,0,0,1,0},
 {0,0,0,0,1,1,1,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,1,0,0},
 {0,0,0,0,0,0,0,0,0,0},

check another one with contact->

 {1,1,1,0,0,0,0,0,0,0},
 {1,1,0,0,0,0,0,0,1,0},
 {1,1,0,0,1,1,1,0,1,0},
 {1,0,0,0,0,0,0,0,0,0},
 {1,0,0,0,0,0,0,0,1,0},
 {0,0,0,0,1,1,1,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,1,0,0},
 {0,0,0,0,0,0,0,0,0,0},

check invalid, is false->

 {0,1,1,1,0,0,0,0,0,0},
 {0,0,0,1,1,1,0,0,0,0},
 {0,1,1,1,0,0,0,0,0,0},
 {0,0,0,1,1,1,0,0,0,0},
 {0,1,1,1,0,1,1,0,0,0},
 {0,1,0,0,0,0,1,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,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,0,0},

random board which is true->

{0,1,0,0,0,0,0,0,0,0},
 {1,1,1,1,0,0,0,0,0,0},
 {1,0,1,1,1,0,0,0,0,0},
 {1,1,0,0,0,0,0,0,0,0},
 {1,1,0,0,0,0,0,0,0,0},
 {0,1,0,0,0,0,0,0,1,0},
 {0,0,1,0,0,0,0,0,1,0},
 {0,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,1,0,0,0,0,0},
 {0,0,0,0,1,0,0,0,0,0},

Who's code will be the shortest byte solution that passes all these examples successfully?! Good luck. ;)

Any language is allowed, but I'd like to see an answer in Java especially.

Tags:

link to the original post- Validating a Battleship board

this also my first post that I am doing. Whats a good way to decide who is the winner and in what time frame? help would be appreciated

(any sidenotes on how to improve?anything needing clarity?)

\$\endgroup\$
13
  • \$\begingroup\$ Hi there, new person! I'm happy to see you using the sandbox first! Generally it is good to avoid language-specific challenges. Also, is there a particular reason you're making this a fastest-code challenge rather than code-golf? \$\endgroup\$
    – Beefster
    Jan 7, 2021 at 23:28
  • \$\begingroup\$ not really im just used to using java \$\endgroup\$
    – Rocky cohn
    Jan 8, 2021 at 6:15
  • \$\begingroup\$ not to sure overall what the challenge itself would be so any suggestions would be great \$\endgroup\$
    – Rocky cohn
    Jan 8, 2021 at 6:17
  • 1
    \$\begingroup\$ Hi there. Great first challenge! As others have mentioned, I would drop the Java code to allow all languages, and just give test cases (since I usually answer in Java and 05AB1E, I might still answer in Java when the challenge goes live though ;) ). As for the win-condition, I would suggest to use [code-golf], since it's the most used and popular, and probably most appropriate for this challenge as well. (Code-golf means to create a function/program as short as possible in terms of used bytes.) \$\endgroup\$ Jan 8, 2021 at 8:48
  • \$\begingroup\$ @KevinCruijssen would it still be good for me to leave the condition that the input is a 2d array into the BF function and must have the validate function? I think that it also makes it more challenging \$\endgroup\$
    – Rocky cohn
    Jan 8, 2021 at 8:58
  • 1
    \$\begingroup\$ @Rockycohn Input as a 2d array is indeed good. But I would remove the Java function and validate code completely and just allow all languages. You can still mention you prefer to see a Java answer especially, though. Here a pastebin what I would personally change it to as example. \$\endgroup\$ Jan 8, 2021 at 9:04
  • \$\begingroup\$ gotcha. did it thanks:) \$\endgroup\$
    – Rocky cohn
    Jan 8, 2021 at 9:19
  • 1
    \$\begingroup\$ That looks a lot better. :) I've upvoted and voted to re-open your challenge, since I saw you made the same edit there. \$\endgroup\$ Jan 8, 2021 at 9:52
  • \$\begingroup\$ would it be better to delete the main post repost it since the title has Java and I changed it to all languages? \$\endgroup\$
    – Rocky cohn
    Jan 8, 2021 at 10:18
  • \$\begingroup\$ Unless there's some rep constraint that I'm not aware of, you should be able to edit the title of the main post. There's no need to repost it. (Or just ping me so that I do the update myself if you're not allowed to for some reason.) \$\endgroup\$
    – Arnauld
    Jan 8, 2021 at 10:44
  • \$\begingroup\$ it doesn't seem to let me @Arnauld if you could remove "Java," from the post that would be great \$\endgroup\$
    – Rocky cohn
    Jan 8, 2021 at 10:46
  • \$\begingroup\$ Also, please note that you should not make assumptions about language features. You should remove things like Solutions may not use streams or you must solve this with a BF function. \$\endgroup\$
    – Arnauld
    Jan 8, 2021 at 10:46
  • 1
    \$\begingroup\$ Title updated. :-) \$\endgroup\$
    – Arnauld
    Jan 8, 2021 at 10:47
1
\$\begingroup\$

Solve a Cubic Equation

Input

  • Your program will take in the integer coefficients of the equation \$ax^3+bx^2+cx+d=0\$ as inputs (a, b, c, and d)
  • All solutions are between 1000 and -1000.
  • a is nonzero

Output

  • All real solutions of the input equation, with an accuracy of at least the thousandths place.

Rules

  • Built-in equation solver are not allowed
  • Native math libraries that do not solve equations may be used
  • If you have any questions, please ask in comment

Examples

Input:

1 2 3 4

Output:

-1.651

Another Valid Output:

-1.651 -1.651 -1.651

Input:

1 3 0 -1

Output:

-2.879 -0.653 0.532

Worked Example (C++) doesn't work with two roots

Try it online!

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
   double a,b,c,d;
   scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
   for(double i=-100;i<=100;i+=0.0001)
   {
      double j=i+0.0001;
      double y1=a*i*i*i+b*i*i+c*i+d;
      double y2=a*j*j*j+b*j*j+c*j+d;
      if(y1>=0&&y2<=0||y1<=0&&y2>=0)
      {
         double x=(i+j)/2;
         printf("%.3lf ",x);
      }
   }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I don't know why is the section with your code named "Worked Example", but it doesn't seem to solve the equation x^3 + x^2 = 0. \$\endgroup\$ Jan 10, 2021 at 11:36
  • \$\begingroup\$ I'd suggesting guaranteeing that a is nonzero so that quadratic or lower cases don't have to be handled. Or, possibly just guarantee a monic polynomial with a=1. \$\endgroup\$
    – xnor
    Jan 11, 2021 at 3:43
1
\$\begingroup\$

Win a K vs KQ endgame

Summary

The goal of this challenge is to create a program or function which will win a Chess game with a King and Queen against a lone King. The user will specify three squares, representing the locations of the computer's King, the computer's Queen, and the user's King. The computer will then a output a move which will eventually lead to checkmate.

Input/Output

The program or function will first take as input three squares, representing the locations of the computer's King, the computer's Queen, and the user's King (not necessarily in that order). It can be assumed that the input is a legal position.

Parsing input is not the point of this challenge, so all reasonable forms of input/output are allowed, including but not limited to

  • Strings with algebraic chess notation such as "Ke4" or "Qf6"

  • Triples representing pieces and coordinates such as ('K', 0, 2)

After three squares are taken as input, the computer outputs a single legal move. Behaviour on invalid input is undefined.

Requirements

This procedure must terminate using your program or function:

  • User sets up a legal KQ vs K position on a physical chessboard.

  • User inputs the board position. The computer outputs a legal move. If the move is a checkmate, STOP.

  • User makes the computer's move on the physical board.

  • User makes a legal move for the lone king on the physical board.

  • User goes to step 2 and repeats.

In other words, the computer must eventually win by checkmate, through repeatedly using your program or function.

Furthermore, from any legal starting position the checkmate must occur in 50 or fewer moves by the computer.

(Of course, a physical chessboard is in no way necessary to test the code; I only mentioned it to help visualize the procedure. The chessboard could just as well be visualized in the user's head.)

Possible test cases

The squares are given in the order: computer's Queen, computer's King, user's King

  • c2, h8, a1 (must avoid stalemate)
  • a1, a2, a8
  • a8, a1, e5

Rules

  • The checkmate must occur in 50 or fewer moves by the computer, but it does not need to be as fast as possible.
  • Chess libraries are not permitted.
  • Shortest program in each language (in bytes) wins.

Questions for sandbox

How can I word the rules better if they are not currently sufficiently clear?

\$\endgroup\$
11
  • \$\begingroup\$ 'It can be assumed that the input is a legal position from which it is possible to force checkmate in 50 or fewer moves.' It's always possible to force checkmate in a KQ vs K endgame (when the side with the queen has the move) in 10 moves or fewer. I wonder if you should consider lowering the 50-move limit? \$\endgroup\$
    – Dingus
    Jan 5, 2021 at 8:39
  • \$\begingroup\$ I don't want to lower the limit too much because it is conceivable that some good solutions might require more than 10 moves. \$\endgroup\$
    – 79037662
    Jan 5, 2021 at 14:20
  • \$\begingroup\$ Fair enough. I still think you should mention that mating in 10 moves is always possible, even if you allow for more. Right now the question reads as if the possibility of forcing checkmate in 50 moves is an assumption (which it is not). \$\endgroup\$
    – Dingus
    Jan 5, 2021 at 22:41
  • \$\begingroup\$ In a pedantic reading, 'The user will specify three squares' could be understood to mean that the same starting position (chosen by the user) is always used. Can you make it clearer that the program should work for any legal starting position (I assume this is what you intend)? \$\endgroup\$
    – Dingus
    Jan 5, 2021 at 22:42
  • \$\begingroup\$ @Dingus The fact that any position can be won in 10 or fewer moves isn't really relevant to the specification of the challenge, but if you think it improves the prompt I'll go ahead and add it. \$\endgroup\$
    – 79037662
    Jan 6, 2021 at 18:05
  • \$\begingroup\$ @Dingus I explain what I mean in the next section, and I'll be surprised if anyone reads this and thinks I meant to use the same starting position every time. \$\endgroup\$
    – 79037662
    Jan 6, 2021 at 18:08
  • \$\begingroup\$ I agree that the 10 moves doesn't affect the spec. Where I see the possible relevance is as an answerer, where I might keep that knowledge in the back of my mind as a reference point to focus my golfing strategy. To your Sandbox questions: 1. I won't offer a strong opinion either way, just an observation: banning libraries will likely lead to fewer answers. Library-based answers might be boring but voters tend to vote accordingly. 2. I agree that there's no reason to specify which side is which. \$\endgroup\$
    – Dingus
    Jan 6, 2021 at 22:26
  • \$\begingroup\$ @Dingus Thanks for your input. \$\endgroup\$
    – 79037662
    Jan 7, 2021 at 15:47
  • \$\begingroup\$ Disallowing chess libraries sounds alright, since there's only 3 pieces to account for. More complex problems have been answered without libraries, but many tend to use libraries since it's simply golfier and simpler. I think this question would benefit from fastest-code scoring, or something similar, rather than code-golf. \$\endgroup\$
    – Razetime
    Jan 8, 2021 at 11:13
  • 1
    \$\begingroup\$ I think fastest code would be tricky to test due to the potentially numerous user inputs needed per code run, and testing how short of a mate the programs can find is not really what I had in mind for this challenge. \$\endgroup\$
    – 79037662
    Jan 8, 2021 at 21:48
  • \$\begingroup\$ Just commenting since you requested, I think this is good. My only real disagreement was the interactivity and since you have changed it and the spec remains clear, it has my thumbs up for as much as that is worth. \$\endgroup\$
    – Wheat Wizard Mod
    Jan 12, 2021 at 2:27
1
\$\begingroup\$

Posted

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

Is this a narrow Thumb instruction?

ARM Thumb was originally a 16-bit only subset of the 32-bit ARM instruction set.

However, later versions added 32-bit "wide" instructions which were more flexible, and called the original, more restrictive 16-bit instructions "narrow" instructions.

The assembler now chooses between narrow and wide instructions automatically, depending on how the instruction was written. However, this meant that the syntax had to be changed to have specific rules.

Your job is to be this assembler.

However, the programs you parse are not that interesting; they will only ever consist of add and adds.

More specifically:

Your task is to write a function or program that will take an add/adds instruction, and return a truthy value if it is a valid narrow instruction, or a falsey value if it is not.

Syntax rules

  • ARM has 16 registers, r0-r12, r13 (aka sp), r14 (aka lr), and r15 (aka pc). For ease of parsing, we are going to refer to all registers by their number, instead of using the special register names.
  • Do note the names when reading the official docs, as there are a lot of special cases for sp and pc.
  • In Thumb mode, these are split into "Lo registers", which are r0-r7, and "Hi registers" which are r8-r15. Many instructions can only use Lo registers.
  • Many instructions use the same source register as the destination register, even if they are written with three operands.
  • add and adds are distinct instructions. adds affects the condition flags, while add does not. That is the difference, if you were wondering.

The following 6 forms are valid for narrow instructions (adapted from here):

  1. adds x, y, #imm: x and y must both be Lo registers, and imm is a 3-bit constant from 0-7.
  2. adds x, y, z: x, y, and z must all be Lo registers.
  3. add x, x, y: x and/or y must be Hi registers. Note that x is repeated twice.
  • We are ignoring the fact that ARMv6 relaxed this rule to keep it interesting.
  1. adds x, x, #imm: x must be a Lo register. imm is an 8-bit constant from 0-255. Again, note that x is repeated twice.
  2. add r13, r13, #imm: imm is a constant multiple of 4 in the range 0-508.
  3. add x, y, #imm: x must be a Lo register, and y must either be r13 or r15. imm is a constant multiple of 4 in the range 0-1020.

Everything else is either a wide instruction or not valid.

Other notes

Standard loopholes, everything must be self-contained, and you are only allowed to treat it as text. You can't feed it to an assembler (unless you include the assembler source code in the result, but.. why).

The input can either be a string argument or text from stdin.

You can assume the format will match the following format (all lowercase, separators being a single space):

{add or adds} reg, reg, {#imm or reg}

Where imm is a non-negative number in base 10 (yes, including zero).

As a regex pattern:

^adds? r([0-9]|1[0-5]), r([0-9]|1[0-5]), (#[0-9]+|r([0-9]|1[0-5]))$

Reference implementation

In case the rules are difficult to follow, here is a reference implementation I made in C. Yes, I deliberately overabstracted it to make you do all the work.

I resisted the urge to post the reference implementation in ARM Thumb assembly, as that would be genuinely evil. 😏

You will not need to do the same error checking I did here. You can always assume the string itself is valid. The error checks in the main function are mostly to show what CAN'T happen.

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <errno.h>
#include <inttypes.h>

struct thumb_add_insn {
    char opcode[5];
    uint32_t op1;
    uint32_t op2;
    char op3_prefix;
    uint32_t op3;
};

// Returns whether the opcode ID is adds.
static inline bool is_adds(const char *opcode)
{
    return strcmp(opcode, "adds") == 0;
}

// Returns whether this register ID belongs to a Lo register,
// specifically r0-r7.
static inline bool is_lo_reg(uint32_t reg_id)
{
    return reg_id <= 7;
}

// Returns whether this register ID belongs to a Hi register,
// specifically r8-r15.
static inline bool is_hi_reg(uint32_t reg_id)
{
    return reg_id >= 8;
}

// Returns whether the operand prefix is for an immediate
// value, specifically, '#'.
static inline bool is_imm(char c)
{
    return c == '#';
}

// adds x, y, #imm3
static bool is_form_1(const struct thumb_add_insn *insn)
{
    return is_adds(insn->opcode)
        && is_lo_reg(insn->op1)
        && is_lo_reg(insn->op2)
        && is_imm(insn->op3_prefix)
        && insn->op3 <= 7;
}

// adds x, y, z
static bool is_form_2(const struct thumb_add_insn *insn)
{
    return is_adds(insn->opcode)
        && is_lo_reg(insn->op1)
        && is_lo_reg(insn->op2)
        && !is_imm(insn->op3_prefix)
        && is_lo_reg(insn->op3);
}

// adds x, x, #imm8
static bool is_form_3(const struct thumb_add_insn *insn)
{
    return is_adds(insn->opcode)
        && is_lo_reg(insn->op1)
        && insn->op1 == insn->op2
        && is_imm(insn->op3_prefix)
        && insn->op3 < 256;
}

// add x, x, y
static bool is_form_4(const struct thumb_add_insn *insn)
{
    return !is_adds(insn->opcode)
        && !is_imm(insn->op3_prefix)
        && (is_hi_reg(insn->op1) || is_hi_reg(insn->op3))
        && insn->op1 == insn->op2;
}

// add r13, r13, #imm
static bool is_form_5(const struct thumb_add_insn *insn)
{
    return !is_adds(insn->opcode)
        && insn->op1 == 13
        && insn->op1 == insn->op2
        && is_imm(insn->op3_prefix)
        && insn->op3 <= 508
        && insn->op3 % 4 == 0;
}

// add x, y, #imm, y == r13 or r15
static bool is_form_6(const struct thumb_add_insn *insn)
{
    return !is_adds(insn->opcode)
        && is_lo_reg(insn->op1)
        && (insn->op2 == 13 || insn->op2 == 15)
        && is_imm(insn->op3_prefix)
        && insn->op3 <= 1020
        && insn->op3 % 4 == 0;
}

// Parses a Thumb add/adds instruction.
// Returns 1 if it is a narrow instruction, 0 if it is not,
// and -1 on an error.
int is_narrow_add(const char *str)
{
    // Note that you do not have to do error checking for the
    // competition.

    if (str == NULL) {
        errno = EINVAL;
        return -1;
    }

    // Allocate a 24 byte struct on the heap for good measure
    struct thumb_add_insn *insn = calloc(1, sizeof(*insn));
    if (insn == NULL) {
        return -1;
    }

    // Parse the instruction with sscanf.
    // {adds} r{0}, r{3}, {#}{3}
    if (sscanf(str, "%4s r%"SCNu32", r%"SCNu32", %c%"SCNu32,
               insn->opcode,
               &insn->op1,
               &insn->op2,
               &insn->op3_prefix,
               &insn->op3) != 5
       || (strcmp(insn->opcode, "add") != 0
          && strcmp(insn->opcode, "adds") != 0)
       || insn->op1 > 15
       || insn->op2 > 15
       || (insn->op3_prefix != 'r' && insn->op3_prefix != '#')
       || (insn->op3_prefix == 'r' && insn->op3 > 15)
    ) {
        errno = EINVAL;
        free(insn);
        return -1;
    }

    int ret;
    // Test against each of the forms
    if (is_form_1(insn)) {
        ret = 1;
    } else if (is_form_2(insn)) {
        ret = 1;
    } else if (is_form_3(insn)) {
        ret = 1;
    } else if (is_form_4(insn)) {
        ret = 1;
    } else if (is_form_5(insn)) {
        ret = 1;
    } else if (is_form_6(insn)) {
        ret = 1;
    } else { // not a match
        ret = 0;
    }

    free(insn);
    return ret;
}

Test cases

adds r6, r3, #0    // true, form 1
adds r0, r1, #7    // true, form 1
add r0, r1, #3     // false, must be "adds"
adds r0, r9, #1    // false, r9 is a Hi register
adds r0, r1, #9    // false, must be 0-7

adds r0, r0, r0    // true, form 2
adds r7, r1, r2    // true, form 2
adds r4, r4, r1    // true, form 2
add r7, r1, r2     // false, must be "adds"
adds r13, r14, r6  // false, r13 and r14 are Hi registers (this isn't even valid as a wide instruction)

adds r0, r0, #0    // true, form 3
adds r5, r5, #249  // true, form 3
add r6, r6, #31    // false, must be "adds"
adds r3, r3, #256  // false, must be 0-255
adds r8, r8, #72   // false, r8 is a Hi register

add r4, r4, r11    // true, form 4
add r8, r8, r5     // true, form 4
add r9, r9, r9     // true, form 4
add r14, r14, r12  // true, form 4
add r8, r9, r10    // false, Rd must be the same
add r1, r1, r0     // false, one must be a Hi register (we are ignoring the ARMv6 change)

add r13, r13, #0   // true, form 5
add r13, r13, #48  // true, form 5
adds r13, r13, #64 // false, must be "add"
add r13, r13, #17  // false, not a multiple of 4
add r13, r13, #512 // false, must be 0-508

add r0, r15, #0    // true, form 6
add r4, r13, #1000 // true, form 6
add r11, r13, #32  // false, r11 is a Hi register
add r2, r13, #4000 // false, must be 0-1020
adds r7, r15, #384 // false, must be "add"
add r3, r15, #127  // false, not a multiple of 4

Things you can safely ignore:

// String will never be empty
adds r1, r2 // don't worry about implicit middle operand
adds R4, #12 // same
adds r3, r3, #-3 // adding a negative is not even a thing
add r0, r0, r99 // the only registers are r0 - r15
add r13, r13, #0x32 // it is base 10
subs r1, r1, r2 // only add and adds need to be handled
add r2, r2, lr // you don't need to handle the special names
add r0, sp, #0 // same
add #3, r1, r1 // only the last one will be an immediate
adds r3, r3, 32 // all immediates are prefixed with #
ADDS R0, R0, R1 // everything is lowercase
adds        r2,     r3 , r4 // only one space
adds r2,r3,r4 // there will always be spaces
addeq r0, r0, r1 // no IT blocks
adds.n r0, r0, r1 // no manual width specifiers
add r1, r2, r3, lsl #8 // no barrel shifting

This is , so the shortest answer in bytes per language wins.

Proposed tags: and maybe but I think that is for things you must write in assembly, not parsing assembly itself.

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

Hanabi playing bot

Overview

Hanabi is a cooperative card game with limited communication. It won the German "Spiel des Jahres" award in 2013.

The game can be played by 2-5 players, each of which has a hand of 5 cards (4 cards for 4-5 players), which they can't see themselves, but the other players can. In each turn, you can either play or discard a card, or give one other player a hint about their cards.

Common goal is to play out the cards in each color in ascending order.

As this is a cooperative game, each answer needs to cooperate with other instances of itself.

I/O format

Option 1: stateless, for all languages

Your program is called once for each turn (and is supposed to terminate afterwards). It will receive the current game state via standard input, and reply with an action via standard output. Invalid output means this game is counted as forfeited (lost, 0 points).

Input

Input is a line-based ASCII-format, with a prefix indicating what kind of data it is. The last line of the input is the current turn number (see below). Input will be in this order:

  1. Meta-information: n: n = number of players (2 .. 5) y: you = own player id (1 .. n)

  2. visible cards of the other players:

    • c 1: cards for player 1
    • ...
    • c n: cards for player n

    The cards for you are omitted in the list (you don't see your own cards).

    Each card has a color (one of r, y, g, b, w) and a number (1 to 5), written like r1 or y5, comma-separated.

    Example: c 2: w4,y1,g2,r3 means that player 2 has a white 4, a yellow 1, a green 2 and a red 3, in this order, on her hand.

  3. Hints given about each player's cards, in a similar list:

    • h 1: hints for player 1
    • ...
    • h n: hints for player n

    For each card (in the same order as before), all hints are noted, in a comma-separated list. We also note negative information, i.e. when a card was present when a hint was given, but was not selected, by prefixing with !. For example 5 is a card which is known as 5 but of unknown color, w1 is a card which is known as a white 1, 3!y is a 3 which is known as not yellow, g!15 is a green card which is known as neither being a 1 nor 5.

    For example, h 2: ,y!2,2!yr,r means that for player 2, the first card is completely unknown (was taken after the last hint), the second card is known as yellow and as not a 2, the third card is known as a 2 which is neither red nor yellow, and the fourth card is known as red.

  4. p color: number – already (successfully) played out cards (one per line). Here we just note the highest card of each color.

    • p r: 2 means for red, the 1 and two were played out (i.e. red 3 is the next one to play).
    • p w: 0 means no white card was played out yet (i.e. the white 1 is the next one to play).
  5. d: – Discarded cards A list of all cards which were either intentionally discarded or unsuccessfully played out, comma-separated.

    For example, d: w3,b5,y2,y2 means that white 3, blue 5 and two yellow 2s were already discarded.

  6. game status information (each on one line, in this order): lh: number of hints left, ld: number of discards left (those two always sum to 8), lb: number of "bad plays" left lc: number of cards left in the deck t: current turn number

(The input will be closed here.)

Output

The action to take. One of

  • h player-id color or number – give a hint to another player. E.g. h 4 y will give player 4 a hint which of his cards are yellow. h 3 1 will give player 3 a hint which of her cards are a 1. This action is only possible if the number of hints left is positive. (The number of hints left will be reduced by 1, the number of discards will be increased by 1.)
  • p card# – play one of your own cards (identified by its number (1..5)). (If this card fits into the cards already played, it's added there. (If this is the last 5, the game ends immediately with full score (25)). Otherwise it is discarded and the number of bad plays is reduced by 1. If it reaches 0, the game ends (unsuccessfully).)
  • d card# – discard one of your own cards (idenfified by its number (1..5)). This is only possible if the number of discards is positive. (The number of hints left will be increased by 1, the number of discards will reduced by 1).

After playing or discarding a card, this card is removed from the hand, and a new card is drawn from the deck and is added to the list of cards of this player (on the left). (The hints are automatically updated.)

Option 2 (stateful)

Your program receives a live transcript of everything what happens (including the actions of the other players, and the results thereof). The controller will read one line of output from the program when it's its turn.

Input

Most input lines have the same format as before.

Initial input (as for the stateless version):

  1. Meta information (n: , y: )
  2. other player's cards (as before)
  3. hints for cards (as before)
  4. played cards (initially just p r: 0, p w: 0, etc.)
  5. discarded cards (initially just d: )
  6. game status, ending with t: 1.

After each player's turn:

  1. a line is given with that player's action: a player id: the action as defined in the output, e.g. a 1: h 4 y means that player 1 gave a hint to player 4 about yellow cards
  2. Those parts of the card situation which changed, e.g. c and d lines if a player discarded a card (or unsuccessfully played a card) and drew a new one), c and p lines if a player played out a card successfully, a h line if a player gave a hint.
  3. Updated status information, e.g. lh + ld when hint was given or a card discarded, lc when a new card was drawn, lb when a card was played unsuccessfully.
  4. t: indicating the next turn number.

*(TODO: Do we need an indication that's now your turn? That can be calculated by y == t mod n, but an explicit prompt might be easier to handle.

When the game ends, the input will be closed. (Your bot should terminate then.)

Output

As in the stateless version, one line indicating the player's action.

Option 3/4 (JVM only, stateless or statefull)

To be defined. As I will be writing the controller in a JVM language, it should be possible/easy to provide a Java API to be implemented by the bots.

Other game rules:

I tried to give most of the details above, but here are some which might be missing/unclear:

  • There are three × 1, two × 2 to 4 and one 5 in each of the five colors (50 cards in total, 10 per color).

  • When playing with 2 or 3 players, each player has 5 cards, when playing with 4 or 5 players, each player has 4 cards in their hand.

  • If you have three bad plays (i.e. the lb counter reaches 0), you lose immediately. This is counted as score 0.

  • If you succeed to play all 25 cards (i.e. all 5s are played successfully), you win immediately, with a score of 25.

  • When the drawing deck is exhausted, one more round is played (i.e. each player has one more turn), then the game ends and the final score is the number of cards successfully played out.

Competition Rules

  • While for human play, the amount of extra communication is "subject to negotiation", here I want to explore what is possible with just what the rules provide. Any communication between your bot instances (except as provided by the defined interface, i.e. via game actions) is strictly forbidden. Strategy needs to be encoded in the source code, not discussed during the game.

  • There is also no communication between your individual games (i.e. no persistence).

  • I will nominate an overall winner, and one for the stateless category. (The stateful ones have a bit more information, so they could emulate the stateless ones.)

  • I will run contestants 1000 times with random decks of cards, once for each number of players from 2 to 5. If your bot only works with a specific number of players, state this in your answer. The competition score is the average score for all the runs. [I'll need to experiment to see how this varies, maybe I'll increase or decrease the count.]

  • A bot needs to provide output in a reasonable time (to be defined). The stateless version needs to terminate after providing output, the stateful one keeps running, but should terminate after end of input (i.e. after the game ended).

  • I will provide the controller on Github, feel free to test your bot with it (and compare it with other competition entries).

  • The programming language needs to have an interpreter or compiler which is available free of cost for Ubuntu 20.4 (otherwise I can't run your bot to score it).

  • I reserve the right to not run a bot when I suspect malicious code in it.

  • This is not , please keep your code readable.

\$\endgroup\$
2
  • \$\begingroup\$ This still needs to be refined, and I actually need to write (and test) the controller. I won't post it before that is done. \$\endgroup\$ Jan 17, 2021 at 23:22
  • \$\begingroup\$ What tags should this get? code-competition? \$\endgroup\$ Jan 17, 2021 at 23:23
1
\$\begingroup\$

Write a Length interpreter

Length is a simple stack-based esolang where instructions are encoded as line lengths The instruction set is as follows:

Line Length Name Description
9 inp Pushes the ascii value of the first byte of stdin to the stack.
10 add Adds the top two values on the stack and pushes the result onto the stack.
11 sub Subtracts the top two values on the stack and pushes the result onto the stack.
12 dup Duplicates the top value of the stack.
13 cond If the top value of the stack is 0, skip the next instruction. Then pop it.
14 gotou Sets the program counter to the value of the line under the instruction.
15 outn Pops the top of the stack, and outputs it as a number.
16 outa Pops the top of the stack, and outputs its ascii value.
20 mul Multiplies the top two values on the stack and pushes the result onto the stack.
21 div Divides the top two values on the stack and pushes the result onto the stack.
24 gotos Sets the program counter to the value at the top of the stack

In case the table doesn't work, here is the esolangs page: https://esolangs.org/wiki/Length
Test inputs are too long to put here, they can be found here
helloworld.len - Outputs Hello, World!
truth.len - A truth machine
bottles.len - Outputs the lyrics to 99 bottles of beer
This is a code golf, so shortest program wins!

\$\endgroup\$
2
  • \$\begingroup\$ table is broken, it looks fine in preview \$\endgroup\$
    – Nailuj29
    Jan 18, 2021 at 20:49
  • \$\begingroup\$ Fixed. But this should be reported on SE Meta. \$\endgroup\$
    – Adám
    Jan 18, 2021 at 20:56
1
\$\begingroup\$

Radiation Showdown (WIP)


Two radiation-hardened programs will go head-to-head to destroy each other.

Your task is to create a program which takes the other program's source as input and output the index of the byte that should be deleted from the other program. (zero-indexed)

Each program will be radiated at the same time. The first program to fail to return a valid index after being radiated loses (whether by compiler error, runtime exception, out-of-bounds output, or some other means), or it is considered a draw if both fail at the same time.

Each program will compete against each other program. The program receives 1 point per round survived. The overall winner is the one with the most points.

Programs are limited to a length of 1024 bytes.


Alternate possibilities:

(Inspired by @Dingus) A hash of the opponent's original source code and a list of the indexes of bytes deleted so far is passed in instead of the current source code, making it a bit more of a blind guess as to what you radiate. If at any time, a program makes a guess it has already made, it loses. This turns it into a sort of "Radiation Battleship"

\$\endgroup\$
13
  • \$\begingroup\$ Interesting challenge. How will it be tested, if different languages are allowed? \$\endgroup\$
    – user
    Jan 19, 2021 at 19:12
  • \$\begingroup\$ @user it shouldn't be terribly difficult to make a shell-based controller. Submissions would probably need to include compiler flags or shebangs separately so that the controller knows exactly how to run the program. \$\endgroup\$
    – Beefster
    Jan 19, 2021 at 19:19
  • \$\begingroup\$ That would work for "practical" languages, but I'm a bit worried about esolangs. I guess TIO can probably deal with that, though. \$\endgroup\$
    – user
    Jan 19, 2021 at 19:20
  • \$\begingroup\$ If Program A has all its bytes deleted before Program B does, does B win? I'm imagining a pathological scenario in which A is empty and outputs by exit code. \$\endgroup\$
    – Dingus
    Jan 19, 2021 at 23:46
  • 1
    \$\begingroup\$ Also, wouldn't something like this be impossible to beat? \$\endgroup\$
    – Dingus
    Jan 20, 2021 at 0:12
  • \$\begingroup\$ @Dingus I suppose that would be impossible to beat. I wonder how I could make things different with resisting arbitrary insertions... probably not viable though. \$\endgroup\$
    – Beefster
    Jan 20, 2021 at 16:14
  • \$\begingroup\$ To prevent fixed-output programs, could you perhaps tie the indexing to the unmodified code? In other words, force the output to be different every round? \$\endgroup\$
    – Dingus
    Jan 20, 2021 at 22:22
  • \$\begingroup\$ @Dingus I think that might work (implying that both the original program and guesses are passed to the program), but there's probably another similar edge case I'm missing. Kinda turns it into radiation battleship. If a program returns a guess it has already made, it instantly loses. \$\endgroup\$
    – Beefster
    Jan 20, 2021 at 23:58
  • \$\begingroup\$ Following that thought, it might be kind of interesting if some opaque id (e.g. a hash of the source code) is passed in instead of the current state of the source code. \$\endgroup\$
    – Beefster
    Jan 21, 2021 at 0:02
  • 1
    \$\begingroup\$ @Beefster what's the point of the hash? (what can submissions do with it?) \$\endgroup\$ Jan 21, 2021 at 4:37
  • \$\begingroup\$ @thedefault. the hash is only used to assign a distinct id to each program and it could be used to seed a random number generator. \$\endgroup\$
    – Beefster
    Jan 21, 2021 at 16:16
  • 1
    \$\begingroup\$ @Beefster I thought submissions aren't supposed to be designed to beat specific opponents (and the only way to use a hash is to optimize to beat specific opponents) (and providing a hash of an unknown string as input just in case somebody wants to seed a RNG with it is a weird decision) \$\endgroup\$ Jan 22, 2021 at 16:47
  • 1
    \$\begingroup\$ Also, if the length of the source code is not known, it's effectively impossible to make guesses that are guaranteed not to be out-of-bounds. (also, I expect 90% answers to this challenge to output something like 0,1,2,3,4,5,...) \$\endgroup\$ Jan 22, 2021 at 16:58
1
\$\begingroup\$

Print a 3D shape

Posted

\$\endgroup\$
7
  • 4
    \$\begingroup\$ Suggestion: use characters other than and as they are multi-byte characters which not all languages will handle easily. ASCII characters instead would be better \$\endgroup\$ Jan 20, 2021 at 21:12
  • \$\begingroup\$ I modified them, thank you. \$\endgroup\$
    – anotherOne
    Jan 20, 2021 at 21:35
  • \$\begingroup\$ @caridCoinheringaahing I was just looking to try some other character taking as reference this ASCII table. The two characters that I changed are numbers 166 and 167 of the table. I am confused. \$\endgroup\$
    – anotherOne
    Jan 21, 2021 at 23:45
  • 1
    \$\begingroup\$ Most languages can handle code points between 32 and 127 inclusive. Some use custom code pages (e.g. Jelly) that won't necessarily have extended ASCII characters, but will have regular ASCII \$\endgroup\$ Jan 21, 2021 at 23:48
  • \$\begingroup\$ Oh all right thank you for the clarification! \$\endgroup\$
    – anotherOne
    Jan 21, 2021 at 23:55
  • 2
    \$\begingroup\$ @Davide the table you linked is not actually an ASCII table. ASCII only goes from 0 to 127; there are more code pages that extend it to 256 and the creator of that table has clearly picked one. This confusion arises because almost all code pages include ASCII as the first 128 and then extend with some symbols like on top of that. Nowadays most things use UTF-8 which encodes some characters with more than one byte and can use millions of different characters from Unicode \$\endgroup\$
    – pxeger
    Jan 22, 2021 at 7:58
  • \$\begingroup\$ @pxeger Oh thank you for this definitive explanation! \$\endgroup\$
    – anotherOne
    Jan 22, 2021 at 13:02
1
71 72
73
74 75
149

You must log in to answer this question.

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