# What is the Sandbox?

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

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

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

## 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]

• How are tags added to questions? – guest271314 Jan 9 '19 at 7:51
• @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] – James Aug 29 '19 at 15:19
• Why no featured anymore? Can't we have it auto-added or something? – S.S. Anne Sep 26 '19 at 15:57
• @JL2210 We now have a permanent info box that links to the Sandbox, so the featured tag isn't necessary – caird coinheringaahing Sep 29 '19 at 13:43

# Fun with Lasers and Prisms (WIP)

Given a rectangular grid of objects, one or more laser pointers, and a target, determine if any laser beam will hit the target.

# Objects

ASCII will be used for illustration purposes

• Laser Pointer: ^, V, <, > - a beam will shoot up, down, left, right, respectively, starting from this cell.
• Target: O - return true if a beam reaches this cell
• Mirror: /, \ - reflects a beam 90 degrees
• Prism: # - the laser will split into three beams, one for each direction
• One-way block: A, U, (, ) - a beam will pass up, down, left, right, respectively, but not other directions
• Corridor block: =, " - a beam will only pass horizontally or vertically, respectively
• Gate block: I, H - a beam will pass through horizontally if another beam touches it vertically, or vice-versa, respectively

# Rules

• Use any convenient representation
• I think it is likely that your gate blocks prevent this from being a dupe of other similar challenges, though I haven't thoroughly checked yet. – FryAmTheEggman Jan 18 at 3:19

# How low can you go?

Time to play so ascii-art limbo!

Here's the bar:

|--|
|  |
|  |


Can you fit under it?

## Goal

Write a program or function that takes an ascii string representing a some shape, and a positive integer representing a bar height.

Output the shape from the input after it has attempted to do the limbo.

## Details

In limbo you lean back to make yourself as small as possible to fit under the bar, and that is just what the input shapes will try and do.

If the input shape contains any repeating patterns in its lines, then you can remove all but the last of the repetitions that are in the pattern. In additions the pattern must start at the top line, and once the repeating pattern is broken no more sections can be removed.

If there is a repeating pattern that contains another repeating pattern, only the innermost pattern is stripped.

For example this is how the following inputs would look after "Leaning back":

1. XXX              2. xxx            3. xxx           4. xxx
YYY                 xxx       xxx     xxx              xxx      xxx
XXX   -->   XXX     yyy  -->  yyy     xxx  -->         yyy      yyy
YYY         YYY     zzz       zzz     xxx              yyy      yyy
zzz         zzz     aaa       aaa     xxx      xxx     xxx  --> xxx
xxx      xxx
yyy      yyy
yyy      yyy


Note how in example number 4 there was a repetition ox xxx insinde of another repetition of xxx, xxx, yyy, yyy. In this case only the inner repeating lines got reduced.

The bars will be drawn as shown below for the given heights:

1 -> |--|    2 -> |--|   3 -> |--|  etc...
|  |        |  |
|  |


If the given input shape in its reduced form does not fit underneath the bar then the bar will be drawn on the ground like this |__|

## Exmaples

Inputs:

a. height: 3      b.  height: 2     c.  height: 1
shape: xxx         shape: xxx        shape: (emptystring)
xxx                xxx
xxx                xxx
yyy                yyy



Outputs:

a. |--|           b. |  | xxx       c. |--|
|  | xxx          |__| yyy
|  | yyy


## Notes

1. You can assume only valid inputs will be given, handle invalid input however you want
2. The input shape will be drawn 1 space after the bar, and the bottom of the input shape will always line up with the bottom of the bar.
3. Extra whitespace after is fine as long as all the lines are properly aligned.
4. If there is whitespace in the given input then that should be included in the output
5. The shape will not necessarily always line up in a perfect rectangle as I drew it.

This is for code-golf so the answer using the fewest bytes wins.

Please let me know what you think / if anything is unclear and needs to be improved. Hope you guys like it!

EDIT: Would whoever down voted please explain whats wrong with it?

• I'm not the voter, but I'd bet they voted because what you have right now is very difficult to understand. I had to read this three times to figure out what you wanted. It may be worth revisiting the concept of "leaning over" as it is deeply unintuitive to me at the moment. On top of that, this requires a lot of "boring" golfing for the required output format when true/false seems to be basically the same. I hope this is helpful! – FryAmTheEggman Jan 20 at 20:24
• @FryAmTheEggman Hmm, I thought I'd explained it fairly clearly - its just removing any lines that form a repetitive pattern, but I will try to update it. The output is slightly more than just T/F because of wanting to see the "limbo'ed" input shape with the shaved lines, and having to draw the bar different if it fails... though maybe that is what you meant by boring golf? – Quinn Jan 20 at 20:30
• @FryAmTheEggman I tried updating the explanation, though I'm not sure if it is any clearer, please let me know if it makes more sense now – Quinn Jan 20 at 20:33
• Explaining things is often harder than one would guess. Here I think a big problem is that your definition of bending is not what I would expect, so it makes the whole idea harder to grasp - particularly the rules about which repetitions happen first. Since I don't get the why I struggle to get the what. Maybe try explaining this to someone verbally to see if you can get rapid and direct feedback. What you have now is better, but I still think I'd have a hard time following on a first read. – FryAmTheEggman Jan 20 at 20:35

# Factorise a floating point number

Given a target floating point number, $$\T\$$ and a set of $$\N\$$ floating point numbers $$\\{x_{1},..,x_{N}\}\$$ and a permissible error $$\tol\$$ , find a set of integer coefficients $$\A\$$, $$\\{m_{1},..,m_{N}\}\$$ such that: $$A\prod\limits_{i=1}^{N}x_{i}^{m_{i}} = T\pm{}tol$$

## Input

Input will be a target number, a set of real numbers and a tolerance as a decimal or percentage (note which) in any order or format required by your language.

## Output

Output should be $$\A\$$, $$\\{m\}\$$ and the corresponding error as a percentage. If multiple combinations are valid any or all sets of $$\A\$$ and $$\\{m\}\$$ are within tolerance.

## 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.

## Examples

$$\3*(3.2^4*7.1^2)=15857.614848\$$

15857.6 [3.2, 7.1] 0.05 => 3, [4, 2]


$$\2*(e^2*\pi{}^2)=145.854121188\$$

145.85 [2.7182, 3.1415] 0.1 => 2, [2, 2]


$$\3*(\pi^0*0.1^1)\$$

0.3 [3.14159, 0.1] 0.05 => 3, [0, 1]


## Auto Tic Tac Toe

Okay, so after thinking about the comment I think I thought of a way to make it more interesting.

### Challenge

Given no input, write a program or function which outputs an entire game of Tic-Tac-Toe where X always wins, or the game ends in a tie.

### Requirements

• The player who takes the first turn should be random
• O must make moves at random
• X must make smart moves such that it always wins the game, or the game ends in a tie

### Example

Here's what I would expect a game to look like:

X--
---
---

XO-
---
---

XO-
-X-
---

XOO
-X-
---

XOO
-X-
--X


### Notes:

• X does not need to win in the fewest moves, it is enough to just make it always block O from winning
• You can output the game in whatever form you like, as long as it is easily conveys every turn of the game. For example you could output a string like above, or a list of lists of ints like below, where 0 is an empty space and 1, 2 are X, O respectively:
[
[1,0,0, 0,0,0, 0,0,0],
[1,2,0, 0,0,0, 0,0,0],
[1,2,0, 0,1,0, 0,0,0],
[1,2,2, 0,1,0, 0,0,0],
[1,2,2, 0,1,0, 0,0,1]
]


This is code golf, answer in the fewest bytes wins. Standard rules apply.

Is this a better challenge? I'd love to know what people think

• I suspect this hasn't been asked because the huge majority of the work is spent on IO and not on an interesting problem. If you want to ask a tic-tac-toe challenge, you might be better served asking something like "can the next move win" which might still be a lot of parsing, but prevents excessive output at least. That said, you did do a good job of alleviating these problems in your notes, so you may be fine - most of what I've written here is my opinion, not precise advice. – FryAmTheEggman Jan 26 at 19:31
• @FryAmTheEggman Made a pretty big edit, do you think this would be less boring? – Quinn Feb 1 at 1:15
• I think the problem I have with this version is that it is probably more work to make a tic-tac-toe AI than it is to encode all the possible games and just pick one at random to output. It is possible that that isn't true, I haven't tried yet, but it still feels a bit tedious. But this might be the right direction - perhaps instead just ask for one random valid final tic-tac-toe board? Then it will likely be an encoding problem, but perhaps one with interesting strategies. Again, all opinion here, the challenge is written well, etc. – FryAmTheEggman Feb 1 at 5:13
• Do you mean "uniformly distributed" when you write "random"? – Jonathan Frech Feb 4 at 9:54
• Is the challenge in its current form not a kolmogorov-complexity challenge with choice? – Jonathan Frech 18 hours ago
• @FryAmTheEggman I don't think making the AI is actually that hard for tic-tac-toe, though if im underestimating it, i could make a change that X always go first, which I think would make the ai pretty trivial – Quinn 5 hours ago
• @JonathanFrech You tell me i have no clue, is that meaning the amount of code to output all possible tictactoe outcomes? – Quinn 5 hours ago
• I am just saying that if you take no input and require a (semi-)static output, a part of the challenge is to find out which tic-tac-toe game requires the least bytes to represent and the rest is a kolmogorov-complexity task, which in my opinion is s slightly over-used challenge format. – Jonathan Frech 4 hours ago
• kolmogorov-complexity challenges are code golf challenges with no input and a static output. – Jonathan Frech 4 hours ago

# Periodic table

The periodic table is a large tablecitation needed where we can find the chemical elements written out with their chemical symbols. For example, Helium shows up as He and Carbon shows up as C. You can read Wikipedia's article on the periodic table, if you want.

You have to write a function/program/procedure/... that, given a chemical element's name, returns its chemical symbol. For the purposes of this challenge, we will use the 118 elements listed below:

['Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron', 'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine', 'Neon', 'Sodium', 'Magnesium', 'Aluminium', 'Silicon', 'Phosphorus', 'Sulfur', 'Chlorine', 'Argon', 'Potassium', 'Calcium', 'Scandium', 'Titanium', 'Vanadium', 'Chromium', 'Manganese', 'Iron', 'Cobalt', 'Nickel', 'Copper', 'Zinc', 'Gallium', 'Germanium', 'Arsenic', 'Selenium', 'Bromine', 'Krypton', 'Rubidium', 'Strontium', 'Yttrium', 'Zirconium', 'Niobium', 'Molybdenum', 'Technetium', 'Ruthenium', 'Rhodium', 'Palladium', 'Silver', 'Cadmium', 'Indium', 'Tin', 'Antimony', 'Tellurium', 'Iodine', 'Xenon', 'Cesium', 'Barium', 'Lanthanum', 'Cerium', 'Praseodymium', 'Neodymium', 'Promethium', 'Samarium', 'Europium', 'Gadolinium', 'Terbium', 'Dysprosium', 'Holmium', 'Erbium', 'Thulium', 'Ytterbium', 'Lutetium', 'Hafnium', 'Tantalum', 'Tungsten', 'Rhenium', 'Osmium', 'Iridium', 'Platinum', 'Gold', 'Mercury', 'Thallium', 'Lead', 'Bismuth', 'Polonium', 'Astatine', 'Radon', 'Francium', 'Radium', 'Actinium', 'Thorium', 'Protactinium', 'Uranium', 'Neptunium', 'Plutonium', 'Americium', 'Curium', 'Berkelium', 'Californium', 'Einsteinium', 'Fermium', 'Mendelevium', 'Nobelium', 'Lawrencium', 'Rutherfordium', 'Dubnium', 'Seaborgium', 'Bohrium', 'Hassium', 'Meitnerium', 'Darmstadtium', 'Roentgenium', 'Copernicium', 'Nihonium', 'Flerovium', 'Moscovium', 'Livermorium', 'Tennessine', 'Oganesson']


