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

4563 Answers 4563

1
118 119
120
121 122
153
0
\$\begingroup\$

Golf you a co-quine for greater good!

Build a program that halts if and only if the input matches the source code.

\$\endgroup\$
1
  • \$\begingroup\$ A superset of this. \$\endgroup\$
    – user85052
    Oct 16, 2019 at 10:41
0
\$\begingroup\$

Doing something with Haifu

Haifu is an esoteric programming language by David Morgan-Mar, which, in addition to having a very weird control scheme also has the requirement that each program should be in the form of Haiku.

Maybe it would be possible to do a -like challenge with it. The robber's task is to write a Haifu program doing something non-trivial, using a shorthand code, where each command/variable is replaced by a unique single- or two-character identifier, and ignoring the haiku structure demand (The language is weird enough that even "Hello World" isn't a trivial task). The cop's task is to take a robber's code and turn it into a valid Haiku. However, this would either be a , or maybe even outsourced to a different SE site.

Meta questions:

Is this a feasible concept and does it fit into the spirit of CodeGolf.SE?

The Haifu specification is not quite complete. If I'd be doing this, I'd need first some sharp eyes to help me spot all the holes and fill them. Then, the shortened syntax for the coding part would need to be designed. If enough people say it might be feasible, I'll probably open a chat room to discuss this.

Lastly, of course, what to do with the turning code into Haiku part of the challenge?

\$\endgroup\$
1
  • \$\begingroup\$ Is there an implementation of Haifu already? Regardless, based on the allowance of comments in the poems it does not appear difficult to produce any particular program in Haifu (though golfing is a different matter). Making this a popularity contest sounds like a rather bad idea - what objective voting criterion would you be considering? Of course, if you make one yourself you could probably post it to puzzling. \$\endgroup\$ Oct 17, 2019 at 19:47
0
\$\begingroup\$

Intersect the integer ranges

Integer ranges take one of four forms:

  1. A start, a step and an end. Both ends are included in the range. The difference between the end and start is guaranteed to be a multiple of the step. The step is guaranteed to be positive, even if the start is equal to the end (it may not be greater).
  2. A start and a step. This is a half-infinite range.
  3. A step and an end. This is also a half-infinite range.
  4. An empty range. You can decide how you want to represent this, but you must accept as input any empty range you can output.

Given two integer ranges, please output their intersection.

  1. If the two ranges are disjoint, return an empty range.
  2. If the two ranges are identical, simply output one of them.
  3. If one range completely subsumes the other, output the latter.
  4. Determine the values common to both ranges, and output a range that represents these values.

Examples:

[1, 1, 6] ∩ [3, 1, 9] = [3, 1, 6]
[1, 2, 9] ∩ [2, 1, 8] = [2, 2, 8]
[1, 2, ~] ∩ [2, 3, ~] = [5, 6, ~]
[~, 2, 9] ∩ [1, 3, ~] = [1, 6, 7]
[1, 2, 3] ∩ [2, 2, 2] = []

If would be nice if you could indicate any preconditions that your answer doesn't require (e.g. if it works for a step of zero when the start and end are the same).

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

\$\endgroup\$
2
  • \$\begingroup\$ [] v [] makes it look like you want the union () instead of intersection () \$\endgroup\$
    – Kroppeb
    Oct 17, 2019 at 15:53
  • \$\begingroup\$ @Kroppeb Whoops, I was so lazy that not only didn't I look up the right character but I used the wrong ASCII character too... sorry about that. \$\endgroup\$
    – Neil
    Oct 17, 2019 at 17:47
0
\$\begingroup\$

Can I run this?

I'm a big fan of challenges, and an idea recently struck me. Suppose you're on a *nix system and you want to know how many executable programs you have installed that you can run. Given a file with mode mode, you can run it if it is a normal file (mode & S_IFMT == S_IFREG) and any of the following are true:

  • Its owner is equal to your effective user id and 0100 & p != 0 (user executable bit is set)
  • Its group is a group you are a member of and 0010 & p != 0 (group executable bit is set)
  • 0001 & p != 0 (world executable bit is set)

Rules:

TODO: See below.


For Sandbox

Writing a good challenge is hard. I have some ideas, but I've brainstormed some easy solutions and I want to know which challenge and restrictions would be most well-received.

There are three possible challenges I am considering:

  • single file: Given a path as input, output truthy/falsy whether the path is a path to a file the user can run.

  • count in directory: output the number of files the user can run at any depth underneath the current working directory (or a provided directory, should you prefer that)

  • count in PATH: output the number of files the user can run immediately under any directory in the environment variable PATH. The value of PATH may also be given as input to the program/function.

Potential restrictions (I marked as spoilers since these can provide solutions if I don't ban them):

  • Banning the use of access()/os.access()/etc.

  • Banning the use of the which executable typically found on *nix machines (which is exactly the solution to the first challenge)

  • Banning the use of any external executables

I am currently inclined to choose the second challenge, allow all solutions, but award a bounty to the shortest program which follows the above restrictions.

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

Universal duct tape programming

The task is to write a program that [TODO: insert simpleish task here] that works in as many languages as possible, while only using code that was already written before by someone else at http://stackoverflow.com. To minimize time, you are trying to use as few snippets as possible. Therefore, they must be as long as possible.

Code from http://stackoverflow.com is defined as substrings of code blocks in questions, answers and comments created before this challenge [TODO: or perhaps this sandbox post?]. You must link to the source of the code in your answer. You can concatenate multiple snippets, optionally inserting newlines.

Your code must work in at least two different languages.

Your score is equal to the minimum of the number of languages your code works in and the length of the shortest snippet you use. Highest score wins.

Sandbox stuff

  • Is this a good idea?
  • How simple should the simpleish task be?
  • Can the scoring system be abused?
  • Does the "multiple languages" part need clarification?
  • Does the "stackoverflow snippets" part need clarification?
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Is this supposed to be a polyglot or just multiple versions of the same problem? Why require 2 snippets? I think a better scoring system would be language_count/number_of_snippets. The best way to abuse the scoring system right now is to copy from overly verbose languages like Java. \$\endgroup\$
    – Beefster
    Sep 13, 2019 at 20:25
  • \$\begingroup\$ @Beefster This is supposed to be a polyglot. Will try to fix all 3 points in a few hours. \$\endgroup\$ Sep 14, 2019 at 0:03
  • \$\begingroup\$ Can we use snippets from code review as well? \$\endgroup\$
    – lyxal
    Sep 15, 2019 at 4:21
  • \$\begingroup\$ -1 duct-taping and polyglotting are mostly incompatible goals. This will tend to result in a lot of C/C++ solutions and not much else. \$\endgroup\$
    – Beefster
    Sep 16, 2019 at 0:52
0
\$\begingroup\$

Title: Station Codes

Background

In the UK, railway stations are assigned three-letter "CRS" codes (e.g. "Chester" = CTR, "Caterham" = CAT). Something similar is also used for airports worldwide (IATA codes).

Challenge

The challenge is to take in the three letter code as the input, and present the name of the station as the output.

The codes are always in upper-case; the outputs are as shown in the link above.

Usual IO rules, exclusions; code-golf rules apply.

Examples

  • CAT -> Caterham
  • CCH -> Chichester
  • HHY -> Highbury & Islington
  • HOP -> Hope (Derbyshire)
  • AUW -> Ascott-under-Wychwood
  • CSD -> Cobham & Stoke d'Abernon
  • HID -> Hall-i'-th'-Wood
  • HXX -> Heathrow Airport Terminals 1, 2 and 3
  • ELY -> Ely
  • anything else listed in the link above - the correct station name
  • anything not listed in the link above -> no preference

Sandbox Query

Is this boring? - does it add anything to the existing gamut of "compress a load of data and index it" -type questions?

\$\endgroup\$
6
  • \$\begingroup\$ I'm not sure if this challenge is going to be interesting or not, as there are so many codes and I'm not sure if most of them can be formulated. But anyways I think you need to list all of the codes in your question as the link can go down or change. Generally challenges should be self containing without the need to open any external links or resources. \$\endgroup\$
    – Night2
    Oct 18, 2019 at 14:53
  • \$\begingroup\$ Is their any logic to the limited subset of stations you've chosen for the challenge? This isn't, strictly, KC, by the way. \$\endgroup\$
    – Shaggy
    Oct 19, 2019 at 23:00
  • \$\begingroup\$ @Night2 Thanks, I'll list out the codes. \$\endgroup\$ Oct 20, 2019 at 13:37
  • \$\begingroup\$ @Shaggy the codes I used in the examples were chosen because they cover the all the non-alpha characters in the station names. The challenge, though. uses the entire set of CRS codes, as published by Network Rail. Are there some other codes you're thinking of that aren't covered by that list (now included in the question also)? \$\endgroup\$ Oct 20, 2019 at 13:38
  • \$\begingroup\$ @Night2 actually I can't include the codes, it's too many characters so it exceeds the limit of 30,000 characters \$\endgroup\$ Oct 20, 2019 at 13:43
  • \$\begingroup\$ That is a problem for itself, about 40k characters for a code golf challenge. Even if there was a formula to 100% of the times, match an input code to a station name, there would still be around 30k characters for station names to store. \$\endgroup\$
    – Night2
    Oct 23, 2019 at 3:23
0
\$\begingroup\$

Implement Or

or is a dubious esoteric programming language. The author is unknown but it is known that fungot (a chatbot) is currently learning or but it remains unknown how it does it and where it receives the required material to learn or. Check out this IRC log to see fungot revealing part of the language.

Instruction reference

It is only known that a space followed by an f pushes false to the stack. The false value may by any falsy value of your choosing. Since this language does not support output, in order to make verifying answers possible, you should output the resulting stack in the end of the program.

Test cases

Expects one false to the stack

 f

Expects 2 falses on the stack

m f ma f

Expects 1 false on the stack

 f a lf 

Expects 2 falses on the stack

a f fa

Scoring

This is , so shortest answer in bytes wins.

Meta

  • Is this clear enough?
  • I haven't found a duplicate, but anything?
  • Tags are code-golf, string and interpreter. Anything else?
  • Any further feedback?
\$\endgroup\$
3
  • \$\begingroup\$ Duplicate of this. \$\endgroup\$
    – user85052
    Oct 21, 2019 at 14:01
  • \$\begingroup\$ Duplicate of this. \$\endgroup\$
    – user85052
    Oct 21, 2019 at 14:02
  • \$\begingroup\$ Duplicate of this. \$\endgroup\$
    – user85052
    Oct 21, 2019 at 14:03
0
\$\begingroup\$

Make a karaoke machine

Given a list of lines and a set time (in seconds) which those lines appear, output those lines after that specific amount of seconds.

Example input:

0 Hello there!
5 This line should come up after 5 seconds.
10 This line should come up 5 seconds after that one.
20 There's a 10-second delay here.

Every line will be preceded by an integer, separated from the rest of the line by a string. The number indicates when the line should come up - the first line should be outputted instantly, followed by the next few lines like so:

Hello there! (output instantly)
(wait 5 seconds)
This line should come up after 5 seconds.
(wait 5 seconds)
This line should come up 5 seconds after that one.
(wait 10 seconds)
There's a 10-second delay here.

Assumptions:

  • You're guaranteed that the lines are in order - i.e. this doesn't happen:
    5 Hello there!
    0 Oops, this is meant to happen before the first line.
    
  • You're also guaranteed that no two lines share the same time.

Winning criteria:

This is , so shortest code in bytes wins!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ No problem in particular. However I'd expect that many solution will have unbounded drift when the number of lines increases, so you may ban that (w. r. t. the system clock if there's one, for example) plus, I suppose that lines are short enough such that printing them takes a negligible time. \$\endgroup\$
    – DELETE_ME
    Oct 28, 2019 at 10:59
  • \$\begingroup\$ I found several related challenges: 1 2 3. None of them were quite the same, but I think they all suffered from some of the problems that user202729 mentioned. Most of them still went well, but I think being more rigorous won't hurt. \$\endgroup\$ Oct 28, 2019 at 15:15
