# What is the Sandbox?

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

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

## Get the Sandbox Viewer to view the sandbox more easily

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

# Compute the order of a Rubik's Cube cycle without trivially counting them

I asked this question here the other day and it was closed as being a duplicate of another question which I had already linked in the original question followed by an explanation of a constraint that made the my challenge different. A discussion ensued in the comment section debating what made my question a duplicate of the other, mostly revolving around whether this constraint was observable or not.

I understand that the challenge at face value is an example of Do X without Y but I think it's still a quality challenge because:

1. The constraint does not simply exist to require people to come up with loopholes or clever workaround to preform avoid a particular commonly used feature of programming languages. It's not the same problem with an unrelated constraint to "make it interesting".

2. There really is no ambiguity in terms of whether or not the constraint is being followed for a particular answer. "Without Y" is not hard to define regardless of the language being used.

3. It changes entire approach needed for the algorithm itself, not just specifics of the implementation. The trivial solution to the question will automatically be preferred by golfers, so the answers of the "duplicate" were not very interesting to me because they mostly worked in the exact same way. By prohibiting this trivial approach, there is still a very wide range of different degrees of efficiency that are possible to achieve through different implementations, and some of these are likely better suited for some languages than others, so I feel the answers will actually show significant diversity in their implementations, which in my opinion is a hallmark of a high quality challenge.

I really think this constraint introduces a meaningfully different and interesting challenge when compared to the other question and I want to see the creative solutions that golfers will come up with to solve it. But as I originally wrote it, and even with the addition of edits I made to make it more clear, it was apparently not sufficient to reopen the question.

Can anyone think of a way to write this question or define the constraint in a way that would make it more clearly not a duplicate, or eliminate the problems brought up in the comments without restricting the implementation further?

Do you think I'm only facing this scrutiny because I'm a newer member who hasn't posted much? Would someone with more reputation that me be willing to post it on my behalf?