with the respective element symbols:

['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og']


# Input

The code you write should receive an element name in any sensible format, such as a string "helium". You may assume whatever capitalization that suits your needs.

# Output

The code you write should return the element's symbol as a string, with any capitalization that suits your needs. Bonus imaginary internet points if you return the symbol with the standard capitalization.

# Scoring

This is so your answer doesn't win by being the shortest! You will be provided 118 test cases. Your score will be your code's byte count divided by the percentage of test cases your code passes correctly. Lowest score wins!

E.g. my code has 1 byte and I get 1 test case correct. My score is $$\1 / \frac{1}{118} = 118 \$$. Someone else writes some code with 110 bytes but gets all the test cases correct. The other person scores $$\ 110 / \frac{118}{118} = 110 \$$, meaning the other person has a better score than me.

# Test cases:

'Hydrogen' -> 'H'
'Helium' -> 'He'
'Lithium' -> 'Li'
'Beryllium' -> 'Be'
'Boron' -> 'B'
'Carbon' -> 'C'
'Nitrogen' -> 'N'
'Oxygen' -> 'O'
'Fluorine' -> 'F'
'Neon' -> 'Ne'
'Sodium' -> 'Na'
'Magnesium' -> 'Mg'
'Aluminium' -> 'Al'
'Silicon' -> 'Si'
'Phosphorus' -> 'P'
'Sulfur' -> 'S'
'Chlorine' -> 'Cl'
'Argon' -> 'Ar'
'Potassium' -> 'K'
'Calcium' -> 'Ca'
'Scandium' -> 'Sc'
'Titanium' -> 'Ti'
'Chromium' -> 'Cr'
'Manganese' -> 'Mn'
'Iron' -> 'Fe'
'Cobalt' -> 'Co'
'Nickel' -> 'Ni'
'Copper' -> 'Cu'
'Zinc' -> 'Zn'
'Gallium' -> 'Ga'
'Germanium' -> 'Ge'
'Arsenic' -> 'As'
'Selenium' -> 'Se'
'Bromine' -> 'Br'
'Krypton' -> 'Kr'
'Rubidium' -> 'Rb'
'Strontium' -> 'Sr'
'Yttrium' -> 'Y'
'Zirconium' -> 'Zr'
'Niobium' -> 'Nb'
'Molybdenum' -> 'Mo'
'Technetium' -> 'Tc'
'Ruthenium' -> 'Ru'
'Rhodium' -> 'Rh'
'Silver' -> 'Ag'
'Indium' -> 'In'
'Tin' -> 'Sn'
'Antimony' -> 'Sb'
'Tellurium' -> 'Te'
'Iodine' -> 'I'
'Xenon' -> 'Xe'
'Cesium' -> 'Cs'
'Barium' -> 'Ba'
'Lanthanum' -> 'La'
'Cerium' -> 'Ce'
'Praseodymium' -> 'Pr'
'Neodymium' -> 'Nd'
'Promethium' -> 'Pm'
'Samarium' -> 'Sm'
'Europium' -> 'Eu'
'Terbium' -> 'Tb'
'Dysprosium' -> 'Dy'
'Holmium' -> 'Ho'
'Erbium' -> 'Er'
'Thulium' -> 'Tm'
'Ytterbium' -> 'Yb'
'Lutetium' -> 'Lu'
'Hafnium' -> 'Hf'
'Tantalum' -> 'Ta'
'Tungsten' -> 'W'
'Rhenium' -> 'Re'
'Osmium' -> 'Os'
'Iridium' -> 'Ir'
'Platinum' -> 'Pt'
'Gold' -> 'Au'
'Mercury' -> 'Hg'
'Thallium' -> 'Tl'
'Bismuth' -> 'Bi'
'Polonium' -> 'Po'
'Astatine' -> 'At'
'Francium' -> 'Fr'
'Actinium' -> 'Ac'
'Thorium' -> 'Th'
'Protactinium' -> 'Pa'
'Uranium' -> 'U'
'Neptunium' -> 'Np'
'Plutonium' -> 'Pu'
'Americium' -> 'Am'
'Curium' -> 'Cm'
'Berkelium' -> 'Bk'
'Californium' -> 'Cf'
'Einsteinium' -> 'Es'
'Fermium' -> 'Fm'
'Mendelevium' -> 'Md'
'Nobelium' -> 'No'
'Lawrencium' -> 'Lr'
'Rutherfordium' -> 'Rf'
'Dubnium' -> 'Db'
'Seaborgium' -> 'Sg'
'Bohrium' -> 'Bh'
'Hassium' -> 'Hs'
'Meitnerium' -> 'Mt'
'Roentgenium' -> 'Rg'
'Copernicium' -> 'Cn'
'Nihonium' -> 'Nh'
'Flerovium' -> 'Fl'
'Moscovium' -> 'Mc'
'Livermorium' -> 'Lv'
'Tennessine' -> 'Ts'
'Oganesson' -> 'Og'


I used this code to shape the list into the test cases, might be useful to you.

Elements and symbols extracted from https://www.thoughtco.com/element-list-names-atomic-numbers-606529, visited at the 9th of February of 2020. At the time of writing, 118 elements were available. Source included "Aluminum" and "Aluminium" as alternatives, dropped "Aluminum" for the purposes of this challenge.

• This is just a massive lookup table. I don't like it. – S.S. Anne Feb 10 at 0:50
• "Aluminum" might be in the dictionaries of some languages. I suggest allowing either but and/or both in the solution and specifying which one was chosen. – S.S. Anne Feb 10 at 1:07
• Dupe – Jo King Feb 10 at 2:55
• @JoKing this being a code challenge doesn't make it different from the dupe you linked? – RGS Feb 10 at 7:02
• I think the problem you have is that your scoring strongly incentivises submitting H as the best answer. The other question had a shortest solution of 200 bytes - which can't get a better score than the 1 byte 1 answer program. – FryAmTheEggman Feb 10 at 19:52
• @FryAmTheEggman thanks for the feedback. Would you suggest tweaking the score or dropping this challenge? – RGS Feb 10 at 20:19
• You might consider a similar idea but with something that hasn't been done as much. I think it depends on how you feel, it certainly isn't unsalvageable. – FryAmTheEggman Feb 10 at 20:27
• @FryAmTheEggman very nice idea. I am thinking airport codes, country codes or military rank abbreviations... – RGS Feb 10 at 21:21
• I really like this idea, and I think allowing approximate answers makes it distinct enough from this that it's not a dupe. However, the current scoring encourages very inaccurate, trivial answers. The best I could find in 05AB1E is 2£ (05AB1E to output the first 2 characters of the input), which gets 45 test cases correct, scoring better than a 6 character answer that gets everything right. – Grimmy Feb 14 at 16:03
• @Grimmy thanks for your very detailed feedback! Like I mentioned above, I'm exploring the possibility of using something other than chemical symbols. In your opinion, would you tweak the scoring or would you suggest something other than chemical symbols? – RGS Feb 14 at 16:20

# Be second to last

This is a challenge with a game with a clear winning strategy, but the winner is not the one who comes in first, but the one who comes in second to last! While losing is easy (just throw every game), just barely not losing is quite a task.

## The Game

The bots will be made to play games of normal Nim against each other. The rules are as follows:

• The board consists of a list of unsigned integers
• In alternating turns, the players reduce one non-zero element by an amount of their choosing, as long as the element is not negative afterwards
• The player who reduces the list to all entries being 0 wins

The length of the Nim list and its entries will be randomly determined for each game.

## The Tournament

All bots will compete against each other in a Danish-Style tournament:

• Initially, players are assigned positions in a list randomly
• After each round, the list is sorted by the amount of wins with an order-preserving method
• In each round, the players with the odd numbers play against those with the following even numbers (so 1st against 2nd, 3rd against 4th, and so forth)
• If the number of players is odd, the one in the middle position has a bye and is given 1 win without playing.
• The tournament ends after $$\\lceil \log_{2}(N_{Players}) \rceil\$$ (Binary logarithm of the number of players, rounded up) rounds.

The player in the second to last position of the list counts as the total winner of the tournament.

## King of the Hill

Each time the contest is run, 100 tournaments are played. The bots with the highest number of being second to last is the overall winner.

# Challenge Rules

• Each bot is a Python 3 class implementing the following functions:
• __init__(ID, n) passes the bot its randomly assigned ID for this tournament, and the total number of players.
• nim(self,list) which takes in the Nim board state and returns a tuple (index, amount), specifying from which list index to subtract what number. This function is repeatedly called during each game of Nim played, until a winner has been determined.
• rank(self,IDs,scores) which takes in the current order of ranking in the tournament, and the list of scores of each bot, ordered by ID. It returns nothing. This will be called for each bot after each round of tournament, as well as before the first round, to provide the ranking information if the bot requires it.
• Bots are explicitly allowed to implement further functions and store data for private use. Bots will only be deleted and re-initialized after each full tournament.
• Programming meta-effects are forbidden, meaning any attempts to directly access other bots' code, the Controller's code, causing Exceptions or similar. Any bot doing so is disqualified until fixed.
• The following will also be set up to cause Exceptions:
• nim returning an index of which the element is already 0
• nim return an amount larger than the element at that index
• Other languages are allowed only in case they can be easily converted to Python 3.
• Class names have to be unique
• Multiple bots per person are allowed, but only the latest version will be taken of iteratively updated bots.
• As per Standard Loopholes, copies of bots are not allowed. This includes bots who differ from other bots only by a trivial change in strategy (e.g. a change in the pseudorandom seed).

## Controller and Examples

Watch this space.

• this sounds fun! I have no idea how it fits this community, but I can't wait to see this in the main site! – RGS Feb 11 at 16:04
• @RGS king-of-the-hill challenges are common -- not all challenges have to be code-golf. – S.S. Anne Feb 11 at 23:55
• @S.S.Anne I know not everything has to be code golf, I'm just saying that in the little time I've been active, I've never seen a KotH challenge – RGS Feb 12 at 7:01

# Compress even permutations

## Factorial number system

Every nonnegative integer can be encoded by factorial number system. Factorial number system doesn't have a fixed radix, but uses the factorial of nonnegative integers as radices. The place of $$\0!\$$ can have $$\0\$$ as the digit, the place of $$\1!\$$ can have $$\0\$$ or $$\1\$$ as the digit, the place of $$\2!\$$ can have $$\0\$$, $$\1\$$, or $$\2\$$ as the digit, and so on. Subscript exclamation mark denotes that the integer is encoded in factorial number system. For example:

$$41010_! = 4 \times 4! + 1 \times 3! + 0 \times 2! + 1 \times 1! + 0 \times 0!= 103_{10}$$

## Permutations

Numbers encoded by factorial number system has one-to-one correspondence to permutations:

$$41010_! \cong \begin{pmatrix} 0 \\ 0 \end{pmatrix} \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \begin{pmatrix} 2 & 1 & 0 \\ 2 & 1 & 0 \end{pmatrix} \begin{pmatrix} 3 & 2 & 1 & 0 \\ 0 & 3 & 2 & 1 \end{pmatrix} \begin{pmatrix} 4 & 3 & 2 & 1 & 0 \\ 3 & 2 & 1 & 0 & 4 \end{pmatrix} = \begin{pmatrix} 4 & 3 & 2 & 1 & 0 \\ 1 & 3 & 2 & 0 & 4 \end{pmatrix}$$

That is, each the place of $$\n!\$$ represents a right-direction rotation of $$\n\$$ through $$\0\$$, and its digit represents what $$\0\$$ becomes after the rotation.