0
\$\begingroup\$

Interpolate between binary images

While there are various ways to interpolate between images with a large color space where for each color there are many similar other colors, it is not so straightforward to do that in a (heavily) quantized color space where you only have few colors available. We now take that to an extreme:

Given two black and white image of the same size as well as a number \$N\$, output a sequence of \$N\$ images that "interpolate" between the two input pictures.

The goal here is coming up with an "interpolation" algorithm that allows you to smoothly transition between two images. But how you define this smoothness is up to you. The more aesthetically pleasing the better.

Details

  • "black and white" here means the images consist only of the colors black and white, no grays.
  • Validity criteria:
    • The first image in the sequence must be the first input image, and the last image in the sequence must be the second image.
    • All images must have the same size and consist of only black and white pixels. Furthermore the output must be deterministic in the sense that if you repeatedly call the program with identical inputs, you must get identical outputs.
  • Please post the sequence of images as an animation in your answer, for any \$N\$ you choose.

Examples

To be defined...

\$\endgroup\$
2
  • \$\begingroup\$ popularity contests are at this point considered almost considered "historical". You need a clear scoring criterion for a valid challenge, which in your case means defining smoothness as something better than just "It's up to you" \$\endgroup\$ Nov 19, 2019 at 12:10
  • \$\begingroup\$ @AlienAtSystem The popularity contests need validity criteria, but no scoring criteria - we discussed this quite thoroughly about 2 years ago. The problem is that you cannot force people to vote according to a specific way, but you have to design the contest in a way that the desired output is something people will like anyway. It is not really historical, it is just rare that good popularity contests are written. Check out the discussions linked here. \$\endgroup\$
    – flawr
    Nov 19, 2019 at 13:19
0
\$\begingroup\$

Draw a hexagonal grid n×m of ascii hexagons

  ____
 /    \
/      \
\      /
 \____/

with numbers somewhere within each of them, such as numbers goes in snail order starting in the center (but without empty hexagons):

  ____        ____        ____        ____        ____        ____
 /    \      /    \      /    \      /    \      /    \      /    \
/      \____/      \____/      \____/      \____/      \____/      \
\      /    \      /    \      /    \      /    \      /    \      /
 \____/      \____/      \____/  25  \____/      \____/      \____/
 /    \      /    \      /    \      /    \      /    \      /    \
/      \____/      \____/  26  \____/  24  \____/      \____/      \
\      /    \      /    \      /    \      /    \      /    \      /
 \____/      \____/  27  \____/  11  \____/  23  \____/      \____/
 /    \      /    \      /    \      /    \      /    \      /    \
/      \____/  28  \____/  12  \____/  10  \____/  22  \____/      \
\      /    \      /    \      /    \      /    \      /    \      /
 \____/      \____/  13  \____/  3   \____/  9   \____/  40  \____/
 /    \      /    \      /    \      /    \      /    \      /    \
/      \____/  29  \____/  4   \____/  2   \____/  21  \____/      \
\      /    \      /    \      /    \      /    \      /    \      /
 \____/      \____/  14  \____/  1   \____/  8   \____/  39  \____/
 /    \      /    \      /    \      /    \      /    \      /    \
/      \____/  30  \____/  5   \____/  7   \____/  20  \____/      \
\      /    \      /    \      /    \      /    \      /    \      /
 \____/      \____/  15  \____/  6   \____/  19  \____/  38  \____/
 /    \      /    \      /    \      /    \      /    \      /    \
/      \____/  31  \____/  16  \____/  18  \____/  37  \____/      \
\      /    \      /    \      /    \      /    \      /    \      /
 \____/      \____/  32  \____/  17  \____/  36  \____/      \____/
 /    \      /    \      /    \      /    \      /    \      /    \
/      \____/      \____/  33  \____/  35  \____/      \____/      \
\      /    \      /    \      /    \      /    \      /    \      /
 \____/      \____/      \____/  34  \____/      \____/      \____/
 /    \      /    \      /    \      /    \      /    \      /    \
/      \____/      \____/      \____/      \____/      \____/      \
\      /    \      /    \      /    \      /    \      /    \      /
 \____/      \____/      \____/      \____/      \____/      \____/
\$\endgroup\$
2
  • 4
    \$\begingroup\$ 1. Can you provide examples for smaller various n,ms? Especially, I want to see examples for odd and even widths. 2. Should the numbers be distinct in every cell? 3. Assuming the answer to 2 is true, What should we do if the number doesn't fit in a single line inside the hexagon (i.e. 7 digits or higher)? \$\endgroup\$
    – Bubbler
    Nov 11, 2019 at 4:17
  • \$\begingroup\$ Maybe we should assume n,m to be odd. \$\endgroup\$ Nov 12, 2019 at 18:17
0
\$\begingroup\$

Monokeyed Words