• There is no ambiguity, Isn't there though? How would you tell that this program is following the constraint without actually knowing Pyth? – Jo King Apr 10 '19 at 1:28
• @JoKing that’s not ambiguity. For example if a challenge were to prohibit the use of the a built in to_lower() function (which I’ve seen before on challenges with plenty of answers and upvotes) how would you know if a given answer was obeying that rule without actually knowing what a call to that language’s to_lower() function looked like? You wouldn’t, but that answer would still break the rules. But it wouldn’t be “ambiguous” because there’s still a clear difference between using such a built in function and not using one. – Conor Henry Apr 10 '19 at 2:12
• Banning built-ins is also an unobservable requirement, and is common in older questions. In general, the community is leaning towards avoiding banning built-ins. In general though, programs using built-ins are far far easier to distinguish than whether a program is using a specific algorithm. – Jo King Apr 10 '19 at 5:34
• The point of what I'm saying is that a constraint being unobservable is entirely different from there being cases where it's ambiguous if it's being followed. Whether or not an algorithm is obeying my constraint I suppose could be difficult to know immediately for some answers, especially if you're unfamiliar with the language it's written in, but at the same time the constraint is still defined quite clearly. Nobody reasonable person could possibly write an answer and not be sure if it is following this rule or not. That's what I mean by there's no ambiguity. – Conor Henry Apr 10 '19 at 19:10
• It is ambiguous if two people can have different opinions on whether it is following the constraint. For example, what is a simulated cube? Is it a literal Rubik's cube datatype like Cubically uses? Does a 5x5x5 sided cube still count as a Rubik's cube? Does a list of numbers count? Two vectors? Non-cube topologies? I'm sure some answerers will have different opinions to yours, and even if you define all the above cases, there's going to be infinitely more possibilities that skirt the line. – Jo King Apr 10 '19 at 22:00
• @JoKing A simulated cube is any data structure(s) that represents the state of a 3x3x3 rubik's cube, and is manipulated to represent the changes caused by preforming valid turns. A simulated 5x5x5 Rubik's would be a simulated cube because you can turn a 5x5x5 into a 3x3x3 by just removing stickers (or in the case of a data structure, ignoring them). As for a list of numbers, or two vectors, etc, if the purpose is to of it is to represent the state of the cube, and it is manipulated to simulate preforming valid moves on it, it's a simulated cube. Do you still think this is ambiguous? – Conor Henry Apr 10 '19 at 22:06
• @JoKing Can you think of an example of an algorithm where you feel there could be reasonable, legitimate debate, as to whether or not it counts as "Performing the turns repeatedly on a simulated cube and counting the repetitions that were needed to reach the original state"? – Conor Henry Apr 10 '19 at 22:11
• Maybe the challenge could be for an NNN cube with N as an input? Then, some limit on complexity or run-time should be able to weed out programs that just iterate through the cycle. – xnor Apr 13 '19 at 3:58
• In the context of this site, we generally use "observable" to mean observable without looking at the code. So even if there's a strong argument that a constraint could be determined unambiguously, it's still a quality of the code, rather than of the output. I'm not aware of an outright rule against this, but it is generally advised against because it leads to unexpected arguments once the answers start coming in. The exceptions that are more likely to be welcomed are the trivial constraints like "source code is a palindrome" or "does not contain the letter e" – trichoplax Apr 24 '19 at 22:34
• Personally I'd lean away from even those as they tend to suit a smaller set of languages. So there isn't a rule preventing you placing constraints on the source code, but it makes it more likely your challenge will be closed as unclear, so it might be worth considering what alternatives might achieve your underlying aim without the risk of arguments over what counts. – trichoplax Apr 24 '19 at 22:37
• For example, some challenges exclude the simplest brute force approaches by saying "must complete within 60 seconds for each of the test cases" (the time period being chosen to be very easily achievable for most approaches, so that it doesn't even matter what machine is used to measure the time taken). That's still not perfect but seems to have worked well on several past challenges. – trichoplax Apr 24 '19 at 22:39
• I can't think of a similar way of achieving your stated constraint without explicitly including it in the spec, but I thought I'd mention this example in case it prompts someone to think of a similar approach that could work here. – trichoplax Apr 24 '19 at 22:42

# Product and Sum free set

Given some non-negative integer $$\n\$$ find a sum- and product-free subset $$\S \subset \mathbb N = \{1,2,3,\ldots \}\$$ of size $$\|S|=n\$$

EDIT: with the least possible maximum $$\\max_{s\in S} s\$$.

### Details

• A set $$\S\$$ is called sum-free if for all $$\a,b\in S\$$ their sum $$\a+b \not \in S\$$.
• A set $$\S\$$ is called product-free if for all $$\a,b\in S\$$ their product $$\a\cdot b \not \in S\$$.

related

### Examples

Note that the sets for each $$\n\$$ might not necessarily be unique.

  n  S
1  {2}
2  {2,3}
3  {3,4,5}
5  {4,5,6,7}


EDIT: Ok, no this doesn't work either.

• I'm a bit concerned that this would just be output the first n odd primes, but maybe non-golfing languages can do something more interesting than that. – Emigna Feb 26 '19 at 10:09
• @Emigna Thanks for the feedback, you're right this is not something I considered. Maybe it helps if we allow any number of additions/multiplications? But in this case I think you could just use [k+1,k+2,k+3,...,n] for some large enough k (depending on n). Maybe I should add some condition that requires the numbers to be very small to make it more interesting. It definitely needs some more work. – flawr Feb 26 '19 at 10:42
• You can make this work by having a secondary scoring algorithm. You could, for example, score the programs by {bytes}*{total score for n=1 to 100}, where the score for an input is the highest number in the output set. – Spitemaster Feb 27 '19 at 18:28
• Also note that the set {1} is not product free - 1*1=1, which is in {1}. – Spitemaster Feb 27 '19 at 18:29

### Use input letters to create as many words as possible

I have the scrabble letters as magnets on my fridge and I was thinking: how many actual words could I make using only these letters. Obviously it would be hard to work out myself, so I challenge you to create a program which will take a string of characters as input, and your goal is to output as many words as possible using those characters.

### Input

• The characters will be one string
• Only the 26 letters of the alphabet will appear.
• Letters may appear more than once
• Letters can appear in any order. 5 e's might appear next to each other, and there might be other e's in the string.
• There will always be at least a single letter, but it might not always be possible to create a valid word

Example, using the letters from Scrabble:

eeeeeeeeeeeaaaaaaaaaiiiiiiiiioooooooonnnnnnrrrrrrttttttllllssssuuuuddddgggbbccmmppffhhvvwwyykjxqz

### Output

A list of valid English words, which you can separate with a space, newline or comma. A trailing newline at the end is fine.

### Meta discussion (not apart of the question)

• Is a decent challenge for this? I'm more interested in more words being output than I am short code, but how best can I frame this challenge that the best result would be most words created and fewest characters left?
• Should I restrict the input list to just the letters from Scrabble? I mean how can I evaluate whether a program prints as many as possible?
• Should I provide a word list? I know there are challenges on this site where a word list is provided 1 and 2 and I'm sure there are a few others which I could not find.
• This is my third question, so any other feedback
• I would highly recommend including the wordlist as an input and including a few trivial test cases so that people can easily test their answers. – Jo King Apr 26 '19 at 7:45
• Not including the word list as input would benefit languages which have dictionary built-ins - everyone else would have to have a list of all English words in the code, which might be a little long, even given really good compression... – Matthew Apr 26 '19 at 8:28
• Allow any reasonable output format rather than just text. Pass in word lists and letter sets as arguments. Making both constant turns this into a kolmogorov-complexity challenge. – Beefster May 1 '19 at 17:53

# Hungry Blobs KoTH

This KoTH is inspired by Primer's Natural Selection Simulation. Your bot is a blob. In order to survive, you must eat pellets to regain energy. You can use additional energy to buy upgraded traits, like increased size (to eat smaller blobs), increased or decreased speed (also changes energy usage rate), or increased sight. Additionally, blobs can use energy to split into two blobs, which are "relatives".

### Energy and Movement

Your blob starts off each round with 100 energy, and it has no limit on the amount of energy it can collect. The game is run in turns, with each blob having the option to move North, East, South, or West in any given turn, or stand still. Moving by defualt uses 1 energy, with standing still using 0.25 energy. The map's side length is ceil(0.25 * blobCount) * 2 - 1 units, with a minimum of 9 units. All blobs start on the edge of the map, with one placed in each corner and every subsequent blob being placed 2 units away from any others. Every 40 turns, a wave of circular pellets with a diameter of 0.8 are placed in random spots around the map, at least 1 unit from any edge. Each time a wave of pellets appears, the quantity of pellets (originally twice the number of blobs) in the next wave is decreased by 1, forcing the number of blobs to decrease over time. Each pellet restores between 25 and 35 energy. When a blob's energy is less than or equal to 0, it dies.

### Speed

Blobs move in cardinal direactions at a rate of 1 unit/turn. A blob can sacrafice 40 energy in order to change its speed by 20%, up or down. Note that this is exponential, so a blob's speed will never reach 0 if decreasing, and speed up more each time it upgrades. The amount of energy used in a turn is equal to the square of the blob's speed, unless it does not move (it is then 1/4 of the normal amount).

### Size

Every blob starts at size 1. For 45 energy, the blob's size can be increased by 20%. Blobs are circular, with their diameter equal to their size. If two blobs overlap, the larger one will consume energy of the smaller one. The amount of energy consumed is smallEnergy * (bigSize - smallSize) / smallSize. Therefore, the energy of the smaller blob will never be completely consumed by the larger one, and instead will decrease until the energy usage per turn kills the blob. As with speed, size comes at a cost. The speed at which the blob moves is divided by its size, but the energy cost stays the same. Therefore, with a speed of 1.2 and a size of 1.2, the blob moves at the equivalent of speed 1 with the energy usage of speed 1.2.

### Detection and Information

Blobs can see any pellets or other blobs within a distance of 3 units, plus half of the blob's size. For 35 energy, a blob can increase its search radius by 1 unit. When their functions are called, blobs are provided with:

• The side length of the map
• The position of the blob on the map
• The positions of all pellets within their search radius, as well as their values
• The positions of all blobs within their search radius, as well as their sizes and UIDs
• The speed, size, search radius, and UID of the blob
• A storage object unique to the blob
• A storage object shared by all blobs related to the blob through splitting

### Splitting

As the challenge continues, the number of blobs decreases as starvation and hunting kills off blobs. In order to keep the map populated and continue the challenge, a blob can choose to split. Splitting costs 100 energy, and any remaining energy is divided evenly between the two blobs. The new blob keeps the size, speed, and detection distance of the original, and shares a communal storage object with all of its relatives. If one blob upgrades its traits or splits, it does not affect others (though the new blob still shares the communal object with all other relatives). Related blobs can still consume energy from each other.

### Functions, Storage, and UIDs

In order to allow more complex learning behaviors, all blobs will be given an integer UID (Unique Identifer). These UIDs will be randomly generated each map, preventing strategies based on individual targets. When a blob's function is called, it is passed four objects:

1. The side length of the map
2. An object with two arrays: pellets, and blobs. Both arrays contain objects, both having a pos property containing the pellet or blob's position formatted as [x,y]. Pellets will have an energy property, while blobs will have a size property and a uid property
3. An object containing various properties of the blob it is passed to: speed, size, searchRadius, uid, and pos. The pos array is formatted as [x,y]
4. An object containing the two storage objects of the blob. A self property contains an individual storage object which can be modified however the blob sees fit (by manipulating properties of the object that is passed), and a communal property which can be modified by any relative.

Blobs are not moved immediately. The direction they return is recorded, and all blobs are moved at the same time after all are finished and before things like energy consumption are processed. In the event multiple blobs land on a pellet, the one closest to its center (relative to the center of the blob) receives it. If a blob lands on a pellet or smaller blob and, in the process uses its last energy, the blob will still consume the pellet/energy independent of whether that would would bring its total energy above 0.

In order for "relative" blobs to recognize one another, the communal storage must be used for each blob to record its UID in an array, or through some other system.

In order to move or make purchases for upgrades to traits, the return value of the function is used. First, the meaning of the cardinal directions in terms of coordinates:

• North = -Y
• East = +X
• South = +Y
• West = -X

Note that [0,0] is the top left corner, and Y increases as you go down. The return value of the function should follow these rules:

• To do Nothing: Return nothing, 0, null, undefined, false, or any other value that equates to false
• To Move: Return one of four global variables: North, East, South, or West, which equate to "north", "east", "south", or "west" (which could also be used as a return value)
• To Upgrade a Trait: Return one of four global variables: SpeedUp, SpeedDown, SizeUp, or SenseDistUp
• To Split: Return the global variable Split

If an upgrade or split command is returned and the amount of energy required is greater than or equal to the energy of the blob, nothing will happen. If any part of a blob would be placed outside of the map by moving, it will move only so far that it reaches the edge exactly.

### Predefined Library Functions

There are a few basic functions available by default, to save some time:

taxiDist(pt1, pt2, step = 1)

Returns the taxicab distance between two points (X distance plus Y distance), with an optional step parameter for distance each step travels (speed).

taxiDist([0, 0], [2, 2]) //4
taxiDist([3, 4], [1, 5]) //3
taxiDist([1.25, 1.3], [1.3, 1.4]) //0.15
taxiDist([0, 0], [5, 2.5], 2.5) //3
taxiDist([0, 0], [2, 4], 2.5) //2.4


hypotDist(pt1, pt2)

Returns distance between two points according to the pythagorean theorem

hypotDist([0, 0], [5, 12]) //13
hypotDist([4, 6], [8, 9]) //5
hypotDist([0, 1], [2, 1]) //2
hypotDist([1, 1], [2, 2]) //sqrt(2)


modDist(dist, amt)

Takes the inputted distance, rotates 90 degrees clockwise amt times, then returns the new value.

modDist(North, 1) //East
modDist(East, 2) //West
modDist(West, 3) //South
modDist(South, 4) //South


### Example Blob

This blob will not move until it finds a pellet nearby. Then, it will move in the direction it thinks is most likely to reward it. If its energy is above 90, it will increase its sense distance. If its energy is ever above 110, it will split.

function(map, near, me, storage) {
if (me.energy > 110)
return Split;
if (me.energy > 90)
return SenseDistUp;
if (!near.pellets.length)
return null;
var dirs = [0, 0, 0, 0];
for (let p, i = 0; i < near.pellets.length; i++) {
p = near.pellets[i];
dirs[0] += me.pos[1] - p.pos[1];
dirs[1] += p.pos[0] - me.pos[0];
dirs[2] += p.pos[1] - me.pos[1];
dirs[3] += me.pos[0] - p.pos[0];
}
return [North, East, South, West][dirs.indexOf(Math.max(...dirs))];
}


### Rules

• Standard Loopholes are prohibited. Also, no Unstandard Loopholes.
• No blob may attempt to modify or read any data not passed to it via its parameters
• No blob may attempt to modify a return-value variable to sabotage other blobs
• A round lasts until the only remaining blobs are relatives
• No blob may modify data by injecting functions into its parameters which modify values using the this keyword
• All submissions must either be in Javascript or a language which is not too different from Javascript (Python, for example). All answers will be converted to Javascript for the competition.
• The winner is the blob which has collected the highest amount of energy in total across all rounds (from either pellets or consuming smaller blobs)
• Now that you've posted to Main, don't forget to edit your post here to shrink it and then delete it to save space. Thanks! – AdmBorkBork May 7 '19 at 19:39

# Who's serving in table tennis?

Table tennis, also known as ping pong, is a well-known game in which players hit a ball back and forth across a table. One player serves the ball twice, and each time the ball is served, either player can score a point. Once the first player serves the ball twice, the second player gets to serve twice. Every two serves, the player which serves the ball switches. The game ends when one player has a score of 11 or more points and is two or more points higher than the other player.

Your task is to take the current score as input, and output a value depending on if player 1 should serve, player 2 should serve, or the game is over.

Input: The score of the first player to serve followed by the score of the other player. This can be as separate values or in a list, or another convenient data type.

Output: A distinct value for each possible case of output. For the test cases, I will use 1 to represent the player who serves first, 2 to represent the other player, and 0 to represent that the game is over.

Test cases:

player1score, player2score -> output

2, 0    ->  2
0, 0    ->  1
11, 0   ->  0
4, 4    ->  1
3, 2    ->  1
6, 9    ->  2
81, 82  ->  2
0, 29   ->  0
16, 13  ->  0


# Alternating Digit Divisibility

TODO: Could use a better title..

## Challenge:

Given a list of positive integer $$\L\$$ with at least two integers, output a list of digits which alternating divide either number itself evenly, of the sum of the digits of this number. The alternating can be done [sum_of_digits, number_itself, sum_of_digits, ...], or [number_itself, sum_of_digits, number_itself, ...]
This no doubt sounds pretty vague, so here an example:

Input: $$\L=[611,044,381]\$$
Output: $$\[[1,2,4],[1]]\$$ (or $$\[1,2,4,1]\$$ or $$\[1,2,4]\$$)

The two alterations are one of these two possibilities:

[8,44,12]      [sum([6,1,1]),  044, sum([3,8,1])]
[611,8,381]    [611, sum([0,4,4]), 381]


As for which digits can divide these numbers:

[8,44,12]    →  [[1,2,4,8], [1,2,4], [1,2,3,4,6]]
[611,8,381]  →  [[1], [1,2,4], [1,3]]


Where the divisible digits that are present in all sublists of the lists are:

[1,2,4]
[1]


## Challenge rules:

• I/O is flexible. Input can be a list of strings, integers, 2D list of digits, etc. Output can be a list of lists of digits, a single flattened list of digits, a single flattened and uniquified list of digits, two lists printed on separated lines, a string, etc. The order of the outputs also doesn't matter, but state which one you've used in your answer.

## General rules:

• This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
• Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
• Default Loopholes are forbidden.

## Test cases:

Input:                      Output:

[611,044,381]               [[1,2,4]], [1]]
[200,32000,4000]            [[1,2], [1,5]]