It follows that the parity of the permutation is same as the parity of the sum of digits at the places of factorials of odd numbers. For $$\41010_!\$$, the permutation is even because $$\1 + 1 = 2\$$ is even.

## Objective

An even permutation of 5 elements, or any equivalent object will be the input. That leaves $$\5! \div 2 = 60\$$ distinct permutations. Compress it to $$\\lceil \log_2{60}\rceil=6\$$ bits.

## Rules

• Input type and format doesn't matter. Possible choices of input format include (in C++):

• std::map<int,int> scrambling the numbers from $$\4\$$ to $$\0\$$

• int[5] containing the digits of the factorial number system

• int[4] containing the digits of the factorial number system, except the place of $$\0!\$$ (it doesn't contribute to the permutation)

• int encoded by the factorial number system

• Output type and format doesn't matter either. It may be:

• bool[6]

• int8_t

• a bit field

• std::string containing ASCII digit 0s and 1s

• Invalid inputs fall in don't care situation.

I want to ask a combined popularity / objectively scored question. Something like:

Take a string as input. Match the string to a famous painting such as "Mona Lisa" and render a cartoon version of it. 1 point per painting, 1 point per upvote. Voting closes on XX/YY/ZZZZ.

I want to reward people for including more possibilities (there will be a fixed upper limit, unlike with paintings). I also want to reward people for the quality of their renderings. The cartoon paintings should be recognisable as versions of the real paintings.

Is this a good scoring system? If not, what would be better?

• This is somewhat vague. Can you be more precise? – Don Thousand Feb 17 at 15:38

# Simplify a directed graph

## Input

A connected directed graph, in any convenient format. A valid format (and probably the most convenient) would be a list of edges.

## Simplification

These two reductions are performed as often as possible. It does not suffice to apply one reduction first, then the other, as each of them can cause more of the other one.

Let $$\E\$$ be the set of all edges of the graph in the following explanations. For example $$\E = \{(0, 1), (1, 2), (2, 0)\}\$$ represents the following graph:

0 ----> 1
^       |
'-- 2 <-'


Let $$\E_a\$$, where $$\a\$$ is a vertex, indicate the set of edges involving $$\a\$$:

$$E_a := \{(u, v) \in E : u = a \vee v = a\}$$

Two graphs are isomorphic iff all vertices from one graph can be relabeled to make it equal to the other graph.

### Deduplication

If there are disjoint sets of vertices $$\M\$$ and $$\N\$$ ($$\M \cap N = \emptyset\$$) not directly connected ($$\((M, N) \cup (N, M)) \cap E = \emptyset\$$) and the graphs with edges $$\E \setminus E_M\$$ and $$\E \setminus E_N\$$ are isomorphic, then the vertices $$\M\$$ (or $$\N\$$, but not both, are removed).

This means that of any two non-overlapping, non-directly-connected subgraphs that leave isomorphic graphs behind when removed, one is removed.

Simple example:

b --> 1
^  ==>  b --> 1
|
a

### Relay removal

If there are vertices $$\a\$$ and $$\b\$$ and a non-empty set of vertices $$\N\$$, such that $$\b \notin N\$$ and $$\E_b = \{(a, b)\} \cup (b, N)\$$, then $$\b\$$ is removed from the graph and edges $$\(a, N)\$$ are added if they do not alreay exist.

This means that a vertex with exactly one edge ending there, at least one edge starting there and no self-loop can be removed, moving the starting edges to the start of the ending edge.

Simple example:

1             1
^             ^
|             |
O --> a --> b  ==>  O --> a ----.
^     |             ^     |
|     v             |     v
'---- 2             '---- 2


## Output

The output is the result of the reductions, in any convenient format. If identifiers are used for edges or vertices, as in a list of edges, these identifiers are not required to correspond to identifiers in the input.

A different format may be used for input and output.

## Scoring

This is : Lowest bytecount in each language wins. No answer will be accepted, as there is no overall winner.

## Other rules

• Standard loopholes apply
• Functions or programs
• Any input and output methods (STDIN, arguments, prompt(), ...)

not yet

## Meta:

• Everything clear?
• Better explanations?
• Better title?
• I'm not sure whether output might depend on the order in which reductions are performed.

# Let's Play Countdown!

(The Numbers round this time)

Countdown is a British TV game show composed of three different styles of rounds; the letters round, the conundrum, and the numbers round.

The conundrum could be solved with the same program you'd make for the Letters round, so let's tackle the third option that hasn't been done yet!

## Challenge

Take in a set of numbers. One of which is the "Target" number, and the rest are the building numbers.

The Countdown Number Round asks you to take the building numbers and to construct the Target number only using the four elementary operators. Every step must result in another strictly-positive integer (so non-perfect division is disallowed). Output the method to which you can construct the target number. If that's impossible, get as close as possible (above or below are scored the same). Numbers do not need to be used, but may NOT be reused.

Note - You will perform at most N-1 operations, where N is the number of building numbers. Every elementary operator takes in two inputs and provides one, so you "lose" one from your ranking every operation. That should give you an idea of the size of your output.

I/O is in any reasonable format, but target vs building numbers must be obviously distinct (either by the target being the first or the last number, or outside an array, or a different type, etc).

Output needs to explain exactly what operations are being performed on what numbers, and what the output for each operation would be, but can be done in whichever way seems reasonable.

## Example I/O

In these examples, the first element is the target.

[888 100 2 75 3 1 10]
75-1=74
10+2=12
74x12=888

[766 22 10 8 3 1]
22+10=32
32x8=256
256-1=255
255x3=765 #You cannot get this one exactly, but one-off is close.


## Sandbox Questions

I'm... like 85% sure this isn't anywhere here yet. I did a chunk of searching and couldn't find anything that fit the bill, so I think this is clear?

Any other neat examples you guys got?

New contributor
Mathgeek is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
• As you say, I don't think we have exactly this challenge, but there are many similar ones. I doubt you will get anything besides brute forcing all possible arrangements then sorting them by nearness to the target. Separately, if there are multiple tying solutions you don't require that e.g. the shortest be output, correct? It is probably worth mentioning that. – FryAmTheEggman Feb 21 at 21:24

Recently, in my algebra class, we proved that the following process always stops at some point, so I thought it would be a cool challenge!

Input: Two reals a,b.

Output Non-negative integer

Challenge:

Given two reals a,b, initialize a count variable c to 0, consider the quadratic equation

x^2+ax+b


If this quadratic has real roots r,s (r<=s), increment the counter by 1, and replace a,b with r,s and repeat the process.

If the quadratic has complex roots, return c.

Test Cases

## Doubly stochastic matrix code-golf

A doubly-stochastic matrix is a square matrix of non-negative real entries each of whose rows and columns sums to 1. Given a doubly-stochastic matrix, express it as a non-negative linear combination of permutation matrices, as is guaranteed to exist by the Birkhoff–von Neumann theorem.

TODO: Example, better explanation, test cases. If you want to develop and post this challenge, it's yours.

• I liked this idea! May I work on this and give you credit? If I manage to do so before you, of course. – RGS yesterday

# Implement GF(2²)

## Introduction to groups and fields

An additive group is a set with addition and negation defined. They must satisfy the following conditions:

• $$\0\$$ is the additive identity.

• For every $$\x\$$, the negation of $$\x\$$, $$\-x\$$ exists, and $$\x + (-x) = (-x) + x = 0\$$.

A field is an additive abelian group with multiplication and reciprocal defined. They must satisfy the following conditions:

• $$\1\$$ is the multiplicative identity.

• Multiplication is associative and commutative.

• For every nonzero $$\x\$$, the reciprocal of $$\x\$$, $$\x^{-1}\$$ uniquely exists, and $$\x\times x^{-1} = x^{-1}\times x = 1\$$.

## Modular Arithmetic

For every positive integer $$\n\$$, you can define an additive abelian group as follows:

• Define the set as integers from $$\0\$$ to $$\n-1\$$.

• Define addition as usual addition with the result moduloed by $$\n\$$.

• Define negation as usual negation with the result moduloed by $$\n\$$.

This group is denoted by $$\ℤ_n\$$. If $$\n\$$ is prime, multiplication can be analogously defined, making it a field. In particular, the operation tables of $$\ℤ_2\$$ are:

$$\begin{array}{l|ll} + & 0 & 1 \\ \hline 0 & 0 & 1 \\ 1 & 1 & 0 \end{array} \begin{array}{l|ll} x & -x \\ \hline 0 & 0 \\ 1 & 1 \end{array} \begin{array}{l|ll} × & 0 & 1 \\ \hline 0 & 0 & 0 \\ 1 & 0 & 1 \end{array} \begin{array}{l|ll} x & x^{-1} \\ \hline 0 & \text{NaN} \\ 1 & 1 \end{array}$$

## Galois Field GF(2²)

A Galois field $$\\text{GF}(p^k)\$$ emerges when one takes the set as polynomials over $$\ℤ_p\$$, and defines addition and multiplication as the usual operation with polynomial modulo, where the modding polynomial is irreducible and has degree of $$\k\$$. Since $$\x^2+x+1\$$ is an (in fact, the only) irreducible polynomial over $$\ℤ_2\$$ that has degree $$\2\$$, this results in $$\\text{GF}(2^2)\$$. Its operation tables are:

$$\begin{array}{l|ll} + & 0 & 1 & x & x+1 \\ \hline 0 & 0 & 1 & x & x+1 \\ 1 & 1 & 0 & x+1 & x \\ x & x & x+1 & 0 & 1 \\ x+1 & x+1 & x & 1 & 0 \end{array} \begin{array}{l|ll} f(x) & -f(x) \\ \hline 0 & 0 \\ 1 & 1 \\ x & x \\ x+1 & x+1 \end{array} \\ \begin{array}{l|ll} × & 0 & 1 & x & x+1 \\ \hline 0 & 0 & 0 & 0 & 0 \\ 1 & 0 & 1 & x & x+1 \\ x & 0 & x & x+1 & 1 \\ x+1 & 0 & x+1 & 1 & x \end{array} \begin{array}{l|ll} f(x) & f(x)^{-1} \\ \hline 0 & \text{NaN} \\ 1 & 1 \\ x & x+1 \\ x+1 & x \end{array}$$

Your task is to implement the set and the operations. As a conseuqence, you must have:

• The members of the set defined as constants (2-bit bitstring, an ASCII digit, or whatever). This won't contribute to the score.

• Four codes that defines each operations, whose input(s) is/are as defined above.

## Rules

• Though defined as polynomials, the type and format of the inputs doesn't matter. You must have the same type for every input.

• The type and format of the outputs doesn't matter either, but it must be the same as the input(s).

• The reciprocal of $$\0\$$ must result in an "error" condition. This includes returning an errornous value, throwing an error, or terminating the program. It must halt.

• Other invalid inputs fall in don't care situation.

• Since there are multiple codes, the score for code golf is alloted by the sum of their lengths in bytes.

• Related: GF(2^8) and GF(3^2), though neither asks for negation or multiplicative inverse. Also, A code that defines the set as a type can be problematic in many languages where the concept of "type" is not well-defined. I'd suggest to exclude it from the code size and just ask the answerer to provide the four values corresponding to $0, 1, x, x+1$ respectively. – Bubbler yesterday
• @DonThousand Requiring the uniqueness of a negation resolves the issue. Also, it would take too long to explain the "actual" definition of $\mathbb{Z}_p$. So I defined it with usual modulo. – Dannyu NDos yesterday
• @DonThousand $(-a) + a = 0$ implies $(-(-a)) + (-a) = 0$. So both $a$ and $-(-a)$ are additive inverses of $-a$. By uniqueness of additive inverse, it follows $-(-a) = a$. – Dannyu NDos yesterday
• @DannyuNDos Incorrect, you assume commutativity again. $a$ is a right inverse, and $-(-a)$ is a left inverse of $-a$ – Don Thousand yesterday
• @DonThousand The definition of group states that a left inverse must be the right inverse, and a right inverse must be the left inverse. Such inverse always uniquely exists. – Dannyu NDos yesterday
• @DannyuNDos That's my point. Your definition doesn't say that the right inverse = left inverse. – Don Thousand yesterday
• @DonThousand Oh my! So there was the flaw. I only remembered the definition, but not memorized it. Thanks anyways. – Dannyu NDos yesterday
• @DannyuNDos Yea, lol. Sheesh, that was a journey. – Don Thousand yesterday
• @DonThousand You only need a right zero and right inverses, then we get left zero and left inverses, and they are unique (we also don't have to demand that). Proof that right inverses are left inverses: $(-a)+a=(-a)+a+0=(-a)+a+(((-a)+a)+(-((-a)+a)))=(-a)+(a+(-a))+a+(-((-a)+a))=((-a)+0)+a+(-((-a)+a))=((-a)+a)+(-((-a)+a))=0$. Using this gives left zero: $0+a=(a+(-a))+a=a+((-a)+a)=a+0=a$. – Christian Sievers yesterday

# Shared Letters in consecutive numbers

Inspired by this puzzling question.

It turns out that, in English, every pair of consecutive integers (e.g. 0,1, 1,2, etc.) shares at least one letter when spelled out (e.g. zErO, OnE (or NOught, ONe); One, twO, etc).

## Input

Any two non-negative integers (all natural numbers including 0) up to and including one googol. These can be input as any type you choose, but string representations must only use the characters 0123456789.,' (i.e. the numbers must not already be spelled out on input, but rather input as a numeral).

You can assume that the two numbers will be consecutive.

Some examples of valid inputs:

{1,2}
{"1","2"}
{1},{2}
{{"1"},{2}}
"123,245", "123,246"
"123.456", "123'457"

some examples of invalid inputs

{1,3}
{-1,0}
{1.1,1.2}
{"one","two"}

The Challenge

Given the two inputs, output all shared characters when spelled (both numbers spelled in either lower or upper-case, the same case for both numbers).

A sample implementation for spelling numbers can be found here: https://stackoverflow.com/a/3911982/318414; but I'm sure other options exist; and there are certainly efficiencies to be found given that there are large amounts of shared strings, once you get into the higher numbers. See also https://simple.wikipedia.org/wiki/Names_for_large_numbers for the names of large numbers.

, usual exclusions apply

Output The shared letters, in any reasonable format. Any of the three numbering systems on the Wikipedia page are valid.

Examples

I will be assuming British English (long form) in my examples.

{6,7} -> "s" or "S" (six, seven)

{999,1000} -> {"n","e"," ","t","h","u","a","d"} (nine hundred and ninety nine, one thousand)

{88955,88956} ->  (eighty eight thousand nine hundred and fifty five, eighty eight thousand nine hundred and fifty six)

1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 -> "ONE THUSADQICL" (ONE THOUSAND QUINDECILLION, ONE THOUSAND QUINDECILLION AND ONE)

9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -> el no (nine hundred and ninety nine thousand sexdecillion **nine hundred and ninety nine thousand quindecillion nine hundred and ninety nine thousand quatturodecillion nine hundred and ninety nine thousand tredecillion nine hundred and ninety nine thousand duodecillion nine hundred and ninety nine thousand undecillion nine hundred and ninety nine thousand decillion nine hundred and ninety nine thousand nonillion nine hundred and ninety nine thousand octillion nine hundred and ninety nine thousand septillion nine hundred and ninety nine thousand sextillion nine hundred and ninety nine thousand quintillion nine hundred and ninety nine thousand quadrillion nine hundred and ninety nine thousand trillion nine hundred and ninety nine thousand billion nine hundred and ninety nine thousand million nine hundred and ninety nine thousand nine hundred and ninety nine; one googol)

• "Any two positive integers (all natural numbers including 0)" You should reword this because 0 is not a positive integer. – 79037662 Feb 22 at 4:34

# Introduction

You are an NSA undercover agent in a Middle-Eastern HR company, you just received a list of people with their jobs in many different languages. Some are spies and you need to know who. Your mission, if you accept it, is to get what are people working in, and relate it to a list of job categories. Most dangerous elements are those working in Law enforcement and security. However as your code will be part of a bigger file it needs to be as short in lines as possible for stealthness. This comes from expectations I encountered in the administration to keep some mystery behind code, if ever it were to be stolen.

• This challenges your way to handle loops, map, reduce and filter, destructuring or unpacking an array/csv/df. Last but not least it allows you to get into the fascinating world of cross-language nlp.

I provide an example in python (64 lines of code)

# Challenge

The challenge is to get, in the shortest amount of bytes (libraries not included) the most similar element in an array of string with another string, and this for each line of a csv taken as input.

• Inputs:

1. X.csv a csv/dataframe of actual jobs that look like this one:
,new_professionactuelle
0,Entrepreneur
1,طالبة
2,ETUDIANT
3,ETUDIANT
4,موظف
5,موجه تربوي
6,Réalisateur film cartoon
7,إإطار مالي
8,موضف إطار
9,مهندس بمكتب دراسات
10,باحثة  _ كاتبة _
11,طالب
12,Chef de projet
13,ASSUREUR
14,FONCTIONNAIRE D'ÉTAT
15,Professeur Universitaire
17,fonctionnaire
19,professeur
20,Chef de projet
21,مدير  شركة
22,Avocat
24,Employé
25,Consultant en Immobilier
26,fonctionnaire
27,اجير أو عامل

1. df.csv job categories that must include all the following categories:

['Agriculture, farming and environment',
'Accountancy, banking and finance',
'Teacher training and education', 'Leisure, sport and tourism',
'Transport and logistics', 'Information technology',
'Hospitality and events management',
'Business, consulting and management', 'Creative arts and design',
'Property and construction', 'Law',
'Engineering and manufacturing', 'Social care',
'Charity and voluntary work', 'Sales',
'Healthcare', 'Energy and utilities',
'Marketing, advertising and PR', 'Media and internet',
'Recruitment and HR', 'Science and pharmaceuticals']

• Output would be the column in X.csv plus a new column, the most similar job. The most accurate results are:
,new_professionactuelle,category
1,طالبة,Teacher training and education
2,ETUDIANT,Teacher training and education
3,ETUDIANT ,Teacher training and education
4,موظف,Recruitment and HR
5,موجه تربوي ,Teacher training and education
6,Réalisateur film cartoon,Creative arts and design
7,إإطار مالي,"Accountancy, banking and finance"
9,مهندس بمكتب دراسات,Engineering and manufacturing
10,باحثة  _ كاتبة _ ,Recruitment and HR
11,طالب,Teacher training and education
12,Chef de projet,Creative arts and design
15,Professeur Universitaire,Teacher training and education
18,CDB Retraite,Recruitment and HR
19,professeur,Teacher training and education
20,Chef de projet,Public services and administration
21,مدير  شركة,Recruitment and HR
22,Avocat,Law
23,cadre à Maroc Telecom,Media and internet
24,Employé ,Sales
25,Consultant en Immobilier,Property and construction
27,اجير أو عامل,Recruitment and HR

• Inputs should be tested against all categories.

The winner of the challenge will be the one with the most accurate results. If on the test set. If several are as accurate, the shortest amount of bytes will be the winner. You can use any methods to get the most similar item. The state of the art method seems to be according to Google Multilingual Universal Sentence encoder. I provide an attempt with the code below but you will see it is not quite acccurate.

# Example in Python

Double agent: A spy who works for two countries, and sometimes even three, in which case he is definitely a trouble. - Mots et Grumots (2003), Marc Escayrol

#@title Setup common imports and functions
import numpy as np
import os
import pandas as pd
import tensorflow.compat.v2 as tf
import tensorflow_hub as hub
from tensorflow_text import SentencepieceTokenizer
import sklearn.metrics.pairwise

from simpleneighbors import SimpleNeighbors
from tqdm import tqdm
from tqdm import trange

import json

def most_similar(embeddings_1, embeddings_2, labels_1, labels_2):

assert (len(embeddings_1) == len(labels_1) and len(embeddings_2) == len(labels_2))

# arccos based text similarity (Yang et al. 2019; Cer et al. 2019)
sim = 1 - np.arccos(sklearn.metrics.pairwise.cosine_similarity(embeddings_1, embeddings_2))/np.pi

embeddings_1_col, embeddings_2_col, sim_col = [], [], []
for i in range(len(embeddings_1)):
for j in range(len(embeddings_2)):
embeddings_1_col.append(labels_1[i])
embeddings_2_col.append(labels_2[j])
sim_col.append(sim[i][j])
df = pd.DataFrame(zip(embeddings_1_col, embeddings_2_col, sim_col),
columns=['embeddings_1', 'embeddings_2', 'sim'])

# return the higest similarity one
category = df['embeddings_1'].iloc[df['sim'].argmax()]
return category

def main():

# The 16-language multilingual module is the default but feel free
# to pick others from the list and compare the results.

def embed_text(input):
return model(input)

def compute_similarity(references, target):
# I want to create as many rows as there are references and fill them with the results
# arccos based text similarity (Yang et al. 2019; Cer et al. 2019)
for row in target.iterrows():
for reference in references:
sim = 1 - np.arccos(
result = sklearn.metrics.pairwise.cosine_similarity(row,
reference))/np.pi

# place the result in the column "reference"

# get unique job categories and job of people
job_categories = X.S02Q11_Professional_field.unique()
# turn them to list
job_categories = job_categories.tolist()
# emebedding job categories
references_result = embed_text(job_categories[1:])

for _, row in df_rni.iterrows():
actual_job = row['new_professionactuelle']
# check for nan that can't be embedded
if str(actual_job) != 'nan':
# embedding actual job
target_result = embed_text(actual_job)
# visualize similarity
category = most_similar(references_result, target_result, job_categories[1:], [actual_job])
else: category = None

if __name__ == "__main__":
main()

New contributor
Revolucion for Monica is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
• @Arnauld Indeed, fixed, thanks! – Revolucion for Monica yesterday
• It looks like your reference code fetches output from an external source, which is forbidden by default. Please detail within the question how one would implement the Google Universal Sentence Encoder. (If the challenge actually requires querying tfhub.dev/google/universal-sentence-encoder-multilingual/3, I don't think that's gonna be appropriate for CGCC). – Grimmy yesterday
• @Grimmy Google Universal Encoder: that's not compulsory, but I find it very handy and a good tip to start. External source: yes, that's the way I provided example data like the inputs above. Should I hard code the sources? – Revolucion for Monica yesterday
• Wait, Google Universal Encoder isn't compulsory? That seems to contradict the most similar element in an array of string with another string according to Google Multilingual Universal Sentence encoder. If GMUSE isn't required, this sentence should be replaced by a proper definition of "most similar element", and GMUSE should only be mentioned in the footnotes. – Grimmy yesterday
• External source: yes, that's the way I provided example data like the inputs above. I'm confused. Do you use tfhub.dev/google/universal-sentence-encoder-multilingual/3 only to get example data? It sure doesn't look like that in your code. – Grimmy yesterday
• @Grimmy Porbably I misunderstood "It looks like your reference code fetches output from an external source" then, my apologizes. – Revolucion for Monica yesterday
• This needs an explanation of how "accuracy" is computed. (And you still need to define "most similar"). – Grimmy yesterday

# Context

After a challenge of mine asking you to compute a specific coefficient of polynomial multiplication, I wish to create a "mirror" one, asking you to compute a specific coefficient from polynomial division.

# Polynomial division

Let us establish an analogy with integer division. If you have to integers a and b, then there is a unique way of writing a = qb + r, with q, r integers and 0 <= r < b.

Let p(x), a(x) be two polynomials. Then there is a unique way of writing a(x) = q(x)p(x) + r(x), where q(x), r(x) are two polynomials and the degree of r(x) is strictly less than the degree of p(x).

Given two polynomials a(x), p(x) such that there exists q(x) satisfying a(x) = p(x)q(x) (with all three polynomials having integer coefficients), find the coefficient of q(x) of degree k.

(Yes, we are assuming the remainder is 0)

# Input

Two polynomials (with integer coefficients) and an integer.

Each input polynomial can be in any sensible format. A few suggestions come to mind:

• A string, like "1 + 3x + 5x^2"
• A list of coefficients where index encodes exponent, like [1, 3, 5]
• A list of (coefficient, exponent) pairs, like [(1, 0), (3, 1), (5, 2)]

An input format must be sensible AND completely unambiguous over the input space.

The integer k is a non-negative integer. You may take it in any of the usual ways. You can assume k is less than or equal to the differences of the degrees of a(x) and p(x), i.e. k <= deg(a) - deg(p) and you can assume deg(a) >= deg(p).

# Output

The integer corresponding to the coefficient of x^k in the polynomial q(x) that satisfies the equality a(x) = q(x)p(x).

# Test cases

The input order is a(x), p(x), integer k.

[15], [4], 0 -> 3
[0, 0, 6], [0, 3], 0 -> 0
[0, 0, 6], [0, 3], 1 -> 2
[0, 70, 70, 17, 70, 61, 6], [0, 10, 10, 1], 0 -> 7
[0, 70, 70, 17, 70, 61, 6], [0, 10, 10, 1], 1 -> 1
[0, 70, 70, 17, 70, 61, 6], [0, 10, 10, 1], 2 -> 6
[-50, 20, -35, -173, -80, 2, -9, -10, 1], [0, 10, 10, 1], 0 -> -5
[-50, 20, -35, -173, -80, 2, -9, -10, 1], [0, 10, 10, 1], 1 -> 7
[-50, 20, -35, -173, -80, 2, -9, -10, 1], [0, 10, 10, 1], 2 -> -10
[-50, 20, -35, -173, -80, 2, -9, -10, 1], [0, 10, 10, 1], 3 -> -8
[-50, 20, -35, -173, -80, 2, -9, -10, 1], [0, 10, 10, 1], 4 -> 1
[-50, 20, -35, -173, -80, 2, -9, -10, 1], [0, 10, 10, 1], 5 -> 0
[-50, 20, -35, -173, -80, 2, -9, -10, 1], [0, 10, 10, 1], 6 -> -1

• I remembered a harder-to-search-for existing challenge about getting a specific coefficient of the power series 1/q(x). Might this be too similar to p(x)/q(x) for polynomials? – xnor 2 days ago
• @xnor you could compute the power series of 1/q(x) up to a certain point and then multiply by p(x) but that still looks like a long way to go for such a simple task. – RGS 2 days ago
• @RGS There are a lot of languages with built-ins for handling polynomial ideals, which would trivialize this challenge, since one simply uses the canonical map (which is again, builtin). Mathematica is an example of a language which would do this in two builtins. – Don Thousand 2 days ago
• @DonThousand Two built-ins in Mathematica != short solution, so I'm pretty sure Mathematica would still be out-golfed... – RGS 2 days ago
• @RGS That doesn't change the fact that its a built-in problem, and not just in Mathematica. – Don Thousand yesterday

# Shift the letters, soldier !

## Context

We're at war! You need to transfert an important message to your general to inform him from an imminent assault. The thing is, your enemy knows a lot about cryptography : you will need to be more creative in order to encode your message...

Create a program that accept a message as input, and the encoded message as output. The message should be encoded this way : each character should get their ascii value to be shifted by their position in the message

For example, let's encode the message "Hello, world!"

H   e   l   l   o   ,       w   o   r   l   d   !     Original message
72  101 108 108 111 44  32  119 111 114 108 100 33    ASCII value
0   1   2   3   4   5   6   7   8   9   10  11  12    Place in the message
72  102 110 111 115 49  38  126 119 123 118 111 45    Encoded ascii (line 1 + line 2)
H   f   n   o   s   1   &   ~   w   {   v   o   -     Encoded message


The message Hello, world! should be encoded as Hfnos1&~w{vo-.

## Rules

• The message should be encoded as described before.
• If the new ascii value goes belong the limit, it should loop back to 1.
• Every character should be encoded. This includes punctuation, spaces etc.
• No standard loopholes allowed
• This is codegolf, so the shortest code wins.
• If you are able to decode a message, multiply your score by 0.7

# Meta

• Is the challenge clear enouth ?
• If the new ascii value goes *belong the limit*, it should loop back to **1** -> Where should i put the limit ? should i stop at 255 ? Or should i let the user decide of his own ?
• Is the extra decode rule ok ?

# How many strings within the character classes code-golfstringcombinatorics

Given a string composed of ASCII printable characters, return how many strings could fit the given pattern with character literals and regex-like ranges.

# Pattern string

The pattern string follows this grammar:

pattern_string := SAFE_CHAR | ASCII_RANGE pattern_string*
CHAR := any ASCII character in the range [32, 127]
SAFE_CHAR := any CHAR except '[', '-' and ']'
ASCII_RANGE := '[' CHAR '-' CHAR ']'


## Examples

Examples of pattern strings would be a, [0-*]4fj, [a-z][4-9]D[d-B].

# Input

The pattern string. You can assume all ranges are well-formed and that all the second characters in the ranges have their ASCII codepoints >= than the corresponding first characters in the range.

# Output

The integer corresponding to the number of strings that match the given pattern string.

# Test cases

"" -> 1
"a" -> 1
"[*-0]" -> 7
"[0-9][0-9]" -> 100
"[a-z]d[A-z]" -> 1508
"[<->]" -> 3
"[!-&]" -> 6
"[d-z]abf[d-z]fg" -> 529
"[[-]]" -> 3
"[a-a][b-b]cde[---]" -> 1
"[0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1]" -> 4096


You can check this Python reference implementation that I used to generate the test cases.

# Program calculating its own length code-golf

Your task is simple: write a program that produces its own length, without using any literals or built-in constants other than 0 (or its equivalents in your language).

## Rules

1. Your code must print its own length in bytes when run, followed by a single newline.
2. Your code cannot use any literals other than 0 (or whatever equivalents your language might have). This includes string and character literals.
3. Your code cannot use any built-in constants of your language, unless these are guaranteed to always have the value 0.
4. Any functions and operators provided by your language can be used.
5. You're not allowed to use any external libraries or external resources in your program.

## Scoring

The score of a valid program is its length in bytes. The score of an invalid program is ∞.
As this is code golf, lowest score wins.

• Does "any literals" include the more involved ones like function, array and object literals? Apart from this restriction, I'm pretty sure this has been asked before. – Martin Ender Aug 3 '14 at 17:54
• @MartinBüttner Probably a dupe: codegolf.stackexchange.com/q/27079/16402 – user16402 Aug 3 '14 at 17:58
• Would this Python entry be valid (not golfed)? It uses only globals. text = open(__file__, 'rb').read(); length = len(text); print(length) – Isiah Meadows Aug 12 '14 at 5:41
• May we use built-in lists that are guaranteed to be []? – Adám Feb 8 '19 at 8:28
• In Jelly (and likely much more esolangs), a empty program outputs 0, producing an answer that is very hard to beat; Try it online! – my pronoun is monicareinstate May 24 '19 at 8:44

# Complicating Simple Maths code-golf

We do know what 1 + 1 is, or 2 - 1. How about we turn those and other really simple operations into complex numbers?

## Goal:

As stated in the intro, taking an operation that can be done within the range of the following operators ( +, -, /, *, ^ and () ), print out a complex number operation that is pretty much a transformed version, and when done using the order of operations, results in the same answer as the inputted operation.

## Examples:

Input: 5 - 1
Output: 5 + 2i

Input: 4 * (7 ^ 2)
Output: (4 * 4i) * (7 ^ 2)


## Rules:

• It is recommended you print out the sector(s) that holds your complex number(s) as a + bi, e.g. (a + bi) - (ci * (di ^ f)). (NOTE: If you are doing non-communicative operations, such as ^, /, or -, the recommendation doesn't apply to the sub-operation).

• If you want to, feel free to use operations/functions other than the set mentioned in the Goal, but your input operation must have at least one of them.

• You can format your operators in any way, e.g. x or • instead of *, ÷ instead of /, etc.

• Input and output is allowed in any format as long as it fits within the standard I/O rules.

• Input must also be flexible (as in to return any input from a simple operation to a complex number operation.

• This is , so shortest answer wins.

## Sandbox use only:

Is there any way I can improve this challenge? Are there any other loopholes to be covered in the rules?

• Can you relax output to standard IO too? At the moment it seems you can only print the result. Also isn't this essentially calculate the result of the inputted expression then work out a complex expression that gives the same answer seeing as you don't need to keep anything in the input the same. – TheLethalCoder Aug 7 '17 at 10:32
• And if that is the case isn't this challenge just return input + (1 + i^2)? – TheLethalCoder Aug 7 '17 at 10:33
• No, the challenge is to transform parts of the input into complex numbers and output that. – S.G. Harmonia Aug 7 '17 at 13:13
• But 5 - 1 becomes 5 + 2i You are removing two stages - and 1 and adding 2 + and 2i. It's not entirely clear how much you can remove and how much you can add. – TheLethalCoder Aug 7 '17 at 13:15
• At least one sub-operation should be transformed from simple to complex (which could take two steps). – S.G. Harmonia Aug 7 '17 at 13:16

# Golf Cubically code code-challengefgitw

Your task is to optimize Cubically source code using one or more optimizations in this post.

How this challenge works:

• You will choose one or more optimizations below and write a program (in the language of your choice) that performs those optimizations on a Cubically program.
• Your program will take a Cubically program as input using any allowed input methods, and output a Cubically program using any allowed output methods.
• The first answer to successfully perform all optimizations wins!

# Optimizations

### 1. Face turn arguments

Before a face turn is performed, the interpreter calculates turns = turns mod 4. So R5 would be equivalent to R1 which is equivalent to R, R7 is equivalent to R3 which is equivalent to R', etc. Also note that R11111 is equivalent to R5, and R22 is equivalent to nothing at all.

Performing this optimization will mean evaluating all arguments to an R, L, U, D, M, E, or S command and shortening them as much as possible.

Test cases:

Relevant code -> Optimization
R11           -> R2
R1            -> R
L33           -> L2
U22           ->
D222          -> D2
M11111        -> M
E00001        -> E
S9            -> S


### 2. Repeated face turn

When multiple calls to the same face turn command are present right next to each other, they can clearly be golfed. For example, R2R1 is equivalent to R3. UUU is equivalent to U3. F2F2F2F2 is equivalent F8.

Test cases:

Relevant code -> optimization
R2R2R2        -> R6            (R2 if you also choose optimization 1)
LLL           -> L3
UU            -> UU or U2
D3D2D1        -> D6            (D2 if you also choose optimization 1)


### 3. "Set notepad to" commands

There are some commands that, instead of adding to/subtracting from/multiplying by/dividing by the notepad, just assign to it. Here are all such commands:

_^=<>⊕«»·|:


When called with multiple arguments, since each argument calls the command separately, only the final argument is relevant. So =123 is equivalent to =3, _00000 is equivalent to _0, and :12345678987654321 is equivalent to 1.

Test cases:

Relevant code -> Optimization
_333          -> _3
=12321        -> =1
+54321        -> +54321
:55           -> :5
/55           -> /55


### 4. Repeated non-face-turn commands

When multiple face turn commands are present right by each other, their arguments can simply be added together. Commands do not act this way. While R2 calls R with 2, =2 calls = with the face sum of the front face (face index 2).

To perform this optimization, when multiple commands outside of RLUDFBMES appear next to each other, simply remove the duplicated commands without removing the arguments.

Relevant code -> Optimization
_1_1_1_1      -> _1111         (_1 if you also choose optimization 3)
%11%22%33     -> %112233       (%3 if you also choose optimization 3)
+12345+67+8   -> +12345678


### 5. Nonexistent commands

Go check out the Cubically commands page and you'll see that there are plenty of characters that are not commands. For example, there are no commands that are lowercase letters.

To perform this optimization, remove all nonexistent commands and their arguments from the Cubically source. If the commands also have arguments, you must remove the arguments so that they are not passed to the previous command.

Test cases:

Relevant code -> Optimization
moo cow moo   ->
moo2cow2moo   ->
misteR2 FOO   -> R2F
FEAR ME.      -> ERME
u1U2u3U4u5U6  -> U2U4U6   (nothing if you also choose optimization 1, U12 if you also choose optimization 2)


There are lots of implicit commands in Cubically (RLUDFBMES()$~&E!), but there are plenty that need to be called with arguments. So %%%% is equivalent to nothing at all while %%2%% is equivalent to %2. Test cases: Relevant code -> Optimization %%%% ->  ->  ++2++2++2 -> +2+2+2 (+222 if you also choose optimization 4) +++>--<- -> Not Brainf**k, sorry! (:P)  # Sandbox I'll add more optimizations later. • Clarification on R123: That's the same as R6 and R2, not R3, right? Digits are summed, there are multidigit numbers? That would be better to specify – isaacg Aug 17 '17 at 20:13 • A few things: first, I can't find the tag "fgitw", is there a typo? Second, does optimization 1 require handling F and B as well, or just the currently listed ones? Third, in optimization 3 most of the listed commands seem invalid because the notepad is used in calculation and then overwritten with the output; for example =11 is not the same as =1 in most circumstances. In fact, I think only _: are valid. Fourth, is the winning answer one which performs all optimizations in a single program, or one which contains a separate program for each optimization? – Kamil Drakari Aug 18 '17 at 18:03 # Proper Kerning Kerning is the adjustment of spacing between pairs of letters in order to obtain an aesthetic result. When kerning is applied automatically by a program (typically whatever editor you're using), it is said to be automatic. There are two types of automatic kerning. The one used in this challenge is metric kerning. With metric kerning, the amount of space between pairs of letters is dictated by the kerning tables found in the font file. Given a TrueType font file, output the kerning values for each mapping in the kerning table for ASCII characters 48 - 122 inclusive. ## Example calibri.ttf l="A" r="C" v="-15" l="A" r="G" v="-15" l="A" r="J" v="23" l="A" r="O" v="-23" l="A" r="Q" v="-23" l="A" r="T" v="-160" l="A" r="U" v="-32" l="A" r="V" v="-89" l="A" r="W" v="-80" l="A" r="Y" v="-150" l="A" r="t" v="-52" l="A" r="v" v="-38" l="A" r="y" v="-41" l="A" r="?" v="-68" l="B" r="A" v="-20" l="B" r="T" v="-48" l="B" r="V" v="-25" l="B" r="W" v="-24" l="B" r="X" v="-44" l="B" r="Y" v="-57" l="B" r="Z" v="-20" l="B" r="f" v="-20" l="B" r="t" v="-20" l="B" r="v" v="-20" l="B" r="x" v="-15" l="B" r="y" v="-20" l="C" r="G" v="-18" l="C" r="J" v="12" l="C" r="O" v="-18" l="C" r="Q" v="-18" l="C" r="T" v="10" l="D" r="A" v="-30" l="D" r="J" v="-22" l="D" r="T" v="-23" l="D" r="V" v="-24" l="D" r="W" v="-14" l="D" r="X" v="-31" l="D" r="Y" v="-39" l="D" r="Z" v="-22" l="E" r="A" v="-22" l="E" r="C" v="-24" l="E" r="G" v="-24" l="E" r="O" v="-32" l="E" r="Q" v="-32" l="E" r="S" v="-20" l="E" r="Z" v="-10" l="E" r="a" v="-34" l="E" r="c" v="-28" l="E" r="d" v="-30" l="E" r="e" v="-37" l="E" r="f" v="-64" l="E" r="o" v="-37" l="E" r="q" v="-30" l="E" r="t" v="-24" l="E" r="v" v="-48" l="E" r="w" v="-34" l="E" r="y" v="-48" l="F" r="A" v="-115" l="F" r="C" v="-18" l="F" r="G" v="-18" l="F" r="J" v="-109" l="F" r="O" v="-18" l="F" r="Q" v="-18" l="F" r="S" v="-29" l="F" r="X" v="-22" l="F" r="Z" v="-11" l="F" r="a" v="-55" l="F" r="c" v="-28" l="F" r="d" v="-20" l="F" r="e" v="-30" l="F" r="o" v="-28" l="F" r="q" v="-20" l="F" r="s" v="-35" l="G" r="T" v="-10" l="G" r="V" v="-10" l="G" r="W" v="-9" l="G" r="Y" v="-30" l="G" r="v" v="-29" l="G" r="w" v="-22" l="G" r="x" v="-14" l="G" r="y" v="-30" l="J" r="A" v="-35" l="J" r="X" v="-20" l="K" r="C" v="-78" l="K" r="G" v="-80" l="K" r="O" v="-97" l="K" r="Q" v="-97" l="K" r="S" v="-18" l="K" r="U" v="-29" l="K" r="W" v="-34" l="K" r="a" v="-34" l="K" r="c" v="-40" l="K" r="d" v="-33" l="K" r="e" v="-37" l="K" r="f" v="-25" l="K" r="m" v="-32" l="K" r="n" v="-32" l="K" r="o" v="-37" l="K" r="p" v="-32" l="K" r="q" v="-33" l="K" r="r" v="-32" l="K" r="s" v="-18" l="K" r="t" v="-38" l="K" r="u" v="-32" l="K" r="v" v="-101" l="K" r="w" v="-95" l="K" r="y" v="-85" l="L" r="C" v="-22" l="L" r="G" v="-47" l="L" r="J" v="25" l="L" r="O" v="-45" l="L" r="Q" v="-45" l="L" r="T" v="-150" l="L" r="U" v="-44" l="L" r="V" v="-147" l="L" r="W" v="-118" l="L" r="Y" v="-167" l="L" r="f" v="-23" l="L" r="t" v="-38" l="L" r="v" v="-78" l="L" r="w" v="-72" l="L" r="y" v="-79" l="O" r="A" v="-23" l="O" r="J" v="-27" l="O" r="T" v="-55" l="O" r="V" v="-25" l="O" r="W" v="-22" l="O" r="X" v="-64" l="O" r="Y" v="-55" l="O" r="Z" v="-38" l="O" r="x" v="-12" l="O" r="z" v="-10" l="P" r="A" v="-151" l="P" r="J" v="-140" l="P" r="T" v="-9" l="P" r="V" v="-10" l="P" r="X" v="-35" l="P" r="Y" v="-11" l="P" r="Z" v="-29" l="P" r="a" v="-44" l="P" r="c" v="-43" l="P" r="d" v="-34" l="P" r="e" v="-41" l="P" r="f" v="12" l="P" r="o" v="-41" l="P" r="q" v="-34" l="P" r="s" v="-32" l="P" r="t" v="12" l="P" r="y" v="12" l="Q" r="J" v="41" l="Q" r="T" v="-47" l="Q" r="V" v="-25" l="Q" r="W" v="-12" l="Q" r="X" v="12" l="Q" r="Y" v="-46" l="Q" r="g" v="59" l="Q" r="j" v="79" l="Q" r="x" v="31" l="Q" r=";" v="60" l="Q" r="]" v="32" l="R" r="C" v="-18" l="R" r="G" v="-19" l="R" r="O" v="-20" l="R" r="Q" v="-20" l="R" r="S" v="-27" l="R" r="T" v="-20" l="R" r="V" v="-28" l="R" r="W" v="-18" l="R" r="Y" v="-30" l="R" r="e" v="-36" l="R" r="o" v="-42" l="R" r="v" v="-26" l="R" r="w" v="-33" l="R" r="y" v="-33" l="S" r="A" v="-15" l="S" r="J" v="-9" l="S" r="T" v="-14" l="S" r="V" v="-14" l="S" r="W" v="-15" l="S" r="X" v="-13" l="S" r="Y" v="-20" l="S" r="v" v="-23" l="S" r="w" v="-17" l="S" r="y" v="-25" l="T" r="A" v="-160" l="T" r="C" v="-42" l="T" r="G" v="-59" l="T" r="J" v="-65" l="T" r="O" v="-58" l="T" r="Q" v="-58" l="T" r="S" v="-10" l="T" r="T" v="28" l="T" r="a" v="-160" l="T" r="c" v="-177" l="T" r="d" v="-147" l="T" r="e" v="-182" l="T" r="g" v="-151" l="T" r="m" v="-127" l="T" r="n" v="-127" l="T" r="o" v="-182" l="T" r="p" v="-127" l="T" r="q" v="-147" l="T" r="r" v="-127" l="T" r="s" v="-153" l="T" r="u" v="-127" l="T" r="v" v="-92" l="T" r="w" v="-86" l="T" r="x" v="-90" l="T" r="y" v="-93" l="T" r="z" v="-142" l="T" r=";" v="-114" l="T" r=":" v="-134" l="U" r="A" v="-45" l="U" r="J" v="-40" l="V" r="A" v="-96" l="V" r="C" v="-18" l="V" r="G" v="-25" l="V" r="J" v="-80" l="V" r="O" v="-27" l="V" r="Q" v="-27" l="V" r="S" v="-12" l="V" r="V" v="9" l="V" r="a" v="-114" l="V" r="c" v="-103" l="V" r="d" v="-87" l="V" r="e" v="-102" l="V" r="g" v="-100" l="V" r="m" v="-50" l="V" r="n" v="-50" l="V" r="o" v="-86" l="V" r="p" v="-50" l="V" r="q" v="-87" l="V" r="r" v="-50" l="V" r="s" v="-90" l="V" r="u" v="-50" l="V" r="y" v="-35" l="V" r="z" v="-82" l="V" r=";" v="-108" l="V" r=":" v="-73" l="W" r="A" v="-93" l="W" r="C" v="-22" l="W" r="G" v="-22" l="W" r="J" v="-88" l="W" r="O" v="-22" l="W" r="Q" v="-22" l="W" r="S" v="-10" l="W" r="X" v="-13" l="W" r="a" v="-71" l="W" r="c" v="-78" l="W" r="d" v="-72" l="W" r="e" v="-75" l="W" r="g" v="-54" l="W" r="m" v="-60" l="W" r="n" v="-60" l="W" r="o" v="-86" l="W" r="p" v="-60" l="W" r="q" v="-72" l="W" r="r" v="-60" l="W" r="s" v="-73" l="W" r="u" v="-60" l="W" r="v" v="-34" l="W" r="y" v="-53" l="W" r=";" v="-156" l="X" r="C" v="-57" l="X" r="G" v="-65" l="X" r="O" v="-57" l="X" r="Q" v="-57" l="X" r="S" v="-20" l="X" r="d" v="-44" l="X" r="e" v="-39" l="X" r="g" v="-9" l="X" r="o" v="-38" l="X" r="q" v="-44" l="X" r="t" v="-31" l="X" r="u" v="-38" l="X" r="v" v="-55" l="X" r="w" v="-49" l="X" r="y" v="-43" l="Y" r="A" v="-152" l="Y" r="C" v="-67" l="Y" r="G" v="-67" l="Y" r="J" v="-112" l="Y" r="O" v="-66" l="Y" r="Q" v="-66" l="Y" r="S" v="-17" l="Y" r="Z" v="-10" l="Y" r="a" v="-134" l="Y" r="c" v="-159" l="Y" r="d" v="-131" l="Y" r="e" v="-147" l="Y" r="f" v="-62" l="Y" r="g" v="-142" l="Y" r="i" v="-32" l="Y" r="j" v="-49" l="Y" r="m" v="-94" l="Y" r="n" v="-94" l="Y" r="o" v="-153" l="Y" r="p" v="-94" l="Y" r="q" v="-131" l="Y" r="r" v="-94" l="Y" r="s" v="-115" l="Y" r="t" v="-44" l="Y" r="u" v="-94" l="Y" r="v" v="-69" l="Y" r="w" v="-62" l="Y" r="x" v="-70" l="Y" r="y" v="-65" l="Y" r="z" v="-100" l="Y" r=";" v="-138" l="Y" r=":" v="-154" l="Z" r="A" v="-11" l="Z" r="C" v="-25" l="Z" r="G" v="-24" l="Z" r="O" v="-24" l="Z" r="Q" v="-24" l="Z" r="W" v="-7" l="Z" r="Y" v="-7" l="Z" r="a" v="-10" l="Z" r="c" v="-12" l="Z" r="d" v="-18" l="Z" r="e" v="-31" l="Z" r="o" v="-29" l="Z" r="q" v="-18" l="Z" r="v" v="-45" l="Z" r="w" v="-38" l="Z" r="y" v="-37" l="a" r="f" v="-12" l="a" r="t" v="-19" l="a" r="v" v="-34" l="a" r="w" v="-14" l="a" r="x" v="-19" l="a" r="y" v="-38" l="b" r="f" v="-17" l="b" r="s" v="-10" l="b" r="t" v="-9" l="b" r="v" v="-10" l="b" r="w" v="-10" l="b" r="x" v="-41" l="b" r="y" v="-10" l="b" r="z" v="-28" l="c" r="a" v="-17" l="c" r="o" v="-17" l="e" r="f" v="-18" l="e" r="t" v="-11" l="e" r="v" v="-10" l="e" r="w" v="-10" l="e" r="x" v="-31" l="e" r="y" v="-13" l="e" r="z" v="-20" l="f" r="a" v="-40" l="f" r="c" v="-45" l="f" r="d" v="-53" l="f" r="e" v="-51" l="f" r="f" v="-20" l="f" r="g" v="-60" l="f" r="o" v="-43" l="f" r="q" v="-53" l="f" r="s" v="-27" l="f" r="v" v="13" l="f" r="w" v="6" l="f" r="y" v="10" l="f" r="z" v="-20" l="g" r="a" v="-38" l="g" r="c" v="-12" l="g" r="d" v="-19" l="g" r="e" v="-17" l="g" r="g" v="19" l="g" r="o" v="-14" l="g" r="q" v="-19" l="g" r="t" v="-31" l="h" r="f" v="-12" l="h" r="t" v="-19" l="h" r="v" v="-34" l="h" r="w" v="-14" l="h" r="x" v="-19" l="h" r="y" v="-38" l="k" r="a" v="-35" l="k" r="c" v="-48" l="k" r="d" v="-56" l="k" r="e" v="-66" l="k" r="o" v="-69" l="k" r="q" v="-56" l="k" r="s" v="-19" l="k" r="t" v="-10" l="k" r="u" v="-26" l="m" r="f" v="-12" l="m" r="t" v="-19" l="m" r="v" v="-34" l="m" r="w" v="-14" l="m" r="x" v="-19" l="m" r="y" v="-38" l="n" r="f" v="-12" l="n" r="t" v="-19" l="n" r="v" v="-34" l="n" r="w" v="-14" l="n" r="x" v="-19" l="n" r="y" v="-38" l="o" r="v" v="-9" l="o" r="w" v="-8" l="o" r="x" v="-40" l="o" r="y" v="-11" l="o" r="z" v="-27" l="p" r="f" v="-17" l="p" r="s" v="-10" l="p" r="t" v="-9" l="p" r="v" v="-10" l="p" r="w" v="-10" l="p" r="x" v="-41" l="p" r="y" v="-10" l="p" r="z" v="-28" l="q" r="g" v="10" l="r" r="a" v="-42" l="r" r="c" v="-30" l="r" r="d" v="-28" l="r" r="e" v="-27" l="r" r="g" v="-28" l="r" r="o" v="-33" l="r" r="q" v="-28" l="r" r="s" v="-35" l="r" r="v" v="19" l="r" r="w" v="11" l="r" r="y" v="10" l="s" r="f" v="-19" l="s" r="t" v="-23" l="s" r="v" v="-31" l="s" r="w" v="-10" l="s" r="x" v="-22" l="s" r="y" v="-37" l="s" r="z" v="-18" l="t" r="a" v="-25" l="t" r="c" v="-25" l="t" r="d" v="-23" l="t" r="e" v="-22" l="t" r="o" v="-20" l="t" r="q" v="-23" l="t" r="t" v="-29" l="v" r="a" v="-30" l="v" r="c" v="-25" l="v" r="d" v="-20" l="v" r="e" v="-20" l="v" r="f" v="11" l="v" r="g" v="-28" l="v" r="o" v="-19" l="v" r="q" v="-20" l="v" r="s" v="-9" l="v" r="t" v="10" l="v" r="v" v="12" l="v" r="w" v="12" l="v" r="y" v="12" l="v" r="z" v="-26" l="w" r="a" v="-23" l="w" r="c" v="-20" l="w" r="d" v="-18" l="w" r="e" v="-18" l="w" r="f" v="6" l="w" r="g" v="-18" l="w" r="o" v="-19" l="w" r="q" v="-18" l="w" r="s" v="-18" l="w" r="t" v="4" l="w" r="v" v="12" l="w" r="w" v="8" l="w" r="y" v="12" l="w" r="z" v="-17" l="x" r="a" v="-37" l="x" r="c" v="-46" l="x" r="d" v="-44" l="x" r="e" v="-54" l="x" r="o" v="-55" l="x" r="q" v="-44" l="x" r="s" v="-12" l="x" r="t" v="6" l="x" r="u" v="-20" l="y" r="a" v="-31" l="y" r="c" v="-26" l="y" r="d" v="-24" l="y" r="e" v="-25" l="y" r="f" v="10" l="y" r="g" v="-26" l="y" r="o" v="-24" l="y" r="q" v="-24" l="y" r="s" v="-19" l="y" r="t" v="10" l="y" r="v" v="12" l="y" r="w" v="8" l="y" r="y" v="10" l="y" r="z" v="-17" l="z" r="a" v="-34" l="z" r="c" v="-45" l="z" r="d" v="-46" l="z" r="e" v="-46" l="z" r="f" v="-10" l="z" r="g" v="-17" l="z" r="o" v="-45" l="z" r="q" v="-46" l="z" r="s" v="-22" l="z" r="u" v="-10" l="z" r="v" v="-18" l="z" r="w" v="-22" l="z" r="y" v="-18"  ## Scoring This is , so the shortest answer (in bytes) wins. ### Meta I know this challenge is going to need a lot of work before it's ready for main. Please hold criticisms for now. Helpful ideas and thoughts are welcome. • I'm not sure that the problem is well defined. There's a reason it's called font hinting: the rendering application is free to take it into account or not, or even to apply more complex logic. E.g. some fonts have multiple sets of font hints for different contexts. There are other complex issues. A font can have Latin and Cyrillic letters and define hints for kerning between pairs of Latin and pairs of Cyrillic but not between Latin and Cyrillic; however, some letters may have identical glyphs, so a judgement on whether the kerning is "correct" might be ambiguous. Then there's antialiasing. – Peter Taylor May 24 '17 at 6:15 • @PeterTaylor Good notes. I will likely restrict the character set. I just wanted to start getting ideas down in the sandbox. – Poke May 24 '17 at 6:51 • Very ambiguous. – dkudriavtsev May 25 '17 at 17:48 • @Mendeleev It's not done yet. I'm aware it's ambiguous. – Poke May 26 '17 at 16:10 • Looking at developer.apple.com/fonts/TrueType-Reference-Manual/RM06/… I can see a number of issues to address. 16- vs 32-bit entries? Should multiple tables be combined or printed separately? All tables or only tables with certain coverage values? Which of the four defined formats need to be supported? Do you have a test case which covers glyph index differing from codepoint? – Peter Taylor Sep 16 '17 at 17:28 • @PeterTaylor I have a proof of concept that I wrote (it's the reason I have taken so long to update this) and I'm planning to address all of your questions. Thanks for doing a bit of research to help me out, though :] – Poke Sep 16 '17 at 18:57 • Downvoter, why? – Poke Oct 4 '17 at 21:03 # Shift-left golfer Sometimes when doing code-golf, a person needs to understand which format is shorter: • 2147483648 • 0x80000000 • 1<<31 The task: You will receive a number in one of the three formats above: decimal, hexadecimal, or shift-left operation. If there is no advantage in converting it to another format, just leave the number the way it is; otherwise I want the shortest format. Of course there are numbers you can't convert to shift-left format! # Notation: • Hexadecimal0x#######.... where there are no leading zeros after the x. When accounting for evaluating the golfiness, the 0x part is also taken into consideration. For example 0x80000000 has a length of 10. • Decimal#######.... where there are no leading zeros. • Shift-left#...<<#.... no leading zeros both sides of <<. The << operator is also considered for length, e.g 1<<31 has a length of 5. You must also handle multiple digits before the << signal. # represents a digit and ... represent possible repetition of digits I don't care if you handle leading zeros at the input or not; but if you handle them, you must do the comparison operations without them and output also without them — You're a golfer, come on! You will understand! There will be no accepted answer. , so I want to know shortest answer by language. # UPDATE 1: In spite of @dzaima 's comment, now it also needs to handle multiple digits before << signal. • How about just take an integer as input and return the shortest form as output? – HyperNeutrino Sep 15 '17 at 19:20 • 1<<31 has a length of 4 not 5? – Rɪᴋᴇʀ Sep 15 '17 at 22:38 • @Riker: Sorry, my mistake. Now fixed. – sergiol Sep 15 '17 at 22:59 • @dzaima: Updated. Yes, it will need to handle multiple digits before << – sergiol Sep 16 '17 at 11:07 • If you allow non-ones in front of the byte shift as input, but not as output, an input like 99<<99 would result in the output having more bytes than the input. – Jonathan Frech Sep 18 '17 at 5:23 • What about something like 0x45<<0x378? i.e., why not hex numbers in left-shifts? – wastl Jul 7 '18 at 20:38 Six Flags over HTTP Let's say you need to transmit six boolean flags in a URL string. Obviously you could do it with six ones or zeroes, but you want better compression. With a little math you can pack them into two characters using 0-7 octal. How about mapping all six to a single ASCII character? Here we have a problem: you are not allowed to use , / ? : @ & = +$ # or space. Now the range of printable ASCII no longer has 64 valid characters in a row.

In Javascript (or another language that can run from a web page, if any), what is the shortest code for a pair of functions to encode and decode this data, between an array of six booleans and a single character?

• -1 language restriction, most languages have HTTP libraries so I think any language should be allowed – ASCII-only Sep 24 '17 at 13:11
• This challenge could be improved by rephrasing it to: "Write a bijective function between an array of six booleans and a single printable character excluding the characters ,/?:@&=+$# ". Mentioning that the encoder and decoder should be separate programs/functions would be helpful. Also, may the encoder and decoder share code? – fireflame241 Sep 24 '17 at 22:08 # Count letter frequency Inspired by question Tweetable hash function challenge, you should take the English dictionary used there and produce a program or function that outputs the the absolute and relative frequency of each character. It is CASE SENSITIVE and the APOSTROPHE is also accountable as a real letter. Example of a valid output format (but with stupid guessing values): A 5566 20% ... Z 60 0.2% a 27000 30% ... z 120 0.01% ' 450 3.5%  It is , but no answer will be accepted. Wanna know shortest script for each language. • -1 (01) Don't rely on another challenge to define yours; include all the information we need in your write-up. (02) Make an effort to come up with some actual test cases - do you honestly expect us to verify our solutions against "stupid guessing values"? – Shaggy Sep 30 '17 at 0:55 # Is it a perfect loop? test-batterydecision-problem Your task is to take a GIF or an animated image in any reasonable format as input (including taking the file name of a GIF in the current directory), and output whether it is a "perfect loop" - that is, the frames transition seamlessly from the end to the start, and a human cannot notice where it starts and ends at first glance. Return or print a truthy value if it is a perfect loop, otherwise print or return a falsy value. ## Scoring Winners will be determined from the percentage of test cases they get correct. In the event of a tie, highest votes wins. You can view test cases at https://ghostbin.com/paste/m3yaw. Show your score against the test cases when you post. ## Input If you are not taking input in a GIF, please provide a program that will convert a GIF to your desired format. Images corresponding to a truthy value have been taken from /r/perfectloops and for falsy test cases, /r/almostperfectloops and /r/gifs. ## Restrictions • Hard coding is not allowed (violates standard loophole 1 and 2). • You must provide consistent results for the same GIF (no randomness) • Remember, this is not , so byte count is not needed in your solution. Just post the language name and add the percentage correct when I comment. • I'm not sure it's as simple as comparing the first to the last frame, if it is we'd have duplicate frames. is this challenge allowing HTTP requests? – tuskiomi Oct 17 '17 at 21:15 • If hashing the inputs is not allowed, then you should clearly define what constitutes a “perfect loop”. It's not good to extrapolate from a handful of test cases where the pass/fail cases are very similar. – japh Oct 18 '17 at 14:31 # Removing a Letter adds a Letter Your program should output nothing when unaltered, however, when any single character is removed it should have an output length of 1. This extends to any number of characters being removed from the program, as long as there is, at minimum, a single character remaining. For example, if my program were abcdefg, it should output nothing if unaltered. However, if I were to remove a and d from this program to get bcefg, it should output any two printable characters that represent 16 bytes of information (2 characters for 2 characters removed). • So if bcefg outputs (00,AA,etc...) this is valid. Taking this further, if we were to remove all but the letter g we'd need an output of 6 characters. • So if g outputs ('000000','@$^%@(',etc...) this is valid.

Your program must function for all possible combinations of removals that are possible, that is to say each single letter in your program should be a valid program.

# Rules

• You may "lock" pieces of the code, each locked byte counts for 2-bytes instead of 1-byte.
• Locked bytes will never be removed.
• For instance, if my program was abcdefg and bcd is locked, the shortest program we'll get is abcd,bcde,bcdf and bcdg.
• If bcd was locked in abcdefg it'd be 10 bytes, not 7.
• The program may output any byte to represent 1 removed character, N-bytes for N removed chars in the code itself.
• The rule only leads to totally locked code – l4m2 Mar 13 '18 at 0:13
• @l4m2 hah. I disagree. – Magic Octopus Urn Mar 13 '18 at 0:58
• But more constructively, increase the penalty? Limit locked chars? – Magic Octopus Urn Mar 13 '18 at 1:04
• Maybe require an unlocked percent? – l4m2 Apr 6 '18 at 10:52

# Non-true, non-false JS boolean

Array prototype isn't redefined, input hasn't getters

function magic(input){
let result = [];
if(input.boolean != true){result.push("non-true");}
if(input.boolean != false){result.push("non-false");}
result.push(input);
return result.join("\n");
}


returns

non-true
non-false
{"boolean": true}


What is passed to magic function?

Based on real problem :) I spent 30 minutes on this puzzle

• This site is for programming contests, not pure programming puzzles. Thanks for using the sandbox, anyway. – user202729 Feb 1 '18 at 12:11
• Contrary to what user202729 states, Programming Puzzles are on-topic on this site. This challenge could use a little cleanup to make it a better fit here (for example, what language is this?), but this challenge is indeed allowed here. – AdmBorkBork Feb 1 '18 at 14:02
• ... someone said that I'm wrong. Anyway people definitely doesn't like this. – user202729 Feb 1 '18 at 14:02
• @AdmBorkBork this is JS – Евгений Новиков Feb 1 '18 at 14:41
• @ЕвгенийНовиков what JS version is this? in is a keyword, and can't be a variable name. – dzaima Feb 1 '18 at 14:47
• @dzaima Good point. Last time I check on TIO the object {boolean: true} doesn't have " around and it caused a syntax error. I forgot about in so just try to rename it and it worked... – user202729 Feb 1 '18 at 14:51
• "Programming Puzzle" is in the name of the site @user202729 – dylnan Feb 1 '18 at 15:46
• @dylnan But... – user202729 Feb 1 '18 at 15:55
• @AdmBorkBork is correct. We do allow programming puzzles. – Nathan Merrill Feb 1 '18 at 16:25
• @NathanMerrill Then just upvote the comment. – user202729 Feb 2 '18 at 5:34
• Many many things in the past, including but not limited to, code-trolling, underhanded, non-observable behavior, etc. are off-topic or heavily-discouraged nowadays. Be careful. – user202729 Feb 2 '18 at 5:34
• @user202729 I did upvote. I just wanted to make sure it was extra clear to the OP. Furthermore, this challenge doesn't fit any of those tags, because its not asking for trolling/underhanded/non-observable code. You could argue that the code in the challenge fits those tags, but that's not what we care about. – Nathan Merrill Feb 2 '18 at 5:51
• I don't believe that console is part of any JS spec. This presumably only works in certain contexts, and the question should specify what they are. Otherwise the task devolves into code-trolling by defining a suitable console. It's already borderline IMO. – Peter Taylor Feb 2 '18 at 12:04
• @dzaima sorry, fixed this. Now input variable is input – Евгений Новиков Feb 3 '18 at 7:40
• OK, so, in that case you may want to work on the wording of the challenge before posting it to Main because, right now, it reads as though you've come across this challenge elsewhere, spent half an hour trying to solve and are now looking for help doing so. Also, just so you know, restricted language challenges rarely go down well here. – Shaggy Feb 3 '18 at 19:20

Sandbox:

Is this question already available (duplicate)?

Are things too vague?

Does providing the example help or hinder?

# Tidy the Pantry (easy)

I hate grocery shopping, particularly the part where I put groceries away--so I'm calling upon the collective hive-mind to handle that.

## Challenge

Your challenge is to take a 1D-list of groceries and a 2D pantry as input; and output an newly assorted pantry. The two variables can be of your type choice, and in any order, but please specify what item types your program requires (e.g. string, array, etc.).

### Scoring

• This is code golf, so the shortest answer in bytes wins

### Rules

• The pantry should be ordered alphabetically (A - Z, left to right, top to bottom)
• For simplicity, the pantry is case-insensitive
• The pantry must retain its horizontal size (but trailing newlines are optional)
• "Pockets" (empty spaces) should be filled between items (i.e. only the last item is allowed to have a trailing pocket)
• If the pantry is too small for the incoming groceries, then the pantry must replace older items (Z being the oldest, A the youngest)
• Z from groceries is younger than A in pantry
• Standard loopholes are forbidden

## Examples ([ and ] are used for readability)

Input (4x4 pantry):

[A][A][ ][ ]
[ ][ ][B][ ]
[C][ ][ ][ ]
[ ][ ][ ][D]



Output:

[A][A][A][A]
[B][C][D][D]
[ ][ ][ ][ ]
[ ][ ][ ][ ]


Input (2x2 pantry):

[A][B]
[C][D]

XYZ


Output:

[A][X]
[Y][Z]


# JavaScript ES6 (989 bytes)

// (String, String) -> String
let organise = (pantry, groceries) => {
let n = pantry.split("\n").sort((a, b) => b.length - a.length); // used at the end of the function for horizontal sizing
n = n[0].length;

pantry = pantry
.replace(/\W/g, "") // get rid of all non-alphanumeric characters
.split("");         // turn the string into an array

// we need the properties of the new array
// so the extra pantry = pantry is needed
pantry = pantry
.slice(0, pantry.length - groceries.length) // go ahead and remove the last overlapping elements
.concat(groceries)                          // add the groceries to the pantry
.join("")                                   // turn into a string
.split("")                                  // turn into an array
.sort()                                     // sort the array
.join("");                                  // turn into a string

return pantry.replace(RegExp((.{${n}}), 'g'), "$1\n");
};

/** Testing below **/

console.log("Test #2:\n" + organise(
AJCHDJE
JJ   JA
ASD
OOQ I U
Q     W
R,

'AHJBCJHDHHATTGEH'
))

## Test Cases:

### Test #1, 4x4 pantry

TVCX <- pantry
ABCD
ATDJ
UAIK

XYXY <- groceries
----
AAAB <- expected output
CCDD
IJKT
XYXY


### Test #2, 7x6 pantry

AJCHDJE
JJ   JA
ASD
OOQ I U
Q     W
R

AHJBCJHDHHATTGEH
-------
AAAAABC
CDDDEGH
HHHHJJT
T


### Test #3, 10x10 pantry

AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA

ZZZZZZZZZZZZZZZZZZZZ
----------
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
ZZZZZZZZZZ
ZZZZZZZZZZ


# Test #4, 16x16 pantry pantry

ASDFGHJKLZXCVBNM
QJKAJ  KAKSJD  J
KJASDKFHI YOIER
W   OSDOFJ    DK
E PPPASP     AS
R
TASD
YAAAAAAAAAAAA
U          JHOLK
IIAUSHODUYOAISUO
OASD  AUSODI
PIASND JUASJNOIJ
A ASJDH PPOIO
QHIAIUSOIUOOO
WYYAIUSNNAJSDASD
EAISDUUIOPJPIJPJ
ROQPEWIHRNXCAISD

QWERTYUIOP
----------------
AAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAA
ABCCDDDDDDDDDDDD
DDDEEEEEFFFGHHHH
HHHIIIIIIIIIIIII
IIIIIIJJJJJJJJJJ
JJJJJJKKKKKKKKLL
MNNNNNNOOOOOOOOO
OOOOOOOOOOPPPPPP
PPPPPPQQQQRRRRRS
SSSSSSSSSSSSSSSS
SSSTTUUUUUUUUUUU
UVWWY


# Test #5, 2x2 pantry

HE
LO

[no groceries]
--
HE
LO

• why divide the program score? – RedClover Feb 26 '18 at 19:03
• I recommend you do count by bytes otherwise someone is just going to encode their entire program in Chinese characters and win. – HyperNeutrino Feb 26 '18 at 19:09
• @labela--gotoa To get a golfed score (smaller programs get a smaller score), should I change it? – Ephellon Dantzler Feb 26 '18 at 19:13
• @EphellonDantzler I don't understand why not just normal scoring...? – RedClover Feb 26 '18 at 19:14
• LOL, that's why I set in in Sandbox first @labela--gotoa – Ephellon Dantzler Feb 26 '18 at 19:16
• Some notes on your reference implementation: 1 It appears far too soon in the challenge. 2 It's not 1768 bytes. 3 You need to ungolf it and make it readable or it's not much use. 4 As it's JS, create a Snippet for it. 5 Is it necessary? It seems to be thrown in there to try to patch over any holes in the challenge spec. – Shaggy Feb 26 '18 at 23:17