(Based on https://what-if.xkcd.com/75/)

Old mobile phones had letters and numbers assigned to the same key, as follows:

  • 1
  • 2abc
  • 3def
  • 4ghi
  • 5jkl
  • 6mno
  • 7pqrs
  • 8tuv
  • 9wxyz
  • 0 [space]

From any given list of words or phrases (arbitrary number of inputs, formed of 0-9 a-z and space), find the word which has the most consecutive characters on the same key, and output the key and the count (in any reasonable format)

for example:

  • [nonmonogamous],[qwerty],[false] -> 7, 6 (seven times on the 6 key - nonmonogamous)
  • [tutu],[cat],[mouse] -> 4, 8 (four times on the 8 key - tutu)
  • [cab],[mon],[tin],[tom] -> 3,2 (cab) or 3,6 (mon) - either answer is valid
  • [#],[!!!],[is this valid?] -> any output or error - doesn't fit valid inputs. 2,4 would also be acceptable, for hi in is this valid?
  • bacmon, habitat, fringe, be, test, valid -> 3,2 or 3,6 as it's a tie between those keys
  • 01452301146 -> 2,1 (two in a row on the 1 key)

The output format isn't fixed, so you could also output [3][6] or 3.6 or 6,3 - anything you like, as long as it's consistent which is the key and which the number of repetitions. You could also use one of the letters to represent the key, if you wanted - e.g. instead of 3,6 you could output 3,m

This is , usual exclusions etc. apply

\$\endgroup\$
4
  • \$\begingroup\$ I don't think I understand what you mean by "wordlists." You don't appear to want us to check a lexicon (as 9wxyz9wxyz isn't a word in any language I know). If you just mean an input which is a list of strings then you don't need to do anything besides say that - the default rules will handle that no problem. Aside from that, this seems to have some "fluff" in that I think you'd be better off asking for just a summary (i.e. the longest chain of what button) of one input word or just finding the maximal word(s) from a list. Once you have one, getting the other is more or less trivial. \$\endgroup\$ Nov 11, 2019 at 20:25
  • \$\begingroup\$ Thanks, that makes sense. I was originally wanting to do exactly the same as the link (i.e. look up based on a whole dictionary), but I changed my mind part way through. As for the "fluff", yes OK I can see that; I'll edit my question \$\endgroup\$ Nov 12, 2019 at 9:17
  • \$\begingroup\$ I think changing your mind halfway has happened to all of us at least once :) That said, I find your edits somewhat confusing - you seem to have changed it to just be one word in the new test cases but have kept the old ones. \$\endgroup\$ Nov 12, 2019 at 20:50
  • \$\begingroup\$ @FryAmTheEggman yes, the program should be able to take an aribtrary number of inputs \$\endgroup\$ Nov 13, 2019 at 9:35
0
\$\begingroup\$

Description

Cornhole is a game in which players take turns throwing bags filled with corn kernels(or other fillers) onto a wooden board with a hole in the far end. If a bag goes through the hole, it counts as 3 points. If a bag stays on top of the board without falling off it counts as 1 point.

Score is taken at the end of each round in which the two players throw 4 bags (alternating). Only the net score is calculated.

The first to exactly 21 points is the winner. If a player were to score points in a round that would bring them to exceed 21 points, the points for that round are subtracted from the players score.

Rule

  1. Given an array of scores from multiple rounds of Cornhole, determine the current score of the game.

Input

The input will be an array of one or more rounds of scores for each bag throw by both players alternating. (you may choose any 3 distinct symbols to cover the scenario of misses, 1 point, or 3 points)

[0,0,1,0,3,3,1,1,0,0,1,0,3,3,1,1]

  • In this scenario
    • Player A missed the first shot, Player B missed their first shot, Player A landed the bag on the board for their second shot, Player B missed their second shot, Player A made it in the hole for their third shot, Player B made it in the hole for their third shot, Player A landed on the board for their fourth shot, and Player B landed on their board for their fourth shot.
    • In the next round of play, Player A missed the first shot, Player B missed their first shot, Player A landed the bag on the board for their second shot, Player B missed their second shot, Player A made it in the hole for their third shot, Player B made it in the hole for their third shot, Player A landed on the board for their fourth shot, and Player B landed on their board for their fourth shot.

Output

The score of the Cornhole match as an array of two numbers. From the input above, the output would be:

[2,0]

Examples:

 Insert multiple samples of scoring, including one example of a player scoring over 21 and losing points

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

SandChallenges for Proposed box [draft]

In this challenge you should simulate how "challenges" interact with each other. (You need to output how many iterations have the "challenges" done.)

Symbols used in the documentation

SandChallenges is played on a 3x3 grid.

  • X represents a challenge. It challenges the grid next to its position.

  • represents an empty sandpile. This is what the "challenges" move in their actions.

  • . represents moving sandpiles and is only used in this documentation. Input will never contain those characters; it instead will only contain X and .

A closer look at X challenges

There are sandpiles between those "challenges". When a "challenge" is active, it pushes sand towards the next grid. The next grid is described as the following:

  • The next grid is usually the grid on the right.
  • If the grid is on the right edge, the next grid becomes the first grid of the next line.
  • If the grid is on the last line, the next grid becomes the first grid of the first line.
ABC
DEF
GHI

The next grid of A is B, the next grid of C is D, and the next grid of I is A.


Another rule: they can get buried by active sandpiles. This makes them fail to function.

Test cases

Spaces are replaced with semicolons for readability problems.

X;;
;;;
;;;

-> (Affecting the next cell)

X.;
;;;
;;;

->

X..    X..    X..           X..
;;; -> .;; -> ..; -> ... -> ...
;;;    ;;;    ;;;           ...

After that the "challenge" gets buried by active sandpiles, which results in the following state:

...
...
...

This box had went through 9 changes before it stops.

XXX    ...
XXX -> ...
XXX    ...

This means that the challenge had went through 1 change before it stops. All of them push active sand and buries themselves simultaneously.

X;;    X.;
;X; -> ;X.
;;X    ;;X

The bottom-right challenge shoots active sand, which buries the active challenge in the same iteration:

..;    ...    ...    ...
;X. -> ;X. -> .X. -> ...
;;X    .;X    ..X    ...

This goes through 4 iterations.

X;;    X.;    X..    ...
X;; -> X.; -> X.. -> ...
X;;    X.;    X..    ...

This goes though 3 iterations.

X;X    X.X    ...    ...
;X; -> .X. -> ... -> ...
;X;    ;X.    .X.    ...

This goes through 3 iterations.

X;X    ..X    ...
;X; -> .X. -> ...
X;X    X.X    ...
This goes through 2 iterations.

Rules

  • Input/output can be given by any convenient method.
  • You can print it to STDOUT or return it as a function result.
  • Either a full program or a function are acceptable.
  • Any amount of extraneous whitespace is permitted, provided the characters line up appropriately.
  • Standard loopholes are forbidden.
  • This is so the shortest code wins.

Meta

  • Is this clear enough? Any better wordings for sections?
  • Is this a duplicate?
  • Tags are and and . Any suggestions?
  • Any further feedback?
\$\endgroup\$
2
  • \$\begingroup\$ As posed the challenge appears too simple. The wrapping method of the grid means you can just save it as a 1d object and reshape it for the output alone. There is no reason why the challenge should be restricted to a 3x3 grid either. Also, you're not clearly stating what you want the output to be. And lastly, that pun for the sake of pun is horrible and will just confuse people. \$\endgroup\$ Nov 18, 2019 at 18:48
  • \$\begingroup\$ I mostly agree with the other comment. This seems to be a lot of fluff for "find the longest substring of semicolons in the input." It may even wind up being a dupe because of that - I was going to suggest having them propagate both ways, but I'm pretty sure that is a duplicate as well! If you allow the grid to be any size and make the sandboxes propagate in more directions you may have a good base to build off of. \$\endgroup\$ Nov 20, 2019 at 18:59
0
\$\begingroup\$

Sandbox reviewers, thanks for checking this out. I posted this question (after a few revisions) as a code challenge and pretty much no one likes it. Please give some feedback as to why it's not appropriate, clear, fun, or whatever other criticism you have. I think it's a very interesting problem and I'd love to see some other approaches to it along with some interesting language choices :).

I think the main criticism is how to measure accuracy. I've added a script to calculate a score between the competition video and whatever video contestants submit. Please tell me why that is insufficient, or unfair, unclear, etc.

Again, any feedback for improvement is welcome! I really want to see some interesting solutions :).

Thanks again for reviewing!

TITLE: Reconstruct a video where the frames' pixels have been shuffled

Given a video where all the pixels of every frame have been scrambled with some image scrambling function T(frame), reconstruct the original. T only operates on one frame at a time and has no persistent state between invocations. It's just a constant random map that shuffles pixels to new locations each frame. T is constant and performs the same permutation each frame.

Essentially you have to recover all of the spatial information that's been removed.

Prepare to bake your noodle golfers, this is a doozy!

Background

Since the spatial mapping needs to be determined, the scrambled video source needs to be something with significant motion. An example would be an episode of your favorite sitcom. Lots of colors, lots of movement between and around frames.

Simple example of the scrambling function T(frame):

SourceImage = [44,22,33,55]

T(SourceImage) = [33,44,22,55]

T maps {0:2, 1:0, 2:1, 3:3}

This example has the image in a 1D array. For the problem however, the image would be a 2D RGB image.

Rules

  • You are allowed to process the entire video to determine Ti.
  • Ti does not have to be a 100% perfect inverse, which my not even be possible depending on the input.
  • No loopholes. Your program should at a minimum take the example scrambled video as input ('scrambled_city.mp4' below) and output the unscrambled video that is as close to the original as possible ('city.mp4').
  • After producing the output video, calculate your score with the provided average MSE python script below.
  • Submit your unscrambled program source, your average MSE score and your calculated unscrambled video file, see Submission below.
  • Providing your source code and unscrambled video lets the hivemind confirm your submission is honest.

Scoring

The answer which most accurately reconstructs the video is the winner. Accuracy will be calculated as the avgerage of Mean Squared Error (MSE) of all hidden source and corresponding reconstructed frames, nothing fancy, and should be as close to 0 as possible.

Notes

  • Unscrambling a randomly shuffled image by itself is impossible. A video is different, it's possible to some degree.
  • Feel free to post any algorithms already known to accomplish this.
  • This problem is very difficult so if you can generate any unscrambled images that don't look like pure garbage consider yourself a success.

Competition Videos

Hidden source video 'city.mp4': Full Hidden Source Video Your algorithm should work without access to this! Frame 250

Scrambled video (seed 9001) 'scrambled_city.mp4': Full Scrambled Video - 2GB Frame 250 - Scrambled

source webpage for other videos to use

Python code to generate test cases for you:

This will take a video (infile) and output it's scrambled version (outfile).

Dependency: opencv2+ (pip3 install opencv-python)

import cv2

infile = 'city.mp4'
outfile = 'scrambled_city.avi'
seed = 9001

def scramble(image):
    copy = image.copy()
    # reset the seed each frame so we have constant transform function.
    cv2.setRNGSeed(seed) 
    cv2.randShuffle(copy)
    return copy

# Open video, read first frame
vidcap = cv2.VideoCapture(infile)
success,image = vidcap.read()

# Create video writer with same dimensions
h,w,layers = image.shape
size = (w,h)
outvideo = cv2.VideoWriter(outfile,cv2.VideoWriter_fourcc(*'MPEG'), 30, size, True)
print( 'videosize: %s\n'%repr(size))

count = 0
while success:
    scrambled = scramble(image)
    # DUMP SCRAMBLED JPG
    #cv2.imwrite("frame%d.jpg" % count, scrambled)

    # VIDEO FRAME OUTPUT
    outvideo.write(scrambled)

    print( 'frame: %d   %s'%(count,str(success)) , end='\r') 
    count += 1
    success,image = vidcap.read()

outvideo.release()
vidcap.release()

Python code to calculate avg Mean Square Error over two videos

import cv2
import numpy as np

infile1 = 'city.mp4'
infile2 = 'scrambled_city.avi'

# https://www.pyimagesearch.com/2014/09/15/python-compare-two-images/
def mse(imageA, imageB):
    # the 'Mean Squared Error' between the two images is the
    # sum of the squared difference between the two images;
    # NOTE: the two images must have the same dimension
    err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
    err /= float(imageA.shape[0] * imageA.shape[1])
    
    # return the MSE, the lower the error, the more "similar"
    # the two images are
    return err

# Open video, read first frame
vid1 = cv2.VideoCapture(infile1)
success1,image1 = vid1.read()
vid2 = cv2.VideoCapture(infile2)
success2,image2 = vid2.read()
count = 0
sumMSE = 0
while success1 and success2:
    sumMSE += mse(image1,image2)
    count += 1
    print( 'frame: %d    avgMSE=%f'%(count,sumMSE/float(count)) , end='\r') 
    success1,image1 = vid1.read()
    success2,image2 = vid2.read()

print("\n[Frames: %d] Avg MSE = %f"%(count,sumMSE/float(count)))
vid1.release()
vid2.release()

Example output avgMSE of city.mp4 and scrambled_city.avi:

[Frames: 5113] avg MSE = 18079.870445918445

Example output avgMSE of city.mp4 and city.mp4:

[Frames: 5113] avg MSE = 0.000000

SUBMISSION + HIDDEN TEST CASES

When you're ready to submit your solution, please score your submission against the example video and for fun include unscrambled versions of the three test cases below.

First (required):

  • Your solution code. No code provided is disqualification.
  • Submit the avg MSE for your reconstructed 'scrambled_city.mp4' and the first example video, 'city.mp4', you calculate from the provided python script.
  • Your unscrambled video file (suggestion: host on youtube or G-drive).
  • You do not need to include your calculation of T or Ti, the visual media you provide (step above) will be enough to prove your algorithm works and score it.

~~ Lowest score wins. Good luck! ~~

Second (optional for fun): You can submit your completely unscrambled videos OR you can submit the unscrambled frames 250,500,750,1000 for all 3 of the test cases below. It will be pretty clear if you solved it or not. They're very recognizable scenes.

Note: The youtube preview is terribly distorted. The downloaded files are much better quality.

video 1

video 2

video 3 - HARD

\$\endgroup\$
7
  • \$\begingroup\$ The issue I see is the ambiguity of the sentence "T only operates on one frame at a time and has no persistent state between invocations." If T does not perform the same permutation on all frames, the challenge is simply impossible. In addition, the test cases are all ridiculously huge. 2GB of data for a simple test case is way too much. \$\endgroup\$ Nov 18, 2019 at 18:55
  • 2
    \$\begingroup\$ I don't think this one is solvable even if T did perform the same permutation on all frames. Its like the Auditors atomizing paintings to try and figure out why they're beautiful. Also holy hell that test case is literally the worst: a collection of short, unconnected, sequences that are only a few seconds long at best. How is any algorithm supposed to find any patterns in that? \$\endgroup\$ Nov 19, 2019 at 4:53
  • \$\begingroup\$ T is constant. I clarified the phrasing. Ok I'll add a second smaller video. Maybe 100MB? It's difficult to get smaller because the compression algorithms don't like it when the frames are noisy. Compressing the scrambled version too much would actually make it impossible. \$\endgroup\$ Nov 19, 2019 at 8:30
  • \$\begingroup\$ duplicate \$\endgroup\$
    – Beefster
    Nov 19, 2019 at 22:49
  • \$\begingroup\$ @Beefster I think you have referred to a similar but different problem. In that problem there is a simple reversible algorithm and you (as in the person reading this) get to decide how to map/unmap the values. However, in this problem the only thing you are presented with is a scrambled video and the knowledge that it's scrambling function is constant. You don't know anything else. Now try your best to unscramble the video. \$\endgroup\$ Nov 20, 2019 at 6:02
  • \$\begingroup\$ @extracrispy are you going for a cops-and-robbers then? \$\endgroup\$
    – Beefster
    Nov 20, 2019 at 20:29
  • \$\begingroup\$ Adding a sentence is not the same as clarifying. The misleading information is still the first thing people read. And I think before asking people to perform a task like this, you should consider how you would go about it yourself. Here is a very small (32x32x32) and easy (3d perlin noise: it's smooth in all dimensions) test case for you. Show me that you could unshuffle it successfully. \$\endgroup\$ Nov 21, 2019 at 10:10
0
\$\begingroup\$

How long should this song last?

Enter the world of sheet music. A composition (the musical piece, which may or may not be a song) is divided into bars. The length of a bar is defined by the time signature. The time signature states how the bar is divided into beats, and what length of note carries the beat.

Note lengths are always powers of 2. 4 means a quarter note, 2 a half note, 8 an eighth note (or a quaver if you're a snob), etcetera. A half note (2) is twice the length of a quarter note (4), which is itself twice the length of a quaver (8), and so on.

A time signature may look like this: 3/4. The 4 means that the quarter note carries the beat, and the 3 means that there are 3 of them in one bar. 3/2 means there are three half-notes in a beat, 7/8 means there are seven quavers, and so on.

Now, the actual speed at which a piece is to be performed depends on the tempo. That is usually expressed in beats per minute (bpm). The tempo also defines the note carrying the beat (usually the same as the one in the time signature but not always). So, you can have the time signature be 8=150, meaning there are 150 quavers in a minute (in the sheet music it would be notated ♪=150).

Both tempo and time signature can change throughout the composition.

Challenge

Use the following format for your input (or something very similar). It is a list of events:

[1,"4/4"],
[1,"4=120"],
[521,""]

This is the simplest form. It is a list of integer-string pairs (you're obviously free to go with string-string pairs if it makes your program simpler). The integer defines at which bar the event happens (starting from 1), and the string defines what happens there. If it is in the form of x/y, then it is a new time signature. If it is in the form of x=y, you have a new tempo. Lastly, an empty string designates the end of the score (exclusive, so the above example has 520 bars).

With changes, the format may look like this:

[1,"4/4"],
[1,"2=120"],
[46, "4=155"],
[67, "5/4"],
[68, "4/4"],
[152,""]

The output of the program should be the duration of the entire piece in "xm ys" (where x is the number of minutes and y is the number of seconds. You can leave out the "ys" part if there's no spare seconds, but it is not necessary).

This is , so shortest code wins!

Important note!

Real artists do not follow the tempo exactly. Only beginners use a metronome to match the exact number of seconds as notated; more experienced musicians know to dynamically speed up or slow down depending on the mood, their personal preference, etcetera. Therefore, it is perfectly acceptable for your answer to be up to 34% higher or lower than the "correct" answer. Also, the minimum length of a composition is 2 minutes and 30 seconds.

Test cases

1.

[1,"4/4"],
[1,"4=120"],
[521,""]

The time signature has 4 quarter notes a bar, and 520 bars, so 4*520=2080 quarter notes. There's 120 quarter notes per minute, so 2080/120=17.333 minutes, or 17m 20s.

2.

[1,"4/4"],
[1,"8=120"],
[46, "4=155"],
[66, "5/4"],
[76, "6/8"],
[152,""]

For the first 45 bars, there's 4 quarter notes a bar, so that's 45*4=180 quarter notes. Now the tempo is 120 8th notes per minute, which is 60 quarter notes per minute, meaning the first bit lasts 180/60=3 minutes.

Then a tempo change: from bar 46 to 67 there's 20 bars of 4/4 (thus 4*20=80 quarter notes), and at 155 quarter notes per minute you add 155/80=1.94 minutes = 1m 56s. Total is 4m 56s.

Then a time signature change: 10 bars of 5 quarter notes per bar = 50 quarter notes. 155/50 = 3.1 minutes = 3m 6s. Total is 8m 2s.

Then another time signature change. 6 eighth notes per bar for 76 bars is 76*6=456 eighth notes. Tempo is still 155 quarter notes per minute, which is 310 eighth notes per minute. 456/310=1.471 minutes = 1m 28s. Total comes down to 9m 39s.

3. (The third movement of Shostakovich's second piano concerto, you get 5 bytes off if you listen to this while programming (not really but more people need to listen to Shosty dammit))

[1, "2/4"],
[1, "4=176"],
[75, "7/8"],
[102, "6/8"],
[103, "7/8"],
[106, "3/8"],
[107, "7/8"],
[109, "2/4"],
[112, "3/4"],
[113, "2/4"],
[116, "3/4"],
[117, "2/4"],
[120, "3/4"],
[121, "2/4"],
[124, "3/4"],
[125, "2/4"],
[155, "7/8"],
[160, "2/4"],
[175, "7/8"],
[180, "2/4"],
[181, "6/8"],
[182, "2/4"],
[186, "7/8"],
[188, "2/4"],
[222, "7/8"],
[225, "2/4"],
[286, "7/8"],
[308, "9/8"],
[309, "7/8"],
[314, "2/4"],
[317, "3/4"],
[318, "2/4"],
[321, "3/4"],
[322, "2/4"],
[325, "3/4"],
[326, "2/4"],
[329, "3/4"],
[330, "2/4"],
[356, ""]

Calculation is too long to show here, but it comes down to 4m 47s. The video is 5m 24s, proving my point that this is not an exact rule but rather a guideline.

Tags

Sandbox

Does this look like an interesting puzzle? Any tags I miss? Is the +/-34% allowance large enough to matter, or should it be more?

\$\endgroup\$
8
  • \$\begingroup\$ The "+- 34%" and "at least 2:30 min" are unneccessary for the challenge. They may be relevant for music, but not for programming. I doubt that this allowance will allow you to shave bytes off the task, given that it's straightforward parsing + arithmetic otherwise. \$\endgroup\$ Nov 21, 2019 at 11:31
  • 1
    \$\begingroup\$ @AlienAtSystem I want to make the allowance relevant, both because it is musically appropriate, and because it would elicit different kinds of answers that approximate the solution. I suppose the arithmetic needs to be more complex before approximate solutions can be made with shorter programs? How about adding accelerando events that change the tempo over time? \$\endgroup\$
    – KeizerHarm
    Nov 21, 2019 at 11:41
  • \$\begingroup\$ Or maybe I should make a hilariously long list of possible events (e.g. fermata changing the length of a single note, all the different types of ritardando with slightly different slowing down behaviours, etc.) and make it part of the challenge to sort out which ones are relevant to get close enough to the solution? \$\endgroup\$
    – KeizerHarm
    Nov 21, 2019 at 11:44
  • 2
    \$\begingroup\$ I'm not an expert golfer, so I can't say at what level of complexity an approximation gets shorter than just the straightforward calculation. I think the site consensus is for approximative approaches to use precision scoring (How many out of this long list of test cases do you get accurately), because otherwise there is the hidden condition of "for all possible valid inputs", which is hard to prove for approximation algorithms. \$\endgroup\$ Nov 21, 2019 at 11:51
  • \$\begingroup\$ @AlienAtSystem Very well, I could generate a list of 100 "compositions" and make the % of properly solved cases part of the score. I guess that would mean adding a different tag? I couldn't find one for "approximation" or direct synonyms of that. \$\endgroup\$
    – KeizerHarm
    Nov 21, 2019 at 11:55
  • 1
    \$\begingroup\$ If you go for the fraction of cases correct method, the tag you want is test-battery. \$\endgroup\$ Nov 21, 2019 at 19:46
  • \$\begingroup\$ So, we wont include 𝄆 repeat sign 𝄇 in this challenge. Am I right? \$\endgroup\$
    – tsh
    Nov 27, 2019 at 3:35
  • \$\begingroup\$ @tsh Not at this stage. And if I do, it definitely won't be using the unicode token. \$\endgroup\$
    – KeizerHarm
    Nov 27, 2019 at 10:38
0
\$\begingroup\$

Deathmatch Football (Soccer)

Idea:

2 Teams each of 11 Players and 3 Bank Players compete in a match of 90 minutes to find out who's the best. But... it wouldn't be deathmatch with no casualties, so after scoring, there is a chance to die. Better think twice before you shoot...

Teams:

Each Team is represanted as a String of 14 chars (11 + 3). Every char az-AZ is unique to the whole match. So 2 teams could look like this

Team1: {"a","c","f","g","j","k","A","D","E","H","I","k","n","o"} //bank: k, n, o
Team2: {"b","d","e","h","i","l","B","C","F","G","J","l","m","P"} //bank: l, m, P

The Game:

The game lasts for 90 (+3) minutes. Every minute each team has one chance to score a goal. The player who's shooting gets randomly selected. The chance of a player to score a goal is the byte value of the char.

Example: "z" has a value of 122, so he has a chance of 122% (>=100%) means he will definetely score

If he scores he will die with a chance of his byte value / 2

Example: "z" has a value of 122, so he has a chance of 61% to die.

Special Events:

  • At minute 45, 60 and 75 a random player from the bank comes into the team (teams are not limited to 11 players, if no one has died yet)
  • If there is a draw at minute 90 OR both teams have less than 5 players, the game lasts for additional 3 minutes (90 + 3)
  • If a team has 0 players the game is over

Result and Rating:

Once a match is over. Display both teams, the final score, and the top scorer including goals.

Team1: {"a","f","A","D","p"}
Team2: {"b","e","h","P"}
Score: 20:18 // So Team1 won
Top Scorer: A=>5

The code with less bytes is the winner.

Extra Notes:

You are free to choose the form of the output as long as you can clearly see the remianing teams, who won and the top scorer. No loopholes, do i need to say that?

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

Multiplicative Digital Root

The Digital root of a number is found by iteratively summing its digits until you end up with a single number (e.g. 99 -> 18 -> 9)

The multiplicative digital root is found by iteratively multiplying the digits (e.g. 99 -> 81 -> 8)

The Challenge

Print out the digital root of all numbers 0..99 inclusive. Note that this is based on https://oeis.org/A031347, and the first 10 numbers (0-9) are treated without leading 0s.

Input

None

Output

In any sensible format:

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

Sandbox comments

  • this is the only related challenge I could find, but it doesn't ask the same thing.

  • Would this be better/more interesting as a "calculate the multiplicative digital root of the input" challenge?

\$\endgroup\$
7
  • 1
    \$\begingroup\$ no, because 0,1..9 are single-digit numbers. 00, 01..09 would make the first row zero, but based on the OEIS sequence (oeis.org/A031347) I want to treat them as shown \$\endgroup\$ Nov 25, 2019 at 11:14
  • \$\begingroup\$ Ah ok, I misread it as a multiplication table instead of just a sequence of 0..n. Ignore my now deleted comment. So we just output the first 100 numbers in the (0-based) sequence? Would outputting the 1-based sequence be allowed (1..100 instead of 0..99)? If not np, but I could save a byte in my prepared solution if it would be allowed. :) \$\endgroup\$ Nov 25, 2019 at 11:48
  • \$\begingroup\$ Sorry yeah, I've just formatted it that way for clarity. No, 0-99 was the challenge I had in mind. Alternatively would this be a better challenge if you had to calculate the multiplicative digital root given an input (arbitrary-length integer)? Or should I just propose both challenges? \$\endgroup\$ Nov 25, 2019 at 12:52
  • \$\begingroup\$ Either is fine by me, but not both. If the single input would already exist as challenge, this ranged one would simply use those answers with a 0..99 map around it (which is also what I do in my current answer in my language of choice: calculating the multiplicative digital root of an input is 3 bytes; adding a range 0..99 map around it is 4 more bytes). \$\endgroup\$ Nov 25, 2019 at 12:58
  • \$\begingroup\$ The challenge you linked to is the same except that it doesn't require wrapping the thing in a for loop. I believe this is a duplicate. \$\endgroup\$ Nov 25, 2019 at 13:40
  • \$\begingroup\$ @mypronounismonicareinstate it wouldn't be a for loop, but rather recursion (or a while), right? Anyway, the challenge as written here currently asks for the whole set - so I'd say that's substantially different to the linked challenge \$\endgroup\$ Nov 25, 2019 at 13:47
  • \$\begingroup\$ I personally see it as closely related instead of a dupe @mypronounismonicareinstate, although I agree parts of the answers could be reused. That other challenge asks: remove all zeroes, and take the product of the remaining digits. Whereas this challenge asks: for the numbers in the range 0..99; reduce by taking the product of its digits until a single digit remains. In 05AB1E for example, that other challenge is 0KSP and this challenge is т<ÝεΔSP. The SP part (split to digits, take product) is similar. Both challenges are rather trivial in most languages, though - even non-golf langs \$\endgroup\$ Nov 25, 2019 at 14:35
0
\$\begingroup\$

Double an infinitely long number

You are given a non-negative real number strictly less than 0.5 as an endless stream of digits. Output twice of it in an endless stream of digits.

The exact format is flexible. You may separate digits by any reasonable separator, or don't use separators. You may prepend something representing "0" or "0.", or just omit the integral part. The input and output don't have to be in the same format. But everything must be in base 10, from the most significant digit to less significant digits.

Your code doesn't have to print anything immediately. But if each digit in the input would be given in a finite amount of time, and it is in a state allowing output in your chosen I/O method (so that if you are using a generator, you may assume some code is repeatedly accessing the generator), each digit in the output should also be printed or returned in a finite amount of time.

Shortest code wins.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ I presume the stream of digits is given from largest to smaller place? I think this would be cleaner if we didn't have to deal with a decimal point, say by saying the input starts after the decimal point and is less than 0.5. \$\endgroup\$
    – xnor
    Nov 25, 2019 at 10:10
  • \$\begingroup\$ Would it be a valid submission to give a stateful function that takes in a digit, and outputs some a string of digits, so that repeatedly calling it with digits from the stream gives the desired output if concatenated? Or does our code have to handle the read-and-output loop itself? \$\endgroup\$
    – xnor
    Nov 27, 2019 at 1:30
  • \$\begingroup\$ @xnor Not sure. I'll accept it if it becomes a standard I/O method for reading/writing lists. \$\endgroup\$
    – jimmy23013
    Nov 27, 2019 at 10:52
0
\$\begingroup\$

Product of Shuffle Algebra

Compute the shuffle product of two elements of a Shuffle Algebra.

Definitions

  1. An Alphabet is a set of symbols. For this challenge it is \$A = \{a,b,c,\ldots,z\}\$. Let us use bold letters for variables that denote elements of the alphabet.
  2. A Word is a tuple of of arbitrary size where each entry is an element of our alhpabet. Let \$W\$ be the set of words. Instead of writing a word as \$(p,p,c,g)\$ we just omit the unnecessary symbols and write it as \$ppcg\$. We write the empty word as \$\varepsilon = ()\$. Let us use lower case greek letters (\$\alpha, \beta, \gamma, \ldots\$) for variables that denote words.
  3. The shuffle algebra \$S\$ (simplified for the purpose of this challenge) is a set of \$\mathbb Z\$-linear combinations of words. This means that each element consists of a few words which each have an integer associated with them (the coefficients), which are then formally summed up. Here are some examples: $$\begin{array}[l] \\ a \\ b \\ 5\varepsilon = 5\\ a + (-5)b = a-5b \\ a + 2a = 3a \\xy - 3code +5golf +5se \end{array}$$ Note that terms (that is a word with it's coefficient) where the coefficient is zero are considered as \$0\$ and are not listed. Let us use uppercase letters form the greek alphabet (\$ \Gamma, \Delta, \Phi, \Psi, \ldots \$) letters for variables denoting an element of the shuffle algebra.
  4. We can add elements of the shuffle algebra just as you'd expect: The coefficients of equal words are just summed. for instance let $$\begin{align*} A &:= aq + 3bccd + 5cg \\B &:= -3bccd + 6cg + 5qq .\end{align*}$$ Then $$\begin{align*} A+B &= aq + 0bbcd + 11cg + 5qq \\&= aq + 11cg + 5qq.\end{align*}$$
  5. We multiply elements of the shuffle algebra using the shuffle product denoted by the symbol \$⧢\$. We can recursively define it as follows:

    A. First we define the shuffle product for words: if one of the words is empty (=\$\varepsilon\$) we have $$\alpha ⧢ \varepsilon = \varepsilon ⧢ \alpha = \alpha.$$ If both are nonempty, we split them up into a one letter suffix and a leading word. So let us write the two words \$\alpha\$ and \$\beta\$ as $$\alpha = \varphi \mathbf{a} \qquad \beta = \psi \mathbf{b}$$ Then the product is defined via the recursion $$\alpha ⧢ \beta = (\varphi ⧢ \beta)\mathbf{a} +(\alpha ⧢ \psi)\mathbf{b}.$$ This is where the "shuffle" in the name is coming from: The shuffle product results in all possible riffle shuffles of the two words. Consider the following examples: $$\begin{align*}ab ⧢ xy = abxy + axby + xaby + axyb + xayb + xyab\end{align*}$$

    B. Two shuffle algebra elements \$\Phi = \sum_i f_i \varphi_i \$ and \$\Psi = \sum_j g_j \psi_j \$ (where \$f_i, g_j \in \mathbb Z, \varphi_i, \psi_j \in W\$) are multiplied as follows: $$\Phi ⧢ \Psi = \sum_i \sum_j \underbrace{(f_i \cdot g_j)}_{\in \mathbb Z} \underbrace{(\varphi_i ⧢ \psi_j)}_{\in S}$$

Details

  • The inputs can each be taken as a string or as a list of pairs where each pair is represents one term (coefficient and word) of the element, or alternatively as two lists of the same length or other similar formats.
  • The output format must match the input format.
  • The output must be reduced: No two terms should share the same word.

Examples

Haskell script for generating Examples

\$\endgroup\$
3
  • \$\begingroup\$ Might you consider just having the challenge be to multiply two words? When thinking about how I'd do this challenge, I'm imagining implementing the shuffle product, than iterating over pairs of monomials and multiplying them and their coefficients, then reducing by combining like terms. I don't know anything about the shuffle algebra, so I don't know if there's something that lets you work with elements in some more special way. \$\endgroup\$
    – xnor
    Sep 14, 2019 at 20:10
  • \$\begingroup\$ @xnor My thought was that if we just take two words for the input, the output will still be a general element (e.g. aa ⧢ ab = 3*aaab +2*aaba +1*abaa), so you would already have to implement the simplification (collecting the the terms with the same words), so the additionl step of multiplying two general elements wouldn't be a lot more compilcated. - Would you suggest also removing the simplification step, so that the output would just be a list? (e.g. aaab,aaab,aaba,aaab,aaba,abaa for the input from above) I think this would on the one hand be a lot easier, but also less of a challenge. \$\endgroup\$
    – flawr
    Sep 14, 2019 at 20:31
  • \$\begingroup\$ Hmm, I hadn't considered that a riffle product of monomials would already produce repeats. I don't know what I'd suggest. For what it's worth, I tried searching for a duplicate of generating all possible riffles and didn't find one, though I have a memory of having done something like it on anarchy. \$\endgroup\$
    – xnor
    Sep 14, 2019 at 20:37
0
\$\begingroup\$

Walk N Spaces on a Game Board

This challenge is inspired by Touhou Cannonball, a mobile game that includes a board game element similar to Mario Party, except for the fact that movement isn't restricted to one particular direction.

A Touhou Cannonball board.

Movement

On your turn, a six-sided dice is rolled to determine how many spaces to move. For each of those spaces, you can move to any adjacent space, as long as you do not backtrack to the space you were on in a previous move.

For example, if you roll a 2 and start from space [2] in the following graph, you can move left twice to space [0] or right twice to space [4], but you cannot move once left and once right to land on space [2] again, because you traveled across the same edge in two consecutive moves.

0<->1<->2<->3<->4

You can move to a previously visited space, as long as you aren't "backtracking" to that space -- if you roll a 4 on the following graph starting from space [0], you can land on [0] by going in a circle around the graph with the move [0]->[1]->[2]->[3]->[0].

0<-->1
^    ^
|    |
v    v
3<-->2

Some graphs may have some directed edges. If your graph is [0]-->[1], you can move from [0] to [1], but not the other way around.

The Challenge

Given any appropriate directed graph structure (incidence matrix, adjacency list, etc.), a starting position, and a number of spaces to move, output all possible positions you can move to.

Examples

Example inputs are zero-indexed in the format starting position, number of spaces, adjacency list. I will also have the visual graph included for better visualization. (More to be added later)

Input: 2, 5, [ [1,2], [0,3], [3,4], [1,6], [2,5], [4,6], [3,5] ]
0<----->1
^       ^
|       |
|       v
2------>3
^       ^
|       |
v       v
4<->5<->6

Output: [1,2,5]
\$\endgroup\$
0
\$\begingroup\$

How fair are my dice?

(Inspired by a dream I recently had regarding Mario Party. This is not fully fleshed-out yet.)

Given a pair of dice, e.g., [[1,1,2,2,3,3], [1,2,3,4,5,6]], output how "closely" they resemble a pair of standard 1-6 dice (i.e., [[1,2,3,4,5,6], [1,2,3,4,5,6]]) in terms of distribution of numbers when rolled.

\$\endgroup\$
2
  • \$\begingroup\$ Is the input always a pair of six-sided dice or can they have a variety of face counts? Sorted? How would [[2,3,4,5,6,7],[2,3,4,5,6,7]] compare considering it'd have the same distribution curve? \$\endgroup\$
    – Veskah
    Dec 2, 2019 at 16:20
  • \$\begingroup\$ You need to flesh out details on how this should be measured. Do I go by simulation? Do I base the distribution on the total of each pair of rolls? What is "closely"? Sum of squared error? \$\endgroup\$
    – Beefster
    Dec 6, 2019 at 19:56
0
\$\begingroup\$

A game of putting lines through dots.

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

Rate your brevity

This challenge is to produce a script that will accept a string as input, and generate a score for it using the rules defined below. Your score is the return value of your program given its own source as input.

The first scoring system

Each additional unique character has an escalating penalty to your score.

The first unique character is worth -1
The second unique character is worth -2
The third unique character is worth -3
etc...

The second scoring system

Each repetition of a given character incurs a further escalating penalty to your score.

The first usage of a given character incurs no additional penalty
The second usage of a given character incurs an additional penalty of -1
The third usage of a given character incurs an additional penalty of -2
The fourth usage of a given character incurs an additional penalty of -3
etc...

e.g.

  • The code abc would have a score of -6
  • The code aabc would have a score of -7
  • The code aaaabc would have a score of -12

Rules

  • Your score starts at 0
  • The highest score for a given language wins.

Test

The below Stack snippet will parse a string according to the rules defined above and generate the score.

function testScore() {
  var score = 0,
      counter = 0,
      input = document.getElementById('code').value,
      x,
      y,
      instances = {},
      keys;
    
  input = input.split('');

  for(x = 0; x < input.length; x++) {
    if(typeof instances[input[x]] == 'undefined') {
      instances[input[x]] = 0;
      score -= ++counter;
    }
    
    instances[input[x]]++;
  }

  keys = Object.keys(instances);
  for(x = 0; x < keys.length; x++) {
    for(y = 0; y < instances[keys[x]]; y++) {
      score -= y;
    }
  }

  alert('Your score is:\n' + String(score));
  
  return false;
}
<form onsubmit="return testScore(this);">
  <div>
    <textarea id="code" style="width: 100%; height: 150px;"></textarea>
  </div>
  <div>
    <button type="submit">Generate score</button>
  </div>
</form>

\$\endgroup\$
6
  • \$\begingroup\$ I'd appreciate some pointers on what tags to use for this one - it's similar to code golf but isn't quite code golf. \$\endgroup\$
    – Scoots
    Dec 11, 2019 at 11:48
  • \$\begingroup\$ Similar but a slightly different scoring system \$\endgroup\$
    – Veskah
    Dec 11, 2019 at 13:02
  • \$\begingroup\$ This is two challenges: First, reading your own source code. Second, creating the score for an input string. In addition, the condition of "Parse yourself" is a non-observable requirement. In this case, it's definetly bad because it forces the two separate challenges approach onto people. I understand why you want to exclude print -45, but right now, the whole quine-except-not-really thing doesn't seem helpful. \$\endgroup\$ Dec 13, 2019 at 14:09
  • \$\begingroup\$ @AlienAtSystem Respectfully I disagree with your assertion that reading the source code is a challenge; I'm very explicit that any means of getting your source code in is acceptable, even copy/pasting it as a command line argument. The parsing of your own code - I thought it might encourage people to golf in a way they may not be used to due to the escalating penalties involved in the scoring system. \$\endgroup\$
    – Scoots
    Dec 13, 2019 at 15:36
  • 1
    \$\begingroup\$ If you don't want the source code reading to be part of the challenge, then don't write things like it is. Really just say Takes a string as input and outputs the uniqueness score and Your score is the return value of your program when given its own source as input. \$\endgroup\$ Dec 14, 2019 at 9:13
  • \$\begingroup\$ @AlienAtSystem I take your point, your phrasing is definitley better than what I originally had. \$\endgroup\$
    – Scoots
    Dec 14, 2019 at 11:32
0
\$\begingroup\$

Nash equilibrium of 2-player 3-choice zero-sum game

Background

In a 2-player single finite game, a Nash equilibrium (NE) is a pair of strategies chosen by both players where neither has an incentive to deviate from their own strategy. For example, here is a payoff matrix of two players \$ A,B \$ where each player has two possible pure strategies \$ X,Y \$:

$$ \matrix{ A \backslash B & X & Y \\ X & 3 \backslash 3 & 0 \backslash 0 \\ Y & 0 \backslash 0 & 2 \backslash 2 } $$

In this game, if \$ A \$ chooses \$ X \$, \$ B \$ should also choose \$ X \$ because it will give \$ B \$ the best outcome. Likewise, if \$ B \$ chooses \$ X \$, \$ A \$ should also choose \$ X \$. Therefore, \$ (X,X) \$ is a NE. We can observe \$ (Y,Y) \$ is also a NE; although it gives less outcome than \$ (X,X) \$ for both players, there is no reason to select \$ X \$ when the opponent selects \$ Y \$.

But a strategy can also be a mixed strategy, i.e. choosing one of the pure strategies with some chance. Let's take a mixed strategy \$ S = \frac25X+\frac35Y \$. If \$ A \$ takes \$ S \$, \$ B \$'s expected outcome is always \$ \frac65 \$, regardless of \$ B \$'s strategy (either pure or mixed). In this case, \$ B \$ has zero incentive to deviate from whatever strategy \$ B \$ is already taking. The same can be said for \$ B \$ taking \$ S \$, so \$ (S, S) \$ is also a NE.

Nash's existence theorem states that every game has at least one Nash equilibrium, either pure or mixed. Note that a game may have many (possibly infinitely many) NEs.

Challenge

In this challenge, we consider 2-player 3-choice zero-sum games, where each player has three possible pure strategies, and the sum of the two players' outcomes is always zero. The payoff matrix of such a game might look like this:

$$ \matrix{ A \backslash B & R & P & S \\ R & 0 \backslash 0 & -1 \backslash 1 & 1 \backslash -1 \\ P & 1 \backslash -1 & 0 \backslash 0 & -1 \backslash 1 \\ S & -1 \backslash 1 & 1 \backslash -1 & 0 \backslash 0 } $$

Since it is a zero-sum game, we can omit the payoffs of \$ B \$:

$$ \matrix{ A & R & P & S \\ R & 0 & -1 & 1 \\ P & 1 & 0 & -1 \\ S & -1 & 1 & 0 } $$

This game is equivalent to Rock-Paper-Scissors, and the only NE is, as we all know, mixed \$ (\frac13R + \frac13P + \frac13S,\frac13R + \frac13P + \frac13S) \$.

The challenge is to find at least one of the Nash equilibria, given the payoff matrix for player \$ A \$. Remember that a Nash equilibrium is a pair of \$ (\text{strategy of } A,\text{strategy of } B) \$.

For an outline of finding a mixed-strategy NE, refer to this Math.SE question. Also related: why some games don't have mixed-strategy NE.

Input and output

The input is a 3-by-3 matrix of integers which represent the payoff matrix for player \$ A \$. You can assume the magnitude of each integer won't exceed 100, and you can take the numbers in any order of your choice.

The output is a pair of strategies in the form of \$ (a_XX+a_YY+a_ZZ, b_XX+b_YY+b_ZZ) \$ where \$ a_i \$ and \$ b_i \$ are the chances of selecting one of the strategies. You don't need to format the output; outputting the 6 numbers \$ a_X,a_Y,a_Z,b_X,b_Y,b_Z \$ is fine. If you want to output a pure strategy, you can do something like \$ (1, 0, 0) \$.

Scoring and winning criterion

Standard rules apply. The shortest code in bytes wins.

Test cases

Matrix: (classic RPS)
  0  -1   1
  1   0  -1
 -1   1   0
NE: A's strategy = (1/3, 1/3, 1/3), B's strategy = (1/3, 1/3, 1/3)
--------------------------------------
Matrix: (scored RPS)
  0  -5   1
  5   0  -2
 -1   2   0
NE: A's strategy = (2/8, 1/8, 5/8), B's strategy = (2/8, 1/8, 5/8)
--------------------------------------
Matrix: (dumb game, pure strategy NE example)
  0   1   2
 -1   0   0
 -2   0   0
NE: A's strategy = (1, 0, 0), B's strategy = (1, 0, 0)
--------------------------------------
Matrix: (asymmetric game example, infinitely many NEs)
  2  -1   3
  0   3  -1
 -2  -3   0
NE: A's strategy = (1/2, 1/2, 0),
    B's strategy = any triple (x, y, z) that satisfies
                   x + 2z = 2y, x + y + z = 1, 0 <= x,y,z <= 1
--------------------------------------
Matrix: (asymmetric game example, one mixed NE)
  2  -1   4
  0   3  -1
 -2  -3   0
NE: A's strategy = (1/2, 1/2, 0), B's strategy = (2/3, 1/3, 0)

Meta

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

This is a repost of the underspecified challenge.

Task:

Remove all duplicates from one list of integers. A list is simply a sequence of connected values that allows the same values to be stored at different positions in this sequence.

If an item was found to be the same value as another item in this list, keep the first occurence of the item and remove the second (third and so on...) occurence of the item.

Input/Output

You may write a function or full program that takes a list as an input and returns a remove-duplicated list as an output.

Rules:

  • This is a challenge, so shortest answer wins!
\$\endgroup\$
0
\$\begingroup\$

Join two file paths

A file path consists of letters a-z separated by slashes /. Your task is to join two paths as follows:

  • If the second path doesn't start with /, concatenate them with exactly one / in between.
  • If the second path starts with /, just output it.

For example,

/User/Desktop   temp/file   ->  /User/Desktop/temp/file
/User/Desktop/  temp/file   ->  /User/Desktop/temp/file
/User/Desktop   /temp/file  ->  /temp/file
/User/Desktop/  /temp/file  ->  /temp/file
relative/path   more/path/  ->  relative/path/more/path

You may assume the inputs don't contain two consecutive slashes, but they may start or end with a slash. Each input with be nonempty and not just a slash. You may use backslash \ in places of slash /.

Sandbox: Is this too boring? Too likely a built-in?

\$\endgroup\$
1
  • \$\begingroup\$ (Replacing with a bit cleaner proof) Here's a neat way that I think works to show that anti-commutativity implies any product equals zero for \$S=\mathbb{Z}\$. We have \$ a * b = a * (b+0) = - (a * b) - (a * 0)\$, so \$ a * b \$ is half of \$-(a * 0)\$ in the standard integer sense. This implies that the product \$ a * b\$ doesn't depend in \$b\$ and so is just a function of \$a\$, say \$ a * b=A\$. Then, the anti-commutativity rule \$a * (b+c) = -(a*b + a*c) \$ gives \$A = - (A+A)\$ so \$A=0\$, and thus any product is \$0\$. \$\endgroup\$
    – xnor
    Jun 16, 2021 at 9:01
0
\$\begingroup\$

String Blockify™ a Hexagon

an obvious rip-off of Hexagonify™ a String Block

What is Hexagonification?

Hexagonification is a transformation that creates a hexagon with 3 copies of a rectangle block™, each skewed to the right by 30 degrees and then rotated by 0, 120 and 240 degrees respectively, as shown in the following image. A triangle hole may appear in the middle, but that isn't a great deal.

diagram of hexagonification

Challenge

Write a program or function that receives a hexagonified block of string™ as an input and outputs the original string block™. diagram of string blockification The input and output formats are flexible. You may receive a single string, a list of lines or a 2D array as input, and output a single string or a list of lines. You may have leading/trailing spaces on each line and leading/trailing newlines, provided that the block is properly formed. See Sample IO for how the blocks™ should be positioned.

Sample IO

Input:

   3 x 3
  e s q u
 u r a r e
3 q a a s 3
 x s r q x
  3 e u 3

Output:

3x3
squ
are

Input:

   l o n g e r . . . . .
  . r e c t a n g u l a r
 r . b l o c k . . . . . .
. a .                 b r l
 . l .               l e o
  . u .             o c n
   . g .           c t g
    . n k         k a e
     r a c       . n r
      e t o     . g .
       g c l   . u .
        n e b . l .
         o r . a .
          l . r .

Output:

longer.....
rectangular
block......

Input:

        v b
       8 e l
      x l r o
     2 a   t c
    k c     i k
   c i       c 2 
  o t         a x
 l r           l 8
b e l a c i t r e v
 v 8 x 2 k c o l b  

Output:

vb
el
ro
tc
ik
c2
ax
l8 

Input:

 1 . l i n e
e           1
 n         .
  i       l
   l     i
    .   n
     1 e

Output:

1.line

Input:

      1
     e .
    n   l
   i     i
  l       n
 .         e
1 e n i l . 1

Output:

1
.
l
i
n
e

Scoring

Your score will be the area of the source code as a String Block™. Assuming your code can just fit inside a rectangle of width \$w\$ and height \$h\$, the score will be:

$$w \cdot h$$

Winning Criteria

The submission with the lowest score in each language wins.

\$\endgroup\$
1
  • \$\begingroup\$ The obvious problem here is that the reverse challenge is "cluttered" with the information being available three times. The solutions won't profit from the structure being a full hexagon, one of the three skewed rectangles is enough. \$\endgroup\$ Dec 22, 2019 at 16:47
0
\$\begingroup\$

Joyous Kwanzaa!

Kwanzaa is an annual week-long celebration of African culture and history, and takes place on December 26 to January 1. During Kwanzaa it is traditional to light the seven candles of a kinara, one on each day. The middle candle is lit first, followed by the rest of the candles from left to right.

Challenge

Your challenge will be to write a program or function that when given ASCII art (in any convenient format) of candles on a kinara (as specified below), some of which may be lit, will return or output a ASCII art of what the kinara would look like on the next day.

Specification

A kinara will contain of seven even columns of equal length with equal spacing between them, representing the candles. The candles will be constructed with some consistent printable, non-whitespace ASCII character.

Some of the candles might have a flame above them, which will be represented by a single printable, non-whitespace ASCII character, possibly the same as the candle's character. If no candles are lit, there will be an empty line above the candles.

Here is an example of a kinara ASCII art:

*     *
| | | | | | |
| | | | | | |

Input/Output

The input will be a kinara with seven candles, 0-6 of them lit according to the rule (middle candle first, then the rest from left to right).

The output will be a kinara with candles and flames identical to the input kinara, but with one more lit candle than the input. The extra candle will be lit according to the rule. If no candles are lit in the input, you may use any character for the flame.

You may assume the input is valid according to the specification given. You may assume the input has no trailing or leading whitespace in any of the lines, but trailing or leading whitespace is acceptable in the output as long as the kinara has the proper shape.

Examples

In/out:

*     *
| | | | | | |
| | | | | | |

* *   *
| | | | | | |
| | | | | | |

In/out:

** *
|||||||

****
|||||||

In/out:

5 5 5 5
6 6 6 6 6 6 6
6 6 6 6 6 6 6

5 5 5 5 5
6 6 6 6 6 6 6
6 6 6 6 6 6 6

In/out:

               # pretend this is an empty line
q q q q q q q

      0
q q q q q q q

Rules

  • No standard loopholes

  • Shortest code in bytes wins

Questions

  • Is this too complicated? If so how could I simplify it?

  • Is the wording unclear?

  • Is this too similar to an existing challenge? I found another challenge which involves creating a menorah, but this one takes candles as input instead of a date.

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

Hit the most Balloons with one Arrow

You got 1 arrow to hit as much balloons as possible. A common way to solve this, is to mark the tangent points of every balloon and project the angles on the source's position. As seen in the following image this has been down already. The task is now to find the optimal and angle-centered solution to hit the most Balloons.

Balloon

The Input:

A json array of length 360 (for every 1° one entry) representating the number of Balloons hit at this angle.

JSON: https://pastebin.com/raw/Rd8g7Z6J

The Task:

Find an algorithm that solves the task with the following requirements:

  • return the number of most hits
  • return the max range of angles with the most hits
  • return the the centered angle of this range
  • there are no format restrictions how you are returning the values, it could be 3 prints or an array... whatever, as long as it is clear to see whats the hits, range and center

Solution of given JSON:

  • Most Hits: 6
  • Range: 358 - 0
  • Center: 359

Notes:

Remember its a circle, so you need to check if the range crosses the 360°/0° mark!!! A range can be like 300° - 10° for example.

For simplicity the angles are 0° - 359° as 360° would be 0°.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ That's a lot of words and a picture wasted because your challenge is really just "Find the longest max-value sequence in the array", which is probably a duplicate. I think the challenge would be a lot better if you actually had to calculate this angle distribution from an input of balloon coordinates and a size. \$\endgroup\$ Dec 23, 2019 at 6:29
0
\$\begingroup\$

Bunda-Gerth parser for abstract APL-family language

Background

APL has four kinds of tokens: arrays, functions, monadic operators (mops) and dyadic operators (dops).1) Let's denote them A (arrays), F (functions), M (mops), and D (dops) respectively. Usually when programming in APL, we use a mental model like this:

  • Strand notation: A A ... A -> A
  • Monadic function application: F A -> A
  • Dyadic function application: A F A -> A
  • Mop with left operand: (A|F) M -> F
  • Dop with both operands: (A|F) D (A|F) -> F
  • Mops and dops bind first from left to right (producing functions), and then function applications are evaluated from right to left

But J.D.Bunda and J.A.Gerth proposed another way to parse APL expressions. In this method, each (ordered) pair of tokens is assigned a binding strength and a resulting token. Below is the translation of the above mental model. Note that some token pairs do not bind at all, and we have a new token type AF, which stands for a function with bound left argument.

Binding strength | Token pair(s) -> result
--------------------------------------------
               5 | A A -> A        # Strand notation
               4 | D (A|F) -> M    # Dop + Right operand -> Mop
               3 | (A|F) M -> F    # Left operand + Mop  -> Function
               2 | A F -> AF       # Array + Function    -> Left-bound function
               1 | (F|AF) A -> A   # Function + Array    -> Array

Then the actual parsing proceeds as follows: given a stream of tokens,

  1. Evaluate the binding strengths between adjacent tokens.
  2. Select the token pair whose binding strength is the rightmost local "peak", i.e. the x y pair in w x y z satisfying wx < xy >= yz. w and/or z can be empty. Note that the leftmost pair is bound first in A A ... A.
  3. Group the pair and produce a new token as specified in the transition table.
  4. Repeat from 1 until single token is left (successful parse) or no more reduction is possible (syntax error).

Challenge

Given a list of tokens, output the order of binding (refer to the I/O section for specification) using the transition table and algorithm described above.

Input and output

The input is a non-empty list of A/F/M/D tokens. You may use any number or single character to represent a token. You may assume that the input will always parse successfully, and the input won't contain any parentheses (since it isn't specified in the table above).

For the output, the order of binding represents in which order each gap between the tokens is closed:

Given the tokens:       A A F M A
Assign each gap an ID:   w x y z
Binding strength:        5 2 3 0
Rightmost local peak:       F M
Bind them first:        A A (F M) A     -> y = 1
Bind A-A next:         (A A) (F M) A    -> w = 2
Bind A-F next:        ((A A) (F M)) A   -> x = 3
Bind AF-A last:      (((A A) (F M)) A)  -> z = 4

Given the tokens:       A A F M A
The order of binding:    2 3 1 4  (the answer)

Note that, if the input contains L tokens, the answer is always a permutation of 1..L-1 (or 0..L-2 if you choose zero-based numbering).

Scoring and winning criterion

Standard rules apply. The shortest code in bytes wins.

Test cases

Input:  A A A A A
Output:  1 2 3 4
-----------------------------
Input:  A F F A A F F A
Output:  6 7 5 2 3 4 1
-----------------------------
Input:  A  F D A A  M  A A D F M F A
Output:  11 9 8 7 10 12 3 4 2 5 6 1

Footnote

  1. An actual implementation of APL has some special tokens, e.g. dot ., jot , and index notation [x]. We ignore them here for simplicity.
\$\endgroup\$
5
  • \$\begingroup\$ Maybe an easy answer format is simply inserting the order of binding? A F F A A F F A((A F) (F (((A A) F) (F A))))((A5F)7(F6(((A1A)2F)4(F3A)))) and maybe even returning the permutation vector 5 7 6 1 2 4 3? \$\endgroup\$
    – Adám
    Dec 17, 2019 at 8:42
  • \$\begingroup\$ @Adám That could work, but I don't think it's any easier to produce than a fully structured output. Also, alternative algorithms can produce the same tree with different binding order. \$\endgroup\$
    – Bubbler
    Dec 17, 2019 at 23:27
  • \$\begingroup\$ It will be really hard to verify with the broad output allowance. Maybe just require fully parenthesising? \$\endgroup\$
    – Adám
    Dec 17, 2019 at 23:55
  • \$\begingroup\$ @Adám IMO it's not a problem, as long as the answers specify which output format they're using. \$\endgroup\$
    – Bubbler
    Dec 18, 2019 at 0:16
  • \$\begingroup\$ On second thought, I decided to emphasize the algorithm itself (over the resulting parse tree). \$\endgroup\$
    – Bubbler
    Dec 26, 2019 at 2:04
1
118 119
120
121 122
153

You must log in to answer this question.

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