TODO: More to come, including some larger ones

# Help the library sort books

A library needs to sort its books, located in separate sections by language. Of course, each language has its own rule for collating strings, so your method should handle that ability.

Most languages will want to treat titles case-insensitively, but unfortunately, the library has a section of Klingon books. And Klingon's romanisation, in case you don't already know, is case-sensitive. As a result, you need to give a way to have the sorter treat two given characters as the same.

Some of the titles also contain numbers, and you need to deal with those as well. Fortunately, the friendly people at the library have written some functions for you to deal with that, so all you have to do is take in a handle to a function as one of your inputs.

Your challenge: Sort a list of book titles, given a collating sequence and a function handle that converts a number to its string representation in the respective language.

• The collating sequence is a list of lists of strings. Given two strings A and B that appear respectively in the entries at indices i and j, respectively:
• if i > j, then A should sort after B
• if i = j, then A should sort the same as B
• In case some elements of the sequence have multiple characters, use the max-munch rule to tokenise the string: e.g. if both l and ll appear in the collating sequence, then lll should be tokenised to ll l.
• Any string of digits should be parsed as a number and passed to the callback. Each such string should be replaced by the result.
• Any characters not appearing in the collating sequence should be ignored. If two strings differ only by such characters, then sort them however you like.

## Test cases

Assuming

english_letters = [["A", "a"], ["B", "b"], ["C", "c"], ["D", "d"], ["E", "e"], ["F", "f"], ["G", "g"], ["H", "h"], ["I", "i"], ["J", "j"], ["K", "k"], ["L", "l"], ["M", "m"], ["N", "n"], ["O", "o"], ["P", "p"], ["Q", "q"], ["R", "r"], ["S", "s"], ["T", "t"], ["U", "u"], ["V", "v"], ["W", "w"], ["X", "x"], ["Y", "y"], ["Z", "z"]]
arka_letters = [["t"], ["k"], ["x"], ["s"], ["n"], ["v"], ["f"], ["m"], ["d"], ["g"], ["p"], ["b"], ["h"], ["y"], ["c"], ["r"], ["z"], ["j"], ["w"], ["l"]]
function english_num_callback(num) {
// convert a number to its representation in English
}
function arka_num_callback(num) { // handles nonnegative integers up to 9999
if (num == 0) return "yuu";
let kot = 0 | (num / 1000);
let gal = 0 | (num / 100 % 10);
let on = 0 | (num / 10 % 10);
let ko = num % 10;
let digits = ["yuu", "ko", "ta", "vi", "val", "lin", "kis", "nol", "ten", "los"];
return (kot == 0 ? "" : digits[kot] + "kot") +
(gal == 0 ? "" : digits[gal] + "gal") +
(on == 0 ? "" : digits[on] + "on") +
(ko == 0 ? "" : digits[ko]);
}

["Stack Exchange", "BB94 Channel!", "BB guns: all you wanted to know about them",
"carrots", "A Grammar of Jbl", "69"], english_letters, english_num_callback =>
["A Grammar of Jbl", "BB guns: all you wanted to know about them", "BB94 Channel!",
"carrots", "69", "Stack Exchange"]
["melidia", "diaklel", "44 miiko", "I Mess With the Librarians", "an isk ris tu lei",
"lei e xion", "xagrisren et xep!", "on melkadren"], arka_letters, arka_num_callback =>
["xagrisren et xep!", "44 miiko", "melidia", "diaklel", "lei e xion",
"an isk ris tu lei", "on melkadren", "I Mess With the Librarians"]


## Will it be red sauce, brown sauce, or no sauce at all?

Unfortunately Danny Baker's Sausage Sandwich game has been taken off the air again, and I'm suffering from withdrawal already. Please alleviate my symptoms by writing a program or function to play the Sausage Sandwich game.

You need to guess how the target prefers to eat a sausage sandwich, given one of the three sauce options. Given an input positive integer n, then the following applies:

• There is a uniformly 1 in n chance that the target chooses no sauce at all.
• Otherwise, there are equal chances of red sauce or brown sauce.
• However, if n is even, then there are n-1 remaining chances, which don't divide by 2. If you draw this n-1th chance you should consistently (for a given n) output the same answer. Please indicate how this is chosen in your answer.
• Output must consist of the phrases "red sauce", "brown sauce", or "no sauce at all", in any of lower, sentence, title or upper case.

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

# Print the Golfican sequence

The Golfican sequence is a sequence of integers, $$\u\$$, defined as follows:

• If $$\n\$$ is a power of $$\2\$$, then $$\u_n=\log_2n+1\$$.
• If $$\n\$$ in not a power of $$\2\$$, then $$\u_n=u_p\$$, where $$\p\$$ is the number of numbers from $$\1\$$ to $$\n\$$ inclusive which are not powers of $$\2\$$.

So, the first numbers in this sequence are $$\1,2,1,3,2,1,3,4\$$ and so on. Your job is to write a program which takes a number, $$\x\$$, as input, and outputs $$\u_x\$$. This is , so the shortest program in bytes wins.

I couldn't find a corresponding OEIS sequence for this. Thoughts?

• So $p = n - 1 - \lfloor \log_2 n\rfloor = n - u_{b(n)} = n - \ell(n)$ where $b(n)$ is the largest power of 2 less than $n$ and $\ell(n)$ is the length of $n$ in base 2? – Peter Taylor May 17 '19 at 8:27
• I suppose it would be. – RamenChef May 17 '19 at 16:36
• (1) IMO the multiple-box requirement is essential to make it an interesting question. Otherwise it's just the hundredth shortest path question, and probably should be closed as a dupe. (2) "If your solution can only retrieve the first box, 10x penalty" is a really bad idea. See Things to avoid when writing challenges: chameleon questions, bonuses in code golf. – Peter Taylor May 17 '19 at 10:34
• @PeterTaylor: Thanks, I've removed the bonuses and outlawed brute force. – Phil H May 17 '19 at 10:55
• Banning brute force is also discouraged, as a non-observable requirement. Some people use a time limit to rule out the slowest kinds of brute force instead. For example, must process any of the test cases in under 1 minute (the time limit being chosen generous enough to make no difference to most approaches, so it doesn't even matter which computer it's measured on) – trichoplax May 18 '19 at 16:28
• @trichoplax: I've modified to replace the brute force note with a time limit – Phil H May 20 '19 at 13:42

# Balanced City Splitting

Right now, there exist N cities that are connected by N - 1 roads in a tree. All is well, but unfortunately, the country's infrastructure is unable to support so many cities and as the population has gone down, it is both practical and necessary to close exactly one city. However, as people migrate to larger areas, the government wants to make sure no remaining cluster of cities is too much larger than the other ones (closing a city also closes all of the roads connected to it).

Let there be N cities. Choose a city v. Then, S is the set of the sizes of the remaining subtrees after v and all edges connected to it are deleted. The score for v is max(S) - min(S). Find the minimum possible score for any city v if v is not a leaf node (because then S = {N - 1} and this isn't even a problem).

# Examples

N = 5

1 2
1 3
1 4
1 5


The minimum score for this would be 0; if you remove 1, then you are left with 4 subtrees each of size 1. The final minimum score is 0.

N = 9

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


If you removed 2 or 7 (it's symmetrical), you'd be left with subtree sizes 1, 1, 6. If you remove 4, you're left with 1, 1, 3, 3. Neither is that great, but of those choices, 4 is the best and your minimum score is 2.

# Rules

This is so the shortest code in bytes wins.

Standard loopholes apply. You may take input in any reasonable format and your output should be a single integer. Input constraints will be something reasonable; if your program can't handle regular 32-bit integers, please specify the constraint and I will accept it if it's reasonable enough. Your solution must theoretically work for any input though.

# Sandbox

• is the problem spec clear enough?
• I will probably add more examples
• Can't this be done rather easily in O(n)? For fastest code the I/O performance would be the bottleneck. – user202729 May 22 '19 at 3:59
• @user202729 I'll have to think about that; that might be true. I remember I solved it in theory at some point (untested); if so I'll just make it code-golf. – HyperNeutrino May 22 '19 at 4:00
• The test data should be publicly available so that the scoring is objective. – Peter Taylor May 23 '19 at 14:50
• It's quite easy to do in linear time: pick an arbitrary vertex at which to root the tree and perform DFS, labelling each vertex with the size of the subtree rooted there. Then for each vertex the sizes of the parts remaining if you delete it are the sizes of its children and n-1 minus the sizes of its children; the latter can be calculated and the min and max found in time linear in the number of children, and the sum of the number of children over all vertices is linear in the number of vertices because it's a tree. – Peter Taylor May 23 '19 at 15:12
• @PeterTaylor Right. i remember how to do this now. Thanks, I'll make it code-golf and make examples public once I make them – HyperNeutrino May 23 '19 at 23:16

# Output efficient Church encodings of natural numbers

The Church encoding of a natural number $$\n\$$ in lambda calculus is the higher-order function which takes a function $$\f\$$ to its $$\n\$$-fold iterate $$\f^n = f \circ \cdots \circ f\$$. For example,

0 = \f.\x.x
1 = \f.\x.f x
2 = \f.\x.f (f x)
3 = \f.\x.f (f (f x))
...


## Challenge

Write a function or program which takes a natural number $$\n\$$ and outputs a lambda calculus expression which is $$\\beta\eta\$$-equivalent to the Church encoding of $$\n\$$.

## Input

Any natural number, including possibly 0.

## Output

A lambda calculus expression in any format of your choosing, as long as it's an encoding that is pure data, or an equivalent in your programming language (e.g. if you wanted to write a submission in lambda calculus itself, the output must be a term which has a normal-form equivalent). Acceptable types of output would include a string or a data structure.

Whatever output format you choose, it must be a format which unambiguously maps to lambda calculus terms, and allows specifying any general lambda calculus term. You must then specify the mapping.

One possibility for a somewhat compact string encoding of typical lambda calculus terms would include terms such as:

$$0=\f x.x)(compose f g=\x.f(g x))(succ n=\f.compose f (n f)).succ(succ(succ(succ 0)))  Here, \ represents a lambda; lambda binding is considered right-associative; and function application is written as a concatenation and is considered left-associative. Then for example, \v1 v2 v3.body is syntactic sugar for \v1.\v2.\v3.body. As in the above example, this language also has syntactic sugar for let-style expressions where \(f a1 ... an=fbody).letbody (which in more verbose languages might be read as let f a1 ... an=fbody in letbody) is syntactic sugar for (\f.letbody)(\a1 ... an.fbody). ## Requirements The crucial part of the challenge is that the encoding must be efficient: the output for input $$\n\$$ must be of length or total size $$\O(\log n)\$$. ## Scoring This is : shortest submission in bytes wins. (In case of a tie, I might compare the "lambda complexity" of the outputs for input 2019, defined as the number of function applications plus the number of lambdas plus the number of variable terms excluding variables in lambda binders.) ## Sandbox questions I'm wondering whether the output format specification might be too lax. (For example, what if somebody gets a shorter submission using highly nonstandard syntax such as specifying that function application is right associative instead of left associative, so instead of s(s(s(s 0))) they could write s s s s 0?) On the other hand, if I required my "lambda calculus with syntactic sugar" format, then that might be considered akin to "here's my newly invented language, try golfing in it" which I'd think would be frowned on. Plus it might disadvantage languages which are good for golfing data structure creation but not as good for golfing output formatting. # Optimize Grocery Bagging You've gone to the store and are at the checkout. Now since you want to be environmentally conscious (or are somewhere that charges for bags and want to save money), you've brought a few reusable bags and would like to minimize the number of plastic bags you use (There are no paper bags here). Each reusable bag can carry 5 kg (5,000 grams) of groceries and each plastic bag can carry 2.5 kg (2,500 grams) of groceries. You will be given a list of weights of groceries (in whole grams) and a number of reusable bags and your task is to output a configuration of bagging that requires the fewest number of plastic bags. ## Examples • Input: 1 reusable bag, groceries: [150, 500, 800, 1250, 2000, 300, 550, 400, 750, 900, 1000, 600] • Output: Reusable[2000, 1250, 1000, 750], Plastic[600, 900, 550, 150, 300], Plastic[500, 800, 400] More TBD ## Rules and Assumptions • Standard rules and loopholes apply • Any convenient input or output method is acceptable as long as which bags are reusable is unambiguous in the output (without calculating anything). • You may assume that there are no groceries larger than 2.5 kg. (No jugs of milk) • All groceries listed require a bag. Unbaggable groceries will not be listed. (No hypothetical 24-packs of toilet paper) • Any grocery item can be bagged with any other. (No need to worry about bread and cans of beans being in the same bag) • Groceries cannot be split into multiple bags. • There is no double-bagging. • Complexity doesn't matter. There may be inputs that would require computation past the heat death of the universe to complete. Happy Golfing! Related Sandbox: This could work as a problem or due to the naive solution being in $$\O(n!)\$$. Thoughts? • – jimmy23013 May 28 '19 at 22:39 • This is NP-hard. – jimmy23013 May 28 '19 at 22:40 • @jimmy23013 yes, indeed. If this were shifted to fastest-code it would necessarily drop the "guaranteed optimality" requirement. – Beefster May 28 '19 at 23:13 • @jimmy23013 I guess this is only different from that linked challenge in that there are two bag capacities instead of just one. – Beefster May 28 '19 at 23:17 • Do you mean requiring the minimum number of bags? If not required optimal, how do you decide whether an answer is valid? – jimmy23013 May 28 '19 at 23:18 • As I remembered (USACO fence8), fast solutions to this problem may use strategies depending on the input data (e.g. try putting heavier things in bags first). You may have to specify exactly how it is scored if you change it to fastest-code. – jimmy23013 May 28 '19 at 23:22 # Beziér me a curve! Task: Create a program that will, given a number N, create a Beziér curve with N control points and output its equation. The definition of a Beziér curve is $$B(t) = \sum_{i=0}^n{{n\choose i}(1-t)^{n-i}t^iP_i}$$ Practically, this means that for a quadratic Beziér cuve: $$B(2) = \sum_{i=0}^2{{2\choose i}(1-t)^{2-i}t^iP_i}\\ B(2) = {2\choose 0}(1-t)^2P_0 + {2\choose 1}(1-t)tP_1 + {2\choose 2}t^2P_2\\ B(2) = (t^2-2t+1)P_0 + 2(t^2-2t+1)P_1 + t^2P_2\\ B(2) = P_0t^2-2P_0t+P_0 + 2P_1t^2-4P_1t+2P_1 + P_2t^2$$ where $$\P_0\$$ is the first control point, $$\P_1\$$ is the second control point and $$\P_2\$$ is the third control point. Note that De Casteljau's algorithm may be useful. ## Rules • The input will be a number (string or number). • The output will be a list of lists. Take an element $$\l_n\$$ of the top-level list. The elements of $$\l_n\$$ will be all the terms that, in the expanded form, are multiplied by $$\P_n\$$. -1t and t^1, as well as t^0 are all fine. • Standard loopholes are not allowed. ## Test cases 2: [ ["t^2", "-2t", "1"], ["2t^2", "-4t", "2"], ["t^2"] ]  5: [ ["-t^5", "5t^4", "-10t^3", "10t^2", "-5t", "1"], ["t^5", "-4t^4", "6t^3", "-4t^2", "t"], ["t^5", "2t^4", "t^3"], ["-t^5", "t^4"], ["t^5"] ]  The program with the shortest length wins. Be creative! • It would be more accurate (and IMO less confusing) to say that the task is to output the Bernstein basis polynomials of degree n, b_{a,n}(t) = \sum_{k=a}^n (-1)^{a+k} \binom{n}{k} \binom{k}{a} t^k In line with Avoid cumbersome I/O formats I would also suggest outputting the polynomials as lists of coefficients, i.e. as a double array / matrix with A_{ij} = (-1)^{i+j} \binom{n}{i,j}. However, all of this is moot because now that I've rewritten it like that I see it's a dupe of codegolf.stackexchange.com/q/69424/194 – Peter Taylor May 29 '19 at 8:22 # Reading the text of the millitext font There is a font here that fits each character into a single, 1x5 pixel block. It does this (assuming you're using an LCD screen) by using the RGB channels of each pixel to expand the one pixel into three subcolumns, one for each channel. Your task is to take in a string of text that describes this font and return the correspond text encoded. # Millitext Alphabet CHARACTER: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ ENCODING: WYWBMRRMMMWYWYWWWMWBMRMYGYGYCWMMMMMW MGBWMRRMMMMMRMRRRMGBMRWMMMMMRGMMMMMB MGWWWWWBWWWYRMWWMWGBYRWMMYMYGGMMWGGG MGRBBBMBMBMMRMRRMMGBMRMMMRWMBGMCWMGR WWWWBWWBWWMYWYWRWMWWMWMMGRCMYGWBMMGW  I've abbreviated each color to a one character symbol (R=red, G=green, B=blue, C=cyan, Y=yellow, M=magenta, W=white). # Input Format The input format for this is pretty open. You can have the input be an array containing each column, an array containing each row, a char[][], or anything like that. You can also choose to use the full words "red", "green", "blue", with uppercase/lowercase of your choice (but it must be consistent for each word! You cannot use "RED" and also do "green" or "Blue"). If your language happens to support it, you can also have input be colors (however that might work, I don't know off-hand). You can assume that the input will ONLY contain encoded characters in the alphabet above (in particular, there will be no spaces or punctuation in your output). # Output Format You can either output a string or some sort of character array. You can chose whether the letters are uppercase or lowercase, but they must all have the same case. # Example MWRRGMGYRY MRRRMMMMRM WWRRMWMYRM -> HELLOWORLD MRRRMWMMRM MWWWGMGMMY  # Rules This is code golf, so shortest answer wins! # Test set WYWBMRRMMMWYWYWWWMWBMRMYGYGYCWMMMMMW MGBWMRRMMMMMRMRRRMGBMRWMMMMMRGMMMMMB MGWWWWWBWWWYRMWWMWGBYRWMMYMYGGMMWGGG -> THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOG MGRBBBMBMBMMRMRRMMGBMRMMMRWMBGMCWMGR WWWWBWWBWWMYWYWRWMWWMWMMGRCMYGWBMMGW  # I Love U So Much! Just print i love u, or I Love U. But, because i love u so much, there is two rule. 1. At least there must be one I, and one U. Capital or not is regardless. 2. Every I and U must be stick together. No sole i and sole u. This is , so shortest code with byte wins. • What is preventing me from just putting a comment or no-op at the end with #IU or something similar? – AdmBorkBork Jun 11 '19 at 12:36 • @AdmBorkBork Ah, I forgot that. Every I and U must be stick together. – LegenDUST Jun 11 '19 at 12:37 • That's better, but it still allows, for example, BrainFuck to just type out the necessary > and < and put IU at the end as a comment/no-op. If that is your intention, that's fine, just wanting to point it out. – AdmBorkBork Jun 11 '19 at 12:42 • IMO this is too boring to be worth posting. The string isn't compressible, so it's just a case of taking the string "ui love ", rotating by one character, and printing (finding a workaround in the languages where one would normally print with print). – Peter Taylor Jun 12 '19 at 10:54 • @PeterTaylor Maybe I could make string more complicated? – LegenDUST Jun 12 '19 at 11:11 # Trace My Triangles Triangular is a 2D programming language that reads its code in the shape of the smallest triangle that the code will fit into, ignoring all whitespace. Its IP starts at the very top point of the triangle, and traverses the code starting in a Southeast direction. The IP's direction can be changed with the following directional switches (Note that "." is a no-op):  ^  / < . > , \ v  ## Challenge You will be given a single input string p which represents a valid Triangular program. Your task is to write a program or function, which will print or return the actual execution order of p. Instructions in p which are never reached by the IP can be ignored. You may assume the following: • p will contain only characters which are necessary for a Triangular program to be valid; no need to account for whitespace. • p will only switch directions via the directional switches listed above. The o,e,c and z instructions will not be used. ## Examples Input: Output: --------------------------------------------------- F\(?)1/%-< F(1<-%/?$$

,%./                      ,%/

\@~/;<                    \~<;/@

123456                    136


This is code-golf, so the shortest byte count wins.

# Sandbox

• Is this a good idea for a question/not a dupe?
• Is the requirement clear enough?
• What other test cases should I be adding, if any?
• Should jump-related instructions - (, ) and ] - also be among the things that can be disregarded?
• Should any other sorts of instructions be disregarded?
• Would any other assumptions make this more manageable/fun?

I'm not able to find a challenge which will return as an integer how many days until Christmas based on an input like DDDD-MM-YY. So...

# How many days until Christmas?

Work out the number of full days until Christmas based on today's date based on the Western Christianity date source.

Write a program, method, function, routine or sub-routine that accepts an input of the current date according the the Gregorian calendar source. The date may be in any format as long as you use the full year (so 2019-09-11 rather than 19-09-11). Other than requiring the full year, the date format is up to you (DD/MM/YYYY or MM/DD/YYYY or even formally written dates like Wednesday 12th June 2019). Please state what date format you are using in your answer.

An integer is displayed according to your standard output.

Example:

input -> output:

12/06/2019 -> 196 days until Christmas*
12/25/2019 -> 0 days until Christmas**

* DD/MM/YYYY format
** MM/DD/YYYY format

• Subset of this? – Adám Jun 12 '19 at 13:18
• @Adám Or really similar to Christmas Eve Eve, just accumulate the days rather than printing "Eve." – AdmBorkBork Jun 12 '19 at 13:22
• Yes, thanks. Those challenges are specifically for technologies that have DateTime functions built in, my suggested challenge would be more suitable for technologies that don't know what date it is or what timezone they are in, like the Sinclair and Commodore 8-bit machines, for instance. Because you would have to specify the date and the rest would have to be worked out with some programmings. – Shaun Bebbers Jun 12 '19 at 14:15

## Is this set doubly orderable?

For input you are given a set of four or five sets of strings. Each string is at least two characters long; those first two characters are always digits but the remaining characters can also be letters.

The set of sets is doubly orderable if an ordered list can be constructed using one element from each member of the set such that:

• The first characters of each element of the list are in nondescending order
• The second characters of each element of the list are separately in nondescending order
• If any elements of the list have more then two characters, then those elements are all wholly equal with each other and appear at the beginning of the list (while still satisfying the other conditions).

Although there is an ordering on the list itself, the original sets can be sampled in any order necessary to achieve a valid list.

Example valid lists:

13  24  25  36
13e 13e 13  13
33s 37  37  37


Example invalid lists:

13  33  15  35  (first character not in order)
13  15  33  35  (second character not in order)
13e 24s 25  36  (different overlong strings)
33  37s 37s 37s (overlong strings are not first)


For output you should have:

• A consistent value indicating that the set is not doubly orderable
• A consistent value indicating that the set is can be doubly ordered using only 2-character strings
• A list of all overlong strings of which one is needed to make a valid list.

Full example:

1. 13 23 33 14 24 34 15 25 35 16 26 36 17 27 37
2. 33s 15e 16 17e
3. 34 25
4. 17e 37


In this example the 34 and 25 in set 3 force us to use either 33s or 15e from set 2 and therefore the 37 from set 4, with a number of options from set 1. Since all the valid lists begin with either 33s or 15e, these are the outputs.

• I find this spec quite confusing. (1) ISTM that the property "doubly ordered" should really be "doubly orderable". (2) The order of the elements in the list can be inferred to be arbitrary from the fact that the spec talks about a set of sets, but it would be much better to make this explicit. E.g. change the second paragraph to start "The set of sets is doubly orderable if a list can be constructed by taking one element from each member of the set and ordering them so that:". (3) On the third bullet, do the elements have to be equal or just the suffixes? – Peter Taylor Jun 12 '19 at 13:40
• @PeterTaylor (3) Yes, the elements have to be wholly equal in this case. – Neil Jun 12 '19 at 14:31

# Proving that a Russian cryptographic standard is too structured

• Nice challenge. I have some suggestions for usability for solvers. Please say what language your example code is in (C?), and an online runnable version -- the community standard is TIO which is maintained by a site mod (example in Python). A pseudocode version or explanation would also be appreciated. It would be useful to include a listing of the permutation as 256 numbers from 0 to 255 written in base 10. The references would be cleaner as inline hyperlinks. – xnor Jun 6 '19 at 21:39
• You should allow submissions to be programs or functions, which is default. Also, please change the scoring to bytes. I sympathize with wanting a fair comparison for 7-bit vs 8-bit languages, but past efforts have proved unpopular, and people now generally think of competitions as being within each language. You can leave the conversion to bits for your personal leaderboard. – xnor Jun 6 '19 at 21:46
• Also, please make the challenge as self-contained as possible, which means putting into the challenge body the parts of the linked papers that are important for solvers. Here, I think this is mainly how the function p works. In particular, what does it mean that the table k is an affine function, and how can it be implemented as such? Does s have any structure? – xnor Jun 6 '19 at 21:52
• Thanks a lot for your comments! I have updated the challenge and did my best to take them into account. Is it clearer now? – picarresursix Jun 6 '19 at 23:50
• Yes, thanks for the edits. Now that you've explained that the core of the code is discrete log, I have some questions on that which other solver might have too. I take it the char declaration is to limit the values to 8 bits and discard bits? If I think of the field of size 256 as GF_2[X] modulo a certain irreducible polynomial, does the update a=(a<<1)^(a>>7)*29 correspond to multiplying by a polynomial? Could the initialization be l=0, a=1 instead? Note that LaTeX is enabled here, in case it's easier to write formulas. It also could help to say that ^ is xor, not power. – xnor Jun 7 '19 at 0:21
• The answer to your questions are yes---mostly. The unsigned char are indeed used to discard some bits. We could alternatively replace a=(a<<1)^(a>>7)*29 with a=(a<<1)^(a>>7)*285 (where 256^29==285, in which case we wouldn't need the unsigned chars. This code snippet indeed corresponds to a multiplication by a polynomial. However, we cannot start at l=0,a=1. For some reason, the designers of $\pi$ used a variant of the logarithm such that $\log_2(1)=255$ instead of $\log_2(1)=0$. Both are "correct" in the sense that $\alpha^{255} = \alpha^{0} = 1$ but this variant is less common. – picarresursix Jun 7 '19 at 0:28
• I added these clarifications to the challenge. – picarresursix Jun 7 '19 at 0:45
• The output of your C code seems to not match the table. – xnor Jun 7 '19 at 1:02
• The table was wrong rather than the C code. Thanks for catching it! I fixed it as well as the corresponding TIO link. To further simplify the verification, I added a link to the wikipedia page of Kuznyechik which contains the table of the function p. – picarresursix Jun 7 '19 at 1:18
• – xnor Jun 7 '19 at 1:57

# Continue a progression code-golfmath

The $$\k\$$th generalized mean $$\M_k\$$ of a set of numbers is defined as $$M_k(a_1,\dots,a_n)=\root^k\of{\frac{a_1^k+\dots+a_n^k}n}.$$ $$\M_0\$$, the geometric mean, is defined through a limit $$\\lim_{k\to0} \root^k\of{\frac{a_1^k+\dots+a_n^k}{n}} = \root^n\of{a_1\cdot\dots\cdot a_n}\$$. $$\k\$$ does not have to be integer.

An arithmetic progression is (according to Wikipedia) a sequence of numbers such that the difference between consecutive terms is constant. A geometric progression is a sequence of numbers such that the ratio between consecutive terms is constant.

There is a simple way to generalize these (that also explains why on earth is geometric progression named geometric): for a progression of order $$\k\$$ for any 3 consecutive elements $$\a\$$,$$\b\$$,$$\c\$$ $$\M_k(a,c)=b\$$. This way, the arithmetic progression is of order 1 and the geometric progression is of order 0. The order does not have to be integer.

The task is, given 3 real positive numbers $$\a,b,c\$$, to find the next term in the progression formed by them.

## Notes

• If multiple valid outputs exist, you can output any of them.
• It is guaranteed that a valid output exists.
• An output is valid if $$\|o_{correct}-o_{program}| \le10^{-5} \cdot \max(o_{correct}, 1)\$$.

# Sandbox stuff

• I still have to prepare some test cases, especially for non-integer orders.
• Has this been asked before?
• Do multiple correct outputs ever exist? I feel like very often there are infinitely many.
• Does Mathematica have a built-in?
• Should I add a time limit? I feel like brute-forcing all floating point numbers and checking if they are valid outputs might be shorter than actually calculating.
• Should I restrict the order to be integer, or even just 0 or 1 (leaving only arithmetic and geometric progressions)?
• Is there a simple and beautiful formula for the next term that I was unable to find and that all answers will have to copy from each other? I could neither get Mathematica nor myself to solve any related equations.
• Is the grammar correct enough?
• I think The task is, given 3 real positive numbers ... is a bit problematic, as receiving them sounds like a daunting task. – Jonathan Frech Jun 13 '19 at 15:21
• @Jonathan Surely reading three numbers or taking them as function arguments or whatever is your language's alternative is the least thing you have to do here? – my pronoun is monicareinstate Jun 13 '19 at 15:25
• I think proving that submissions will always meet your validity criterion will be rather daunting. This will probably further encourage solutions that just try every single floating point number? I'd recommend saying that floating point issues won't be counted against the submission, but you still have a bit of a problem. If you do add a time limit I'd recommend saying that it only need be tested on the cases you provide (and maybe remind users that hardcoding is a loophole ;) ) – FryAmTheEggman Jun 13 '19 at 17:30
• The time limit only on the test cases thing makes sense to me. What does "not counting floating point issues mean"? I think most solutions will have to use binary or ternary search, and that needs a, uh, stopping precision or a iteration count to be close enough. I think we can remove the need to verify it on all numbers by preparing a lot of test cases! – my pronoun is monicareinstate Jun 14 '19 at 3:58
• Not every solution will use that, and even if they do they may still run into a problem where they can't get a solution well enough based on their native floating point type and have to do a bunch of extra work. I think it works well as a catch-all that prevents golfers from having to struggle with weird edge cases. But generally I think you are right that just having enough test cases will be good enough (also I didn't get notified by your comment because someone else has commented already, you'd need to use @). – FryAmTheEggman Jun 14 '19 at 18:08
• @FryAmTheEggman double-precision floating points have around 14 digits of precision, and 1e-8 is a perfectly common epsilon for such tasks (and I use 1e-5). And if I assume floating point numbers are arbitrary precision, that implicitly disallows binary/ternary search, as it will never produce the exact answer. And since the only two solutions I know are Mathematica NSolve and alternatives and searching for the order and then for the next number, this disallows all remotely interesting solutions known to me. – my pronoun is monicareinstate Jun 15 '19 at 2:46
• Assuming the languages that people use to answer your challenge will use a reasonable convention is not a particularly good one! I didn't meant arbitrary precision but arbitrarily larger precision based on what you have specified. It is probably fine the way you have it, I just think it is better to think about nonstandard languages when you can. If you put no time limit, some solutions may try to iterate over all floating point numbers of a particular precision, for example. Sorry if this has gotten out of hand, maybe I'm not doing a good job explaining what I mean? – FryAmTheEggman Jun 15 '19 at 3:16
• So in short, given inputs $a,b,c$ find a $k$ such that $a^k + c^k = 2b^k$ and then find and output a $d$ such that $d^k = 2c^k - b^k$? There is a significant problem in that $k=0$ is always a solution to the first equation, so I think that the geometric mean would have to be tested first as a special case. – Peter Taylor Jun 18 '19 at 11:03
• @PeterTaylor I think so. I feel like there actually is a simple and beautiful solution that everyone will have to copy from each other here. – my pronoun is monicareinstate Jun 18 '19 at 11:08

# Nearest match with limited values

When writing my solution for this challenge, I found that I needed to generate a target value using nothing but multiplication and increments/decrements, using a restricted set of values to use in the multiplication. Given that my choice of values was restricted, I had to brute-force what the optimum solution was. gObviously, this seems like a programming challenge!

The challenge is this: Given a target value t and set of allowed multiplier/multiplicand values, find the solution t=x×y±c (x and y are from the set of allowed values), that has the smallest value of c. If c is zero, indicate the solution as an exact match.

As this is a challenge, smallest code size wins. The standard rules apply.

Example program (ungolfed): Try it online!

I don't think that I saw this particular challenge before, but I may have missed some. This is my first challenge, so please let me know how I can make it better!

• Thanks for using the sandbox! This is mostly fine, except for two main things: "indicate that the solution as an exact match" is not really fleshed out enough, and that you don't have any test cases in the body. There are some other minor things, like specifying t and the allowable values to be integers (can they be negative?), and if returning all of the optimal x,y pairs is acceptable. As a challenge, I'm a bit unsure if this is particularly interesting due to its simplicity, but I don't think it is so simple that it is bad or anything. – FryAmTheEggman Jun 16 '19 at 17:56

# Political Simulator king-of-the-hillgrid

It's election time, and your job is to beat your competitor in a head-on rivalry! You are both trying to win over a city of 256 people in a 16x16 grid. Right now, the city hasn't been divided into voting regions yet, but that's where your gerrymandering skills come in! You can also campaign in arbitrary areas of the city to gain support.

# General mechanics

The game starts out with each bot having $100 and all 256 voters being neutral (value 0). In the below notation, <x> refers to the grid space at x (so, 0 <= x < 16), and [x] refers to the block at x (so, 0 <= x < 4). The city starts out divided into 16 4x4 voting blocks. Each turn, both players get to perform one move: • C <x0> <y0> <x1> <y1> - campaign in the area bound by (x0, y0) and (x1, y1), inclusive, which will make all neutral voters with at least as many of your voters compared to your opponent's voters in their Moore neighborhood (diagonals included) vote for you. This only counts neighbors in your campaigning area; that is, voters at the corners of your campaign area only have three neighbors. Additionally, opponent's voters with at least 4 of your voters in their neighborhood will switch to your side (note that this means that you cannot swing votes in the corners of your campaign area). This costs$1 per square, and if you do not have enough money, your turn will be skipped. Additionally, you must have 0 <= x0 <= x1 < 16 and 0 <= y0 <= y1 < 16; otherwise, your turn will be skipped.
• M [x0] [y0] [x1] [y1] - Attempt to merge the voting region containing the block (x0, y0) with the voting region containing the block (x1, y1). Note that here, 0 <= x0, x1 < 4 and 0 <= y0, y1 < 4. If the voting regions containing these two blocks touch, then the merge will succeed. This costs $(max(# blocks in first region, # blocks in second region) - 1) * 25; that is, if you merge a voting region containing 3 4x4 blocks with a voting region containing 2 4x4 blocks, it costs$50. This means that an initial merge of untouched regions is free. If you don't have enough money, or the regions don't touch, or your input is invalid, your turn will be skipped.
• U [x] [y] - Attempt to unmerge the voting region containing the block (x, y). If successful, it will take all blocks in the voting region containing your specified block and separate them all. This costs $(# of blocks in the region - 1) * 50. If you don't have enough money, or your input doesn't fit 0 <= x, y < 4, your turn will be skipped. • B <x> <y> - Bribe the person at (x, y) with the amount specified by their bribing cost (initially$5), which raises their bribing cost by $2. This makes them vote for you. If you don't have enough money, your turn will be skipped. At the end of every other turn (including the end of the first turn), you will gain$50.

# Win condition

Each region will have all of its votes summed up. Then, if at least 50% of voters are not neutral and the number of votes for the two parties is not exactly the same, whichever party has more votes wins that region; otherwise, the region is neutral. The game ends when all regions are non-neutral and one party has strictly more regions than the other party (basically, you can call an election at any time, so as soon as you can win, you call the election and win).

# I/O Format

I/O will be done via STDIN/STDOUT to allow (almost) any language to be used. On each turn, your bot will be presented with the following input:

Line 1: the number of regions, R
Line 2 to 5: a grid of the voting regions consisting of a 4x4 of capitalized hexadecimal digits. For example, a possible voting region configuration with 11 regions is:

0023
4867
88AB
CAAF


Line 6: N M, the amount of money you have, and the amount of money your opponent has.
Line 7 to 22: the 16x16 grid consisting of 0, 1, and 2, where 0 is a neutral voter, 1 is one of your voters, and 2 is an opponent voter.

For example, the starting configuration will be:

16
0123
4567
89AB
CDEF
100 100
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000


You will be given this input with a terminating newline, and you need to output one of the four commands indicated above (if you want to do nothing, then output anything invalid or output a newline, but if you don't output, your bot will be presumed frozen and you will lose).

Unless someone needs otherwise, bots taking more than 2 seconds on a turn are killed and lose.

# Rules

Your submission must work correctly in under 2 seconds per turn. Your program should block for input and will be run once and will be fed 22 lines of input per move and should give exactly one line of output per move.

Every bot will be run against every other bot. Each round, the simulation will be run twice with each bot getting the first move in one of the simulations. If both bots win exactly one simulation, the tiebreaker goes:

• the bot that wins by a wider margin of regions wins (that is, whichever bot had a higher difference between their regions and the opponent's regions)
• the bot that wins by a wider margin of popular vote wins
• the bot with more popular votes wins
• the bot that took fewer moves to win wins
• failing these, the round is declared a tie

The bots will be run until one of them wins three rounds. If ten rounds have passed and neither bot wins, it is declared a tie, giving each bot half a win.

The bots will be ranked by wins, with earlier submissions winning ties.

# Sandbox

• Is this game balanced and strategizable?
• I will probably leave this challenge open for two weeks before declaring a winner; submissions can still be made afterwards but may or may not be graded.
• Any clarifications or specifications needed?
• I'm not sure if giving $1 per voter vs giving a fixed allowance is better.$1 per voter leads to more run-away wins (quicker games are definitely better), but giving a fixed allowance gives the AI more turns to flesh out their strategy. The section under "rules" is confusing. I'm having trouble figuring out what a round, subround, and matches are. – Nathan Merrill Jun 16 '19 at 5:59
• @NathanMerrill Hm, that's fair enough. I'll clarify the scoring. – HyperNeutrino Jun 16 '19 at 13:34
• That's clearer. That said, I don't understand why you are grouping by rounds. Wouldn't it be simpler to have, say, 10 games, and then follow the tiebreaker rules to determine the winner. – Nathan Merrill Jun 16 '19 at 16:08
• Also, the moves aren't very clear, it took me several reads to understand them. You are reusing the word "region" to mean both a set of squares, as well as one of the specific 4x4 set of squares. Also, it isn't clear when the coordinates refer to square coordinates vs region coordinates, I'd have a different notation for those. – Nathan Merrill Jun 16 '19 at 16:13
• "This costs $max(# blocks in first region, # blocks in second region) * 25; that is, if you merge a voting region containing 3 4x4 blocks with a voting region containing 2 4x4 blocks, it costs$50." Is this right? Shouldn't the example cost $75? – Alion Jun 17 '19 at 14:30 • @Alion I forgot to subtract 1 from that lol. The original spec was their sum but I made it max, and it's supposed to be -1 still. – HyperNeutrino Jun 17 '19 at 15:49 • @NathanMerrill I've updated it; area refers to campaigning, block is the 4x4 overlaying grid, and region is an arbitrary shape of the 4x4 blocks. – HyperNeutrino Jun 17 '19 at 15:51 • "This means that an initial merge of untouched regions costs$25." How? max(1, 1) - 1 gives 0. – Peter Taylor Jun 18 '19 at 10:31
• @PeterTaylor Sorry, that was left over from an earlier revision of the computation. Will update. – HyperNeutrino Jun 18 '19 at 12:18
• Bribing seems ridiculously inefficient, both cost- and time-wise. I'm having a hard time imagining a situation where it would be the correct play, especially considering how much money each player makes every turn. Cutting the budget by about 50-80% would likely resolve the issue. If you've studied this problem more closely than I have and are aware of situations where it is indeed appropriate, however, feel free to ignore my suggestion. – Alion Jun 18 '19 at 19:47
• @Alion I have not analysed the balance of the moves and what strategies would be optimal, but yeah, I think it's a very nuanced move that would only ever be used if you need to hit a specific region and force converting someone can allow you to use a campaign to cover the area. But yeah, I'll probably leave it in there and I'll look into the cost and budget balancing. – HyperNeutrino Jun 18 '19 at 20:14
• @Alion, there's no point campaigning before bribing. You need to somehow jump-start the scenario. – Peter Taylor Jun 19 '19 at 11:57
• @PeterTaylor "Campaign[ing] [...] will make all neutral voters with at least as many of your voters compared to your opponent's voters [...] vote for you." In other words, 0 >= 0. – Alion Jun 19 '19 at 12:06
• 1) Does bribing make the person vote for you until opponent's bribe, regardless of campaigning? I only just realized this, so if this is the intended mechanic, I would recommend making it a bit more clear. 2) I know that you are planning on tuning the numbers, but I think I might've found a quick and easy forced win for player 1, or at least something very close to one, so that's a bit more incentive for that. I feel like the game is just too ridiculously fast paced for any strategy to show up at the present. I could be wrong, but everything I try points to that conclusion. – Alion Jun 19 '19 at 12:32
• @Alion No, it just sets their affiliation to you and the opposition can gain that vote by campaigning. About the pace, I will probably need to reduce the budget so player 1 can't just win half the game on the first move. – HyperNeutrino Jun 19 '19 at 12:39

## Conversion

Assume that there is a number a. In every conversion of that number, the number can either convert itself to its value plus the value of one of its digits, or convert itself to its value minus the value of one of its digits.

In this situation, find the minimum number of conversions one has to make in order to get to the number b. If b cannot be reached, output -1.

## Input

Input one line containing the integers a and b (where 1 <= a, and b <= 10^6).

## Output

Output a line containing one integer, which represents the minimum amount that one has to convert the number.

## Example input and output (s)

Input:  1 10
Output: 5


Why?

   1
-> 1+1=2
-> 2+2=4
-> 4+4=8
-> 8+8=16
-> 16-6=10
=> 10

• At first sight this looks like just another shortest path question, but reachability is actually quite subtle. Do you have a proof of decidability? – Peter Taylor Jun 22 '19 at 18:33

# Meta command-line flag parsing code-golf

### The challenge

Write a program or function which determines whether or not a chosen command-line flag has been passed into the compiler or interpreter, but without accessing command-line parameters directly.

### Details

• You must take in no input.
• You are free to choose the flag that is being detected, but it must:
• be a flag, meaning a boolean command-line parameter that does not take any arguments (e.g. -O3 in gcc)
• not print anything by virtue of being present (e.g. flags that print a version number or usage help are disallowed)
• The output must be 1 if the flag is present, and 0 otherwise.
• The program must successfully run without errors, whether or not the flag is present.
• You may not make use of the arguments passed to the compiler/interpreter, whether directly by value or by a property such as string length, array length.
• Separately from the chosen flag, other command line parameters can be used, so long as they remain the same when running the code with and without the flag in question.
• This is ; shortest answer in bytes wins!

## Sandbox Questions

• Are there any other edge cases or loopholes that should be accounted for here?
• Is this a , despite the challenge not being related to input?

Feedback welcome!

• I think this may have quite a few problems with determining what counts as a valid flag, what counts as accessing them, and what counts as an error. For example, Pyth has a flag -d which turns on debug printing. So any program with constant output would work. But that doesn't seem like what you have in mind, would it be acceptable? – FryAmTheEggman Jun 21 '19 at 19:57
• @FryAmTheEggman Indeed, that's somewhat problematic. Maybe restricting output to either 1 or 0 would stop such trivial solutions from passing, though at the cost of punishing some other languages. I don't want to completely bar short-but-clever solutions, though, as I find that they can often be surprisingly creative; the example you posted is just something that would end up being used in too many solutions. – negative seven Jun 21 '19 at 20:11
• That may help, but you are right that it will restrict solutions a lot. I think this is a challenge that is worth running past quite a few people so you can get an idea of which flags are actually worth (and possible) to rule out. – FryAmTheEggman Jun 21 '19 at 20:23
• Thinking of Japt here which takes its flags via an HTML input: if I'm understanding correctly, I wouldn't be allowed to simply read the value of that input, right? What about accessing Japt's internal variable for storing flags, would that be allowed? Also, should our solutions run no matter which flag is used or need we only support our chosen flag and no flag? Again thinking of Japt which has a flag that negates it's output; obviously that's going to be problematic! – Shaggy Jun 22 '19 at 22:14
• @Shaggy Both the input and internal variable would classify as "accessing the list of arguments", which is disallowed. Only two sets of command line parameters need to be supported: [some set of starting parameters not including the chosen flag, if any] and [the same set of starting parameters] + [the chosen flag]. I'll try to clarify both of these things. – negative seven Jun 23 '19 at 5:09

## GPA calculator

A GPA is sort of weighted average based on the grades obtained in certain courses. There are a number of different systems, but for this challenge we'll use the following grades and their numeric values:

A: 4
B: 3
C: 2
D: 1
F: 0
P: —


The grade is P is a special case. For some courses, students can sign up to take a course as Pass/Fail. In the case of a Pass (P), the course has no effect on their GPA whatsoever, but in the case of a Fail (F), the course does affect the GPA.

All courses are weighted by the number of hours/credits they are taken for. So give the following transcript:

Course            Hours   Grade
------            -----   -----
Next Gen Perl       6       A
Starting with Java  3       B


We would calculate the total points as 35 (6*4 + 1*2 + 3*3), and then divide it by the number of hours, or 10 (6+1+3) for a final GPA of 3.5. If Starting with Java had been given an F, the total points would be 26 with 10 hours, for a GPA of 2.6. However, if it had been a P, the total points would still be 26, but with only 7 hours, the GPA would be 3.71428571429…

## Input

An arbitrarily long list/array/sequence/etc of transcript entries. The entries are simply a two item list/array/sequence/etc with one item being an integer value (doesn't have to be an actual Int value, floats are fine) of hours, and the other being the string ('A','B'...). The above example would have been:

[
[6, 'A'],
[1, 'C'],
[3, 'B']
]


You may assume that the list will have at least one computable grade (so no empty transcripts, nor transcripts consisting only of P). If your language does not have strings, then you may use numbers for A/B/C/D/F/P, but their values must be similarly spaced (e.g. 10,11,12,13,14,25)

## Output

A number representing the GPA (float or other non-Int value)

## Scoring and Restrictions

Codegolf, so shortest code in bytes wins. Standard rules apply.

## Sandbox questions

I thought about allowing for either +/- grades (A+, A, A-, B+...) which would definitely prevent using ASCII values as easily, but then that led me to the thought of having a second input which is a list of possible grades with their equivalent value, but I think that would start over complicating it and way over benefit languages with built-in hashing. Thoughts?

• Dupe – FryAmTheEggman Jun 21 '19 at 20:01
• @FryAmTheEggman not a dupe. This one adds the P which makes it a good bit more complciated. – user0721090601 Jun 21 '19 at 20:03
• I disagree, solutions can just filter out all the grades with P and then exactly reuse the result from the question I linked. Unless I've missed something that definitely fits in the criteria for being a duplicate. – FryAmTheEggman Jun 21 '19 at 20:06
• @FryAmTheEggman Between filtering, vastly different input/output (all of which could/would significantly modify entries — the input/output in particular was a strong criticism of the one you linked to), I think it's sufficiently different and golfed answers wouldn't be trivially different. But in any case, I asked about feeding in +/- or arbitrary grades which absolutely would be a totally different question. Perhaps instead of being dismissive, you could be constructive. – user0721090601 Jun 21 '19 at 20:24
• It is possible that I'm being too harsh, but I don't think I am. The only real problem with the other question compared to this one is the rounding, which could basically just be dropped from the answers. While I agree that this isn't identical, I don't think it has enough reason to exist as even with the +/- grades it's still just looking up values then applying a weighted average. It is certainly possible that I am in the minority, but I think my skepticism should encourage you to find other people's opinions before posting. – FryAmTheEggman Jun 21 '19 at 21:03
• I agree with @FryAmTheEggman; the core of both challenges is identical. The only real difference here is having to filter the Ps which is a trivial modification for most languages. Having said that, though, I wouldn't swing my hammer at this until a few solutions had been posted, in the hope that I would be proven wrong. – Shaggy Jun 22 '19 at 22:26

Tag:

## Arrays

I originally wrote it in Chinese and am still working on translating it. Sorry for the inconvenience.

Given an array containing n integers A1,A2,…,An, where all of their initial values are 0. Please implement the four operations to the array described below:

## Operations

Given the positive integer x and y, let every number in the range Ax~Ay (including Ax and Ay) be added by the given positive integer c;
Given the positive integer x and y, let every number in the range Ax~Ay be (similarly to the previous spec; the rest of the spec also conforms that rule) multiplied by a given positive integer c;
Given the positive integer x and y, let every number in the range Ax~Ay be changed to a given positive integer c;
Given the positive integer x and y, with regard to a given positive integer p, evaluate the value of the following expression :[pow(Ax, p) + pow(A(x + 1), p) + … + pow(Ay, p)]7


## Input

In the first line of the test case, there are two positive integers n(where 1<=n), which represents the length of the array.

Then, input operations sequentially, where each operation occupies one line, and the input will be 4 positive integers as in: type x y num, where type is either 1, 2, 3, or 4; these identifiers correspond to the corresponding operation as described above. The meaning of x and y corresponf to the description (where 1<=x<=y<=n). When type is not 4, num will be the positive integer given c(where 1<=c<=10000); when type is 4, num will be the given positive integer p(where 1<=p<=3)。

## Output

For each test case, for every 4 operation for the array, output the value of the corresponding expression.

## Example input

5
3 3 5 7
1 2 4 4
4 1 5 2
2 2 5 8
4 3 5 3


## Example output

307
7489

• Is it supposed to have restricted-complexity? Or pure golf? – jimmy23013 Jun 27 '19 at 11:37
• I will add the category later after I translate the problem. – user85052 Jun 27 '19 at 11:46
• In that case it's restricted-time. But you have to specify exactly how it is tested. 8 seconds doesn't mean much without the test cases and the the exact computer it will run on. restricted-complexity is much simpler. And just to confirm, you wrote this question, and it's not a homework problem from elsewhere, is it? – jimmy23013 Jun 27 '19 at 11:56
• Yes, I wrote the question; I will accept your suggestion. – user85052 Jun 27 '19 at 11:58
• Because, I think it is designed to be O(n+qlogn) in some algorithm competition. If more than that, any straightforward algorithm will probably work, and it's better to just removed the restriction. (Also note that on CG.se, in a challenge that there is a known best algorithm, coming up with the algorithm is generally not supposed to be the main challenge. If you go for O(n+qlogn), they will simply ask for a reference algorithm.) – jimmy23013 Jun 27 '19 at 12:10
• Don't use multiple test cases. Make the list format flexible and q implicit. I'm not sure what's the best way to input multiple operations, but at least you could make operation types consistent and distinct value. If there is no time or complexity limit you don't need mod 10007. Even if there is a limit, it is probably better to make this an input. – jimmy23013 Jun 27 '19 at 12:18
• I think if you wrote this you probably know that O(n+qlogn) and O(n^3) (or simply without restriction) makes a lot of differences. The code would be much longer for O(n+qlogn). And for reference, this question asking for suffix tree or alternatives had the first and only non-deleted answer about 2 years later. Not that you can't post it in either case, but... just make sure you know what you are doing. – jimmy23013 Jun 27 '19 at 12:29
• I mean at least you could make operation types any consistent and distinct values, instead of 1, 2, 3, 4. – jimmy23013 Jun 27 '19 at 12:31

# Answer chain: decreasing character scores

Assign a non-negative integer value to each letter in the alphabet, and write a function or program which takes as input a character string and outputs the sum of of the values of the letters in the string. Characters outside of [a-z] and [A-Z] have value 0.

Now run your code, taking as input the code of each of the previous answers in the order they were posted (including your own). The resulting sequence of scores should be strictly decreasing.

For example, if you are 4th to answer and your code defines a function $$\f\$$, then the output should verify $$\f(c_1)>f(c_2)>f(c_3)>f(c_4)\$$ where $$\c_1\$$ is the code of the 1st answer, $$\c_2\$$ is the code of the 2nd answer, ..., $$\c_4\$$ is the code of your answer.

When there will have been one week with no new answer, the 2nd-to-last answer will be declared the winner.

### Clarifications:

• The values you assign may be the same as or different from those used by previous answers.
• The value 0 is allowed.
• Different letters may be assigned the same value.
• Upper and lower case versions of the same letter may have different values.
• Letters with diacritics, such as é or Ä, have value 0.
• Your code need not handle letters which have not occurred in any of the previous answers (so if no answer so far has used the letter W, it's OK if your code fails on strings with a W).
• Using characters like this seems to have some problems. Do answers get to pick encodings? Or is it really more like $f(c_{1},e_{1})$ where $e_{i}$ is the encoding used by the ith answer? I think this may work better if you say it should work on bytes, then answerers can choose to interpret those bytes as characters in whatever encoding they want. – FryAmTheEggman Jun 24 '19 at 3:45
• @FryAmTheEggman I have been thinking about this as well. I want it to be easy to set up on TIO, which means that solvers should be able to just copy-paste the code of previous answers. Forcing solvers to take into account the esoteric codepoints of golfing languages would be a hassle. I'd be more inclined to let answerers pick the encoding, but I suppose that might create potential loopholes. – Robin Ryder Jun 24 '19 at 14:34
• Wouldn't asking for a hexdump of the code to be in each answer ensure that the solutions are fairly accessible? TIO also has problems with displaying particular characters (null bytes especially) and other things like that each text box has one fixed encoding. – FryAmTheEggman Jun 24 '19 at 14:39
• @FryAmTheEggman How about restricting to letters (without diacritics)? Anything not in [a-z] or [A-Z] must have value 0. I think this circumvents the problem. Or maybe extend to letters+digits, or even all ASCII characters. – Robin Ryder Jun 24 '19 at 16:35
• I don't think that works with your setup at all because a submission with no characters in whatever range you pick must always score exactly zero so it necessarily ends the chain. – FryAmTheEggman Jun 24 '19 at 16:49
• @FryAmTheEggman Yes, and then whoever submitted that is guaranteed to lose, since the second-to-last answer wins. – Robin Ryder Jun 24 '19 at 20:41
• Ah, I missed that, sorry. It still seems to have trouble with languages that could write all of their code using bytes outside the range you select and then throw in a small number of other characters, but I don't know if that is "broken" enough to make it unfun. – FryAmTheEggman Jun 24 '19 at 22:55
• @FryAmTheEggman Potentially, an answerer could use only non-letters, add a single a, and then all following answers would need to assign a large value to a and avoid that letter in their own code. That seems OK to me, but I am a fan of lipograms... Anyway, I have updated the challenge following this helpful discussion; let's see if there are further comments. Thanks for your feedback! – Robin Ryder Jun 25 '19 at 22:05
• Can a letter be assigned the value 0? That would be a non-negative integer – Nick Kennedy Jun 27 '19 at 14:51
• @NickKennedy Yes, 0 is allowed. – Robin Ryder Jun 27 '19 at 15:02

# Enable 2-char Jsfuck

Provide a shortest code that makes JavaScript able to do everything JavaScript is supposed to do, i.e. able to access(so no deleting [].prototype.toString unless you have a backup, even if you can simulate one [].prototype.toString) and exec anything, with only [ and ]. You can choose your environment(FF/node/etc). Answering in 6-char JsFuck or something similar is welcomed.

E.g. If you run

Array.prototype[''] = 'a';
Array.prototype['a'] = 'b';
Array.prototype['b'] = function() { console.log(this[0]); };


then [][[]] = [][''] = 'a', and [][[][[]]] = []['a'] = 'b', so [[][[]]][[][[][[]]]] = ['a']['b'] = function(){console.log('a')}.

Of course, this is an invalid answer, because it can't do prompt(web browser) or fs(node) or anything similar, or even calling the console.log.

• This is not clear as is. Are we making a transpiler from JS to JSFuck with the winning criterion code-golf? Do we need to support all JS input, or just some subset? – lirtosiast Jun 25 '19 at 17:13
• So a solution like translating "[[]"→( "[]["→) "[]]"→+ "][["→[ "][]"→] "]]["→! is valid? – Adám Jun 25 '19 at 18:18
• @lirtosiast I said "makes JS able to do everything in2c", not "make a language that do everything" – l4m2 Jun 26 '19 at 9:28
• @Adám I don't think it's possible. +[] turns into []]][[][] which is not even valid JS code – l4m2 Jun 26 '19 at 9:29
• @l4m2 Please include your not-golfed reference implementation so we can understand what you mean. – Adám Jun 26 '19 at 9:34
• @l4m2 If I understand this right, you're saying that we should write code that modifies the JavaScript environment such that all JavaScript code can be converted into JavaScript code that only uses characters [ and ]. Basically, add something to Array.prototype that makes the []` characters JavaScript-complete. – wizzwizz4 Jul 24 '19 at 13:28
• @wizzwizz4 right – l4m2 Aug 8 '19 at 15:11

## Tips for golfing in H

As for H as described here, what general tips do you have for golfing in H? I'm looking for ideas which can be applied to code-golf problems. Tips have to be specific to H (e.g. "remove comments" is an answer).

Tips in Standard H are also on-topic, although its spec is in a bad condition. You can use the H description provided in the first link to solve anything you don't understand about.

Please post one tip per answer. Also, please specify which H implementation you are using if your code runs only under a specific H implementation, as different H implementations can have different behavior.

• Why do you want to ask this when H doesn't even exist? – Adám Jun 28 '19 at 12:40
• What's the rush? Also, H as linked, isn't a programming language, and it has a very strict definition, so there's no much room for golfing. The only thing I can think of is to omit quotes in the rare instances where you want a string that looks like one of the 1999 integers in the range -999–999. – Adám Jun 28 '19 at 12:57
• That would be a duplicate. – Adám Jun 28 '19 at 13:10
• Tips for golfing in Turing Machine but Way Worse also only has 1 tip. – user85052 Jun 28 '19 at 13:14
• I can also think of a lot of those examples, as in: codegolf.stackexchange.com/questions/19423/… codegolf.stackexchange.com/questions/101557/… codegolf.stackexchange.com/questions/96682/… – user85052 Jun 28 '19 at 13:42
• It does not matter whether it is a programming language or not; this question only cares whether H can be golfed or not. – user85052 Jun 28 '19 at 13:47