title: "As we travel the universe..."

text:
# Question
Title: "As we travel the universe..."
You'll be given the name of one of the 20 biggest objects in the Solar System. Your task is to return an approximation of its radius, expressed in kilometers.

This is a where your score consists of the length of your code (in bytes) multiplied by a penalty ratio \\$\ge 1\\$, based on your worst approximation. Therefore, **the lowest score wins**.

*"As we travel the universe" is the last line of the song Planet Caravan by Black Sabbath, also later covered by Pantera.*

## The Solar System objects

Source: Wikipedia

NB: The rank is given for information only. The input is the **name** of the object.

```
  n | Object   | Radius (km)
----+----------+-------------
  1 | Sun      |   696342
  2 | Jupiter  |    69911
  3 | Saturn   |    58232
  4 | Uranus   |    25362
  5 | Neptune  |    24622
  6 | Earth    |     6371
  7 | Venus    |     6052
  8 | Mars     |     3390
  9 | Ganymede |     2634
 10 | Titan    |     2575
 11 | Mercury  |     2440
 12 | Callisto |     2410
 13 | Io       |     1822
 14 | Moon     |     1737
 15 | Europa   |     1561
 16 | Triton   |     1353
 17 | Pluto    |     1186
 18 | Eris     |     1163
 19 | Haumea   |      816
 20 | Titania  |      788

```

Or as copy-paste friendly lists:

```
'Sun', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Earth', 'Venus', 'Mars', 'Ganymede', 'Titan', 'Mercury', 'Callisto', 'Io', 'Moon', 'Europa', 'Triton', 'Pluto', 'Eris', 'Haumea', 'Titania'
696342, 69911, 58232, 25362, 24622, 6371, 6052, 3390, 2634, 2575, 2440, 2410, 1822, 1737, 1561, 1353, 1186, 1163, 816, 788

```

## Your score

Let \\$R\_n\\$ be the expected radius of the \\$n^{th}\\$ object and let \\$A\_n\\$ be the answer of your program for this object.

Then your score is defined as:

$$S=\left\lceil L\times\max\_{1\le i \le20}\left({\max\left(\frac{A\_i}{R\_i},\frac{R\_i}{A\_i}\right)^2}\right)\right\rceil$$

where \\$L\\$ is the length of your code in bytes.

*Example:*

If the size of your code is \\$100\\$ bytes and your worst approximation is on the Moon with an estimated radius of \\$1000\\$ km instead of \\$1737\\$ km, then your score would be:

$$S=\left\lceil 100\times{\left(\frac{1737}{1000}\right)^2}\right\rceil=302$$

The lower, the better.

Recommended header for your answer:

```
Language, 100 bytes, score = 302

```

You can use this script to compute your score (first line = code length, next 20 lines = your outputs, from Sun to Titania).

## Rules

* You may take the name of the object in either full lowercase, full uppercase or exactly as described above (title case). Other mixed cases are not allowed.
* The input is guaranteed to be one of the 20 possible names.
* You may return either integers or floats. In both cases, the penalty must be computed directly with these values (not rounded values in case of floats).
* You must return positive values.
* Empty programs are not allowed.

# Answer
# PowerShell, 3 bytes, score 3637

```
2e4

```

Try it online!

Very naive, boring, implementation; just returns `20000` no matter the input. Experimentation with things like special-casing the sun or using floating-point values instead of `2` all resulted in worse scores because the length of code increased enough to offset any size-comparison gains.
> 29 votes

# Answer
# Jelly, 34 bytes, score = 37

```
OḌ“⁸|5/!‘%ƒị“RNFLOJMjs⁽\u[USJ‘1.1*

```

Input is in uppercase, output is the power of 1.1 with the least error.

Try it online!

### How it works

```
OḌ“⁸|5/!‘%ƒị“RNFLOJMjs⁽\u[USJ‘1.1*  Main link. Argument: s (string)

O                                   Ordinal; map the char in s to their code points.
                                        "ERIS" -> [69,82,73,83]
 Ḍ                                  Undecimal; treat the result as an array of digits
                                    in base 10 and convert it to integer.
                                        [69,82,73,83] -> 69000+8200+730+83 = 78013
  “⁸|5/!‘                           Literal; yield [136, 124, 53, 47, 33].
         %ƒ                         Fold the array by modulus, using the computed
                                    integer as initial value.
                                        78013 -> 78013%136%124%53%47%33 = 32
            “RNFLOJMjs⁽\u[USJ‘      Literal; yield [82, 78, 70, 76, 79, 74, 77, ...
                                    106, 115, 141, 92, 117, 91, 85, 83, 74].
           ị                        Retrieve the element from the array to the right,
                                    at the index to the left.
                                    Indexing is 1-based and modular.
                                        32 = 16 (mod 16) -> 'J' = 74
                              1.1*  Raise 1.1 to the computed power.
                                        74 = 1.1**74 = 1156.268519450066

```
> 25 votes

# Answer
# Java (JDK), 90 bytes, score = 97

```
s->("ýCĄ (ᬺ!˂Fɍ".charAt(s.substring(2).chars().sum()%96%49%25)-7)*100

```

Try it online!

* This entry uses both undisplayable and multi-byte Unicode characters (but Java accepts them nevertheless). Check the TIO for the accurate code.
* The input must be title-case.
* This code rounds the values to the best multiple-of-100 (sometimes up, sometimes down) so that the last two digits can be skipped when encoded, and the value can then be approximated by multiplying by 100.
* This entry uses various hashes to fit a 25 codepoints string (shortest string I could find).

## Credits

* -48 score (-45 bytes) thanks to Kevin Cruijssen by encoding the radiuses (divided by 100) directly in a `String` instead of hardcoding them in an explicit `int` array..
> 20 votes

# Answer
# Wolfram Language ~~114 103 97 88 86~~ 82 bytes. score = ~~114 103 97 89 87~~ 83 points

```
(#&@@EntityValue[Interpreter["AstronomicalObject"]@#,"Radius"]/._String->507)1.61&

```

At least 6 points saved thanks to `Dennis`, several more thanks to `lirtosiast`, and 6 more thanks to `user202729`.

Although Mathematica can fetch solar system data (as well as much additional astronomical data), some minor tweaks are needed, as explained below.

`Interpreter[#,"AstronomicalObject"]&` will return the entity (i.e. the machine computable object) associated with the term represented by `#`.

`EntityValue[AstronomicalObject[],"Radius"]` returns the radius, in miles, of the entity. In the case of "Haumea", the value, 816.27 (i.e. 507\*1.61), is returned.

Multiplication of the radius by `1.61` converts from miles to km. Decimal values, rather than integers, account for much less than 1% error, even in the most extreme case.

`[[1]]` returns the magnitude without the unit, km. This was later changed to `#&@@`, yielding the same result.
> 9 votes

# Answer
# Python 3, score 95, 95 bytes

```
lambda n:ord("ؙҢਏാᣣ४ঈ挒ឤ?̰ҋ??ۉՉ怮ܞ੊̔"[int(n,35)%87%52%24-1])

```

Try it online!

---

# Python 3, score 133, 133 bytes

```
lambda n:int(f'00e0{10**18+10**6}10x1h2411j4?00??811i1207wazxmwuvko?mw??xc1ze1ldyujz6zysi4?ob??k9lym6w'[int(n,35)%87%52%24-1::23],36)

```

Try it online!
> 7 votes

# Answer
# Powershell, ~~150~~ 141 bytes, score ~~163~~ 153

```
($args|% t*y|?{'Su6963J699S582U253N246Ea63V60Ma33G26Ti25Me24C24I18M17Eu15T13P12E12H8Titani8'-cmatch"$(($y+=$_))(\d+)"}|%{100*$Matches.1})[-1]

```

Try it online!

Test script:

```
$f = {
($args|% t*y|?{'Su6963J699S582U253N246Ea63V60Ma33G26Ti25Me24C24I18M17Eu15T13P12E12H8Titani8'-cmatch"$(($y+=$_))(\d+)"}|%{100*$Matches.1})[-1]
}

$penalty = @(
    ,("Sun"      , 696342)
    ,("Jupiter"  ,  69911)
    ,("Saturn"   ,  58232)
    ,("Uranus"   ,  25362)
    ,("Neptune"  ,  24622)
    ,("Earth"    ,   6371)
    ,("Venus"    ,   6052)
    ,("Mars"     ,   3390)
    ,("Ganymede" ,   2634)
    ,("Titan"    ,   2575)
    ,("Mercury"  ,   2440)
    ,("Callisto" ,   2410)
    ,("Io"       ,   1822)
    ,("Moon"     ,   1737)
    ,("Europa"   ,   1561)
    ,("Triton"   ,   1353)
    ,("Pluto"    ,   1186)
    ,("Eris"     ,   1163)
    ,("Haumea"   ,    816)
    ,("Titania"  ,    788)
) | % {
    $s,$expected = $_
    $result = &$f $s
    $ratio = [Math]::Max($result/$expected, $expected/$result)
    $ratio*$ratio
}
$scriptLength = $f.ToString().Length - 2  # -4 if CRLF mode
$penaltyMax = ($penalty|Measure-Object -Maximum).Maximum
$score = $scriptLength * $penaltyMax
"$score = $scriptLength * $penaltyMax"

```

Output:

```
152.731283431953 = 141 * 1.08320059171598

```

Explanation:

* Names contain letters only, radiuses contain digits and dots. So we can write all the data in a data string and perform a regexp search.
* The script searches for all substrings from left to right and takes the last result found.
* The input must be title-case to reduce the data string.
* The `end of line mode` is LF only.

Example:

```
Titania         Triton         Titan
--------------  -------------  -------------
T       -> 1.3  T      -> 1.3  T      -> 1.3
Ti      -> 2.5  Tr     ->      Ti     -> 2.5
Tit     ->      Tri    ->      Tit    ->
Tita    ->      Trit   ->      Tita   ->
Titan   ->      Triton ->      Titan  ->
Titani  -> .8
Titania ->

Result is .8    Result is 1.3  Result is 2.5

```

---

# Powershell, 178 bytes, score 178

```
($args|% t*y|?{'Su696342J69911S58232U25362N24622Ea6371V6052Ma3390G2634Ti2575Me2440C2410I1822M1737Eu1561T1353P1186E1163H816Titani788'-cmatch"$(($y+=$_))(\d+)"}|%{+$Matches.1})[-1]

```
> 7 votes

# Answer
# 05AB1E, score ~~100~~ ~~66~~ ~~60~~ 56 (~~100~~ ~~61~~ ~~56~~ 52 bytes)

```
•1∞²îc|I‰∍T‡sÇ3¡ò½в…»Ë••1ë£ñƒq£û¿’…•S£I¦¦ÇO96%49%èт*

```

Port of *@OlivierGrégoire*'s Java answer, so if you like this first answer, make sure to upvote him as well!
Input in titlecase.

Verify all test cases.

---

# 05AB1E, score ~~100~~ 99 (~~100~~ 99 bytes)

```
•*Òâ%ÌÜS…Ùb‹Úi{e!]É¸·vÌBUSηHã£āðxyµŠ••3«8¹ØмS7Ç•S£.•WùηƵ@,Sº,ûεβʒóÃX\¹Θäáá’Ý)”Ωož∞-z.A±D•3ôI2£Iθ«kè

```

Input in full lowercase. Outputs the exact radius, so no penalty is added.

Verify all test cases.

**Explanation:**

```
•*Òâ%ÌÜS…Ùb‹Úi{e!]É¸·vÌBUSηHã£āðxyµŠ•
                 # Compressed integer 696342699115823225362246226371605233902634257524402410182217371561135311861163816788
 •3«8¹ØмS7Ç•     # Compressed integer 65555444444444444433
  S              # Converted to a list of digits: [6,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,3,3]
   £             # The first integer is split into parts of that size: ["696342","69911","58232","25362","24622","6371","6052","3390","2634","2575","2440","2410","1822","1737","1561","1353","1186","1163","816","788"]
    .•WùηƵ@,Sº,ûεβʒóÃX\¹Θäáá’Ý)”Ωož∞-z.A±D•
                 # Compressed string "sunjursanursneeeahvesmasgaetinmeycaoioomoneuatrnploershaatia"
     3ô          # Split into parts of size 3: ["sun","jur","san","urs","nee","eah","ves","mas","gae","tin","mey","cao","ioo","mon","eua","trn","plo","ers","haa","tia"]
       I2£       # The first two characters of the input
          Iθ     # The last character of the input
            «    # Merged together
             k   # Get the index of this string in the list of strings
              è  # And use that index to index into the list of integers
                 # (and output the result implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress strings not part of the dictionary?*) to understand how the compression used works.
> 4 votes

# Answer
# Mathematica, 57 bytes, score = ~~62~~ 58

*-4 bytes/score thanks to lirtosiast!*

```
#&@@WolframAlpha[#<>" size km","Result"]]/._Missing->816&

```

Just does a Wolfram Alpha lookup for the mean radius.
> 4 votes

# Answer
# Jelly, 28 bytes, score = 31

```
“__ʋ7ṗ“RUu⁽NM\sOSJj[FL‘ḥ1.1*

```

This uses a configurable hashing built-in that I added to Jelly at @lirtosiast's suggestion.

Input is in titlecase, output is the power of 1.1 with the least error.

Try it online!

### How it works

This answer consists of merely two parts.

* First, `“__ʋ7ṗ“RUu⁽NM\sOSJj[FL‘ḥ` uses the new built-in to map each of the 20 possible inputs to 15 different integers.
* Then, `1.1*` elevates 1.1 to the computed power.

`“__ʋ7ṗ“RUu⁽NM\sOSJj[FL‘` is a literal; every non-quote character is replaced by it's 0-based index in Jelly's code page, yielding \\$\[95, 95, 169, 55, 242\], \[82, 85, 117, 141, 78, 77, 92, 115, 79, 83, 74, 106, 91, 70, 76\]\\$.

The hashing built-in  first maps \\$\[95, 95, 169, 55, 242\]\\$ to an integer by incrementing each number, then treating the result as the bijective base-250 digits integer and adding \\$1\\$. This yields \\$376510639244\\$.

By halving and flooring this integer until the result is \\$0\\$, we get the sequence \\$\[376510639244, 188255319622, 94127659811, 47063829905, \dots, 5, 2, 1, 0\]\\$, which has the forward differences \\$\[188255319622, 94127659811, 47063829906, \dots, 3, 1, 1\]\\$.

Next, we generate 64 64-bit integers by applying SHAKE256-4096 to the string representation of the internal representation of 's right argument, then chopping the resulting 4096 bits into 64 64-bit chunks.

now computes the dot product of the 39 differences and the first 39 generated 64-bit integers, modulo \\$2^{64}\\$. This yields an integer in \\$\[0, 2^{64})\\$.

The list \\$\[82, 85, 117, 141, 78, 77, 92, 115, 79, 83, 74, 106, 91, 70, 76\]\\$ has length 15, so we multiply the generated integer by 15 and take the 64 higher bits of the result. This yields an integer in \\$\[0, 15)\\$, which we use to index into the list.

To find the appropriate hash configuration, I've used a brute-forcer in C that is part of the Jelly repo.
> 4 votes

# Answer
# Python 2, 155 bytes, score = 155

```
lambda p:int('G11KK54222111111XXNM8MCO37WQ53YXHE93V8BIF2IMH1WU9KPU2MLN    HGR'['uSJJaSrUNNrEnVsMeGtTMMoCoInMuErTuPsEaHTT'.find(p[7%len(p)]+p[0])/2::20],35)

```

Try it online!

Surprisingly well for this lazy solution... will look into improving as well. ;-)
> 3 votes

# Answer
# Japt, 86 bytes, score = 94

```
g5 ¥'i?788:[7*A³7*L6*LG²G²IIÉHÄDÑDÑCÑCÑGÄÄGÄGECC8]g`suj«a¨Ì¼và@ã/eÖô¶e©rp¤r`bU¯2)z)*L

```

Try it for all inputs, Calculate the score, or Check the highest error

Very similar to Olivier's original answer. Input is all lowercase.

After various improvements to the output values, the current highest error is Venus at just over 4%.

Explanation now that things are a bit more stable:

```
¤¥`Éa`?                             :If the fifth character of the input is 'i':
       788                          : Output 788.
          :                         :Otherwise:
           [...]                    : From the array representing radii
                g                   : Get the value at the index:
                 `...`              :  In the string representing names
                      b             :  Find the first index where this string appears:
                       U¯2)         :   The first two characters of the input
                           z)       :  And divide it by two
                             *L     : Multiply that value by 100

```

The string for the names is `sujusaurneeavemagatimecaiomoeutrplerha` compressed using Japt's built-in compression. The numbers representing the radii are calculated like so:

```
                          My value | Actual value
                          ---------+-------------
7 * 10 ^ 3 = 7000 * 100 =   700000 | 696342
7 * 100    = 700  * 100 =    70000 |  69911
6 * 100    = 600  * 100 =    60000 |  58232
16 * 16    = 256  * 100 =    25600 |  25362
16 * 16    = 256  * 100 =    25600 |  24622
64         = 64   * 100 =     6400 |   6371
64 - 1     = 63   * 100 =     6300 |   6052
32 + 1     = 33   * 100 =     3300 |   3390
13 * 2     = 26   * 100 =     2600 |   2634
13 * 2     = 26   * 100 =     2600 |   2575
12 * 2     = 24   * 100 =     2400 |   2440
12 * 2     = 24   * 100 =     2400 |   2410
16 + 1 + 1 = 18   * 100 =     1800 |   1822
16 + 1     = 17   * 100 =     1700 |   1737
16         = 16   * 100 =     1600 |   1561
14         = 14   * 100 =     1400 |   1353
12         = 12   * 100 =     1200 |   1186
12         = 12   * 100 =     1200 |   1163
8          = 8    * 100 =      800 |    816
788                     =      788 |    788

```
> 3 votes

# Answer
# Japt, ~~77~~ ~~76~~ 75 bytes, score = 75

First pass at this; I wanted to try a 0 penalty solution to give myself a baseline to work off. Will come back to it tomorrow to see what improvements can be made, hopefully still for 0 penalty.

Input is case-insensitive.

```
n35 %87%52 g"..."ò)mc

```

Try it or test all inputs

The `"..."` represents a string containing many unprintables. The codepoints are:

```
32,32,15,61,11,86,696,342,25,75,699,11,33,90,63,71,24,10,24,40,253,62,60,52,32,32,8,16,11,63,32,32,32,32,58,232,17,37,135,3,246,22,18,22,26,34,7,88

```

To offer a quick explanation: the string gets split into chunks of 2 characters. We then index into that array using part of ovs' formula plus some index-wrapping and then map the 2 characters to their codepoints.

* Saved a byte/point thanks to ETH

## 54 bytes, score = 58

A port of Olivier's solution.

```
"ýCĄ (ᬺ!˂Fɍ"cU¤¬xc %96%49)-7 *L

```

Test all inputs
> 3 votes

# Answer
# T-SQL, ~~203 202 201~~ 196 bytes, score = ~~217 216 212~~ *208*

```
SELECT IIF(v='Titan',13,STUFF(value,1,2,''))*198
FROM i,STRING_SPLIT('Ca12,Ea32,Er6,Eu8,Ga13,Ha4,Io9,Ju353,Ma17,Me12,Mo9,Ne124,Pl6,Sa294,Su3517,Ti4,Tr7,Ur128,Ve31',',')
WHERE LEFT(v,2)=LEFT(value,2)

```

Line breaks are for readability only.

Input is taken via pre-existing table **i** with varchar column **v**, per our IO standards.

Joins the input table to an in-memory table on the first two characters, and returns the remaining digits x100.

Treats "Titan" as a special case using `IIF`.

**EDIT**: Saved 1 byte (and 1 point) by using `STUFF` to erase the first two characters instead of `SUBSTRING`. Thanks, t-clausen.dk!

**EDIT 2**: I wanted to see what would happen if I tried to save another byte by multiplying each lookup value by 99 instead of 100, and found to my surprise that it actually *increased* the accuracy (of the least accurate estimate)!.

This led me to some trial and error testing, and some fancy Excel what-if data tables, where I found an optimal solution using a multiplier of **89** (which of course changed all my stored values).

So while this saves me only one byte, it actually improves my score by **4.6** from my prior solution.

**EDIT 3**: Searched higher instead of lower, and found an even *better* multiplication factor, **198**. Values stay reasonably accurate while shortening my stored string by quite a few characters, which improves my score.
> 3 votes

# Answer
# Ruby, 105 bytes, score 109

```
->n{7E5/('!)"0 r&zZ&1#}3Mfh-~~d@'[0,j=" =1&%)AM<I>2,-B#($D  7@".index((n[1,9].sum%50+34).chr)].sum-j*32)}

```

Try it online!

If we divide 700000 by the radii, we get a sequence which increases reasonably linearly (though rather erratically). The increments in the table below can be approximated by the ASCII values of characters. The problem with this approach is it requires the input to be decoded to a value which orders the different names by size.

A minor issue is that the difference between Eris and Haumea is quite large. Three characters `~~d` are required to encode this increment in ASCII only format. The planet-to-index string has two "ghost planet"spaces in it to pad the index.

```
700000/r    increment from previous
0.994774
9.960407    8.965633
11.95806    1.997657
27.45612    15.49805
28.28129    0.825178
109.2987    81.0174
115.0598    5.761118
205.4106    90.3508
264.3667    58.95612
270.4241    6.057335
285.3861    14.96199
288.9386    3.552524
382.1855    93.24692
400.8877    18.70223
446.0871    45.19939
514.6652    68.57806
587.1349    72.46972
598.7463    11.61144
853.3603    254.6139
883.6827    30.32245

```
> 3 votes

# Answer
# PowerShell, 203 bytes, score 203

```
param($a)if($a-eq'Titan'){2575;exit}(696342,69911,58232,25362,24622,6371,6052,3390,2634,2440,2410,1822,1737,1561,1353,1186,1163,816,788)["SuJuSaUrNeEaVeMaGaMeCaIoMoEuTrPlErHaTi".indexOf(-join$a[0..1])/2]

```

Try it online!

Very similar to Olivier's answer, now that I see it, but developed independently.
> 2 votes

# Answer
# Charcoal, 101 bytes, score = 101

```
Ｉ⍘§⪪“_″FJ⁼⦄b\l≕)Ｔ‹#⊙xO-nη⁻À↓ζ↥ς§%Ｈ8H“ρj✳Hρl× S↶…|ＵＤ⎇ＬkfZ”³⌕⪪”@/rjmq_↙§Ｅ▶νＦ↨oº⁷÷Ｋ⁻eDH:_Tbk¦�”²⁺§θ⁰§θχγ

```

Try it online! Link is to verbose version of code. Explanation:

```
⁺§θ⁰§θχ

```

Take the 1st and 11th character (cyclically) of the input string and concatenate them.

```
⌕⪪”@/rjmq_↙§Ｅ▶νＦ↨oº⁷÷Ｋ⁻eDH:_Tbk¦�”²

```

Look them up in the string `SuJiSrUuNtEEVVMrGnTTMcClIIMoEpToPPEiHeTa` split into pairs of characters.

```
§⪪“_″FJ⁼⦄b\l≕)Ｔ‹#⊙xO-nη⁻À↓ζ↥ς§%Ｈ8H“ρj✳Hρl× S↶…|ＵＤ⎇ＬkfZ”³

```

Split the string `m.w'fv&J|\"l|\"e1 c& _c Ca ;e ;* 9a 9C 31 2; 0I .7 ,N ,7 (X (<` into groups of three characters and take the corresponding group.

```
Ｉ⍘ ... γ

```

Decode the result as a base-95 number using the printable ASCII character set as the digits. Example: `Io`'s 11th character is `I`, so we look up `II` and find it's the 13th largest object and its size is `31` which maps to `19 * 95 + 17 = 1822`.
> 1 votes

# Answer
# Swift 4, 225 bytes, score = 241

Probably golfable a bunch more (maybe in the "Ga-Me-Ca" area?), but Swift is not often used (for a reason, maybe.)

```
func b(i:String){print(i=="Titan" ?2575:["Su":6963,"Ju":699,"Sa":582,"Ur":253,"Ne":246,"Ea":63,"Ve":60,"Ma":33,"Ga":26,"Me":24,"Ca":24,"Io":18,"Mo":17,"Eu":16,"Tr":14,"Pl":12,"Er":12,"Ha":8,"Ti":8][String(i.prefix(2))]!*100)}

```

and ungolfed

```
func size(ofAstralObject object: String) {
  let objectToRadius = // Map size/100 of all objects to the first two chars
   ["Su":6963,
    "Ju":699,
    "Sa":582,
    "Ur":253,
    "Ne":246,
    "Ea":63,
    "Ve":60,
    "Ma":33,
    "Ga":26,
    "Me":24,
    "Ca":24,
    "Io":18,
    "Mo":17,
    "Eu":16,
    "Tr":14,
    "Pl":12,
    "Er":12,
    "Ha":8,
    "Ti":8] // Ti is Titania, while Titan is treated differently

  print(object == "Titan" ?
    2575 : // If "Titan", print the exact size
    objectToRadius[String(i.prefix(2))]!*100 // get the size from the map and multiply by 100
  )
}

```

Try It Online!

I tried different "key sizes" for the map, but of course 1 has many clashes and using three chars doesn't give me `i=="Titan" ?2575:`'s 17 chars, since there's "Io" to manage (and it'll take more than 3 chars, I think).
> 1 votes

# Answer
# JavaScript (ES6), 152 bytes, score = 163

Well, it's a pretty standard solution, but I enjoyed the challenge anyway!

```
s=>s=='Titan'?2575:[6963,699,582,254,246,64,60,34,26,24,24,18,17,16,14,12,12,8,8]["SuJuSaUrNeEaVeMaGaMeCaIoMoEuTrPlErHaTi".match(s[0]+s[1]).index/2]*100

```

My Score:

```
Max. penalty ratio = 1.07068 for Triton
Score = ceil(152 x 1.07068) = 163

```

Try it Online!
> 1 votes

# Answer
# FALSE, 152 bytes, Score = 563

```
[911*.]^$0\[~][1+^]#$$2=\$4=\8=||[2 0!]?$3=[764 0!]?$5=[\$$69=\86=|$[6\]?~[2]?0!]?$6=[\$$83=\85=|$[46\]?~[$72=$[1\]?~[2]?]?0!]?$7=[\$84=$[1\]?~[52]?0!]?

```

Lazy answer using word lengths and first letters but my excuse is that I'm using a weird language

Try it online! (copy paste the code, hit show and then run)

```
[911*.]          {defines a function that multiplies a number by 911 and then prints it}
^$0\[~][1+^]#    {counts the length of the name as it's input, also records the first char}
$$2=\$4=\8=||[1 0!]?  {if the name is 2, 4, or 8 chars long print 911*2 (0! calls the function)}
$3=[764 0!]?          {if name is 3 long print 911*764}
$5=[\$$69=\86=|$[6\]?~[2]?0!]? {5 long? print 911*6 if it starts with E or V, otherwise *2}
$6=[\$$83=\85=|$[46\]?~[       {6 long? print 911*46 if it starts with S or U, otherwise:}
    $72=$[1\]?~[2]?            {if name starts with H print 911*1 else *2
]?0!]?
$7=[\$84=$[1\]?~[26]?0!]?      {7 long? print 1822*1 if it starts with NT otherwise *26 (for jupiter}

```

My results:

```
Sun       : 696004.00 penalty ratio = (696342.00 / 696004.00 )² = 1.00097
Jupiter   : 47372.00  penalty ratio = (69911.00  / 47372.00  )² = 2.17795
Saturn    : 41906.00  penalty ratio = (58232.00  / 41906.00  )² = 1.93095
Uranus    : 41906.00  penalty ratio = (41906.00  / 25362.00  )² = 2.73014
Neptune   : 47372.00  penalty ratio = (47372.00  / 24622.00  )² = 3.70166
Earth     : 5466.00   penalty ratio = (6371.00   / 5466.00   )² = 1.35855
Venus     : 5466.00   penalty ratio = (6052.00   / 5466.00   )² = 1.22591
Mars      : 1822.00   penalty ratio = (3390.00   / 1822.00   )² = 3.46181
Ganymede  : 1822.00   penalty ratio = (2634.00   / 1822.00   )² = 2.08994
Titan     : 1822.00   penalty ratio = (2575.00   / 1822.00   )² = 1.99737
Mercury   : 1822.00   penalty ratio = (2440.00   / 1822.00   )² = 1.79342
Callisto  : 1822.00   penalty ratio = (2410.00   / 1822.00   )² = 1.74959
Io        : 1822.00   penalty ratio = (1822.00   / 1822.00   )² = 1.00000
Moon      : 1822.00   penalty ratio = (1822.00   / 1737.00   )² = 1.10026
Europa    : 1822.00   penalty ratio = (1822.00   / 1561.00   )² = 1.36236
Triton    : 1822.00   penalty ratio = (1822.00   / 1353.00   )² = 1.81343
Pluto     : 1822.00   penalty ratio = (1822.00   / 1186.00   )² = 2.36008
Eris      : 1822.00   penalty ratio = (1822.00   / 1163.00   )² = 2.45435
Haumea    : 911.00    penalty ratio = (911.00    / 816.00    )² = 1.24640
Titania   : 911.00    penalty ratio = (911.00    / 788.00    )² = 1.33655

Max. penalty ratio = 3.70166 for Neptune
Score = ceil(152 x 3.70166) = 563

```
> 1 votes

# Answer
# C (gcc), 118 bytes, score = 135

```
i;f(char*s){i=exp((strchr("(~?_q#m#.(`(=*2,r-v.h2z2p3d3j6>Qb>a?{Qx]",(*s^s[1]*4)+(strlen(s)!=5)&127|32)[1]+55)/13.5);}

```

Try it online!

Scoring

## Rundown

The object name is turned into a single-character hash through the cumbersome process

```
(((*s ^ s[1] << 2) + (strlen(s) != 5)) & 127) | 32

```

whose bloat points to "Titan"/"Titania" as the main offenders. Including the last character in the hash was considered, but that still requires a `strlen()` in C. The first occurence of the hash character is searched for in the hash/data string. When found, the next character is taken and used to approximate the radius of the object in question.

The data character holds the shifted, scaled natural logarithm of the radius. Generated like so:

```
for (int i = 0; i < 20; i++)
    data[i] = log(radii[i]) * 13.5 - 55;

```

The scale was chosen through highly scientific trial-and-error, and the shift for bringing the value within printable ASCII range while avoiding backslashes. Some rearrangement of the objects in the string was necessary due to some hash/data collisions.

```
i;                                      Return value
f(char*s){                              s is object name
    i=                                  Implicit return
    exp(                                Raise e to some power
        (
            strchr(                     Find hash
                "...",                  Hash/data string
                (*s^s[1]*4)+            Calculate...
                (strlen(s)!=5)&127|32   ...hash
            )
            [1]                         Char following hash holds the power
            +55                         Shift it
        )/13.5                          Scale it
    );                                  Use it
}                                       Exit

```
> 1 votes

# Answer
# Python 2, 89 bytes, Score = 234

```
lambda(p):39**4/'zzuSJJaSrUNNrEnVsMeGtTMMoCoInMuErTuPsEaHTT'.find(p[7%len(p)]+p[0])**2.18

```

Try it online!

Most answers posted appear to have used a "encode/decode" strategy. I wondered how well I could do by estimating the diameter of celestial bodies using a simple equation. It's been a fun exercise, but the moderate byte savings are more than made up for by the accuracy penalty.

The core of this solution is the estimating equation:

```
Radius = 39**4/x**2.18

```

where x is twice the rank order of the radius of the body.

I generate the value of x based on the input string using a modification of @Erik the Outgolfer's Python 2 solution. I saved a few bytes on his code by recasting my equations to work with \[2..40\] instead of \[1..20\].

The code for generating rank orders takes up more than 2/3 of the bytes of the whole solution. If anyone has a more compact way of generating ranks, this solution could be shortened further. Because of the accuracy penalty (around 2.6), the score would improve quite a bit.

## Generating the Equation

I used statistical methods to search for simple equations to estimate the size of each body based on its rank. In part following up on the insights in @Level River St's Ruby solution and generalizing, I settled on equations of the form:

```
Radius = A/(Rank)**B

```

Working in R, I used linear models on the log of the radii to develop initial estimates, and then used non-linear optimization, seeding the optimization with the results of the linear models, to search for solutions that minimized the penalty function specified in the problem.

The estimated value of A in the above equation is seven digits, so I searched for a simple expression to save a couple of bytes. I looked for expressions of the form

```
x**y

```

for two digit x and 1 digit y (for a total of five bytes, saving two bytes, or about five points, given the penalty) that was not too different from the optimum value of A and did not inflate the penalty much, and ended up with the (otherwise inexplicable):

```
39**4

```
> 0 votes

# Answer
# TI-BASIC (TI-84), 285 bytes, Score = 285

```
Ans→Str1:{696342,69911,58232,25362,24622,6371,6052,3390,2634,2575,2440,2410,1822,1737,1561,1353,1186,1163,816,788:Ans(-int(-.125inString("SUN     JUPITER SATURN  URANUS  NEPTUNE EARTH   VENUS   MARS    GANYMEDETITAN   MERCURY CALLISTOIO      MOON    EUROPA  TRITON  PLUTO   ERIS    HAUMEA  TITANIA",Str1

```

A simple "index in string to list" program. Can be golfed further.

Input is in `Ans` and is one of the objects' name in full uppercase.
Output is in `Ans` and is automatically printed out.

**Example:**

```
"MOON
MOON
prgmCDGFC
            1737
"IO
IO
prgmCDGFC
            1822

```

**Explanation:**
(Radii list and name string have been shortened for brevity. `...` is used to indicate the rest of the list/string.)

```
Ans→Str1:{696342,69911,5...:Ans(-int(-.125inString("SUN     JU...",Str1  ;complete source

Ans→Str1                                                                 ;store the input string
                                                                         ; in "Str1"
         {696342,69911,5...                                              ;generate the list of
                                                                         ; radii and leave it in
                                                                         ; "Ans"
                                          inString("SUM     JU...",Str1  ;get the index of the
                                                                         ; input string in the
                                                                         ; name string
                                      .125                               ;multiply the index by 1/8
                                -int(-                                   ;then round it towards
                                                                         ; positive infinity
                            Ans(                                         ;use the result as the
                                                                         ; index of the radii list

```

**Visual Model:**

```
Ans→Str1                                            ;Ans = "MOON"
                                                    ;Str1 = "MOON"

{696342,69911,5...                                  ;Ans = {696232 69911 ... }
                                                    ;Str1 = "MOON"

inString("SUN      JU...",Str1                      ;Ans = {696232 69911 ... }
                                                    ;Str1 = "MOON"
                                                    ;current evaluation: 105

.125                                                ;Ans = {696232 69911 ... }
                                                    ;current evaluation: 13.125

-int(-                                              ;Ans = {696232 69911 ... }
                                                    ;current evaluation: 14

Ans(                                                ;Ans = 1737

```
> 0 votes

---
Tags: code-challenge, approximation
---


title: Multiply Two Integer Polynomials

text:
# Question
Title: Multiply Two Integer Polynomials
Your task is to take two single-variable integer polynomial expressions and multiply them into their unsimplified first-term-major left-to-right expansion (A.K.A. FOIL in the case of binomials). Do not combine like terms or reorder the result. To be more explicit about the expansion, multiply the first term in the first expression by each term in the second, in order, and continue in the first expression until all terms have been multiplied by all other terms. Expressions will be given in a simplified LaTeX variant.

Each expression will be a sequence of terms separated by `+` (with exactly one space on each side) Each term will conform to the following regular expression: (PCRE notation)

```
-?\d+x\^\d+

```

In plain English, the term is an optional leading `-` followed by one or more digits followed by `x` and a nonnegative integer power (with `^`)

An example of a full expression:

```
6x^3 + 1337x^2 + -4x^1 + 2x^0

```

When plugged into LaTeX, you get \\$6x^3 + 1337x^2 + -4x^1 + 2x^0\\$

The output should also conform to this format.

Since brackets do not surround exponents in this format, LaTeX will actually render multi-digit exponents incorrectly. (e.g. `4x^3 + -2x^14 + 54x^28 + -4x^5` renders as \\$4x^3 + -2x^14 + 54x^28 + -4x^5\\$) You do not need to account for this and *you should not include the brackets* in your output.

## Example Test Cases

```
5x^4
3x^23

15x^27

```

---

```
6x^2 + 7x^1 + -2x^0
1x^2 + -2x^3

6x^4 + -12x^5 + 7x^3 + -14x^4 + -2x^2 + 4x^3

```

---

```
3x^1 + 5x^2 + 2x^4 + 3x^0
3x^0

9x^1 + 15x^2 + 6x^4 + 9x^0

```

---

```
4x^3 + -2x^14 + 54x^28 + -4x^5
-0x^7

0x^10 + 0x^21 + 0x^35 + 0x^12

```

---

```
4x^3 + -2x^4 + 0x^255 + -4x^5
-3x^4 + 2x^2

-12x^7 + 8x^5 + 6x^8 + -4x^6 + 0x^259 + 0x^257 + 12x^9 + -8x^7

```

## Rules and Assumptions

* You may assume that all inputs conform to this exact format. Behavior for any other format is undefined for the purposes of this challenge.
    + It should be noted that any method of taking in the two polynomials is valid, provided that both are read in as strings conforming to the above format.
* The order of the polynomials matters due to the expected order of the product expansion.
* You must support input coefficients between \\$-128\\$ and \\$127\\$ and input exponents up to \\$255\\$.
    + Output coefficents between \\$-16,256\\$ and \\$16,384\\$ and exponents up to \\$510\\$ must therefore be supported.
* You may assume each input polynomial contains no more than 16 terms
    + Therefore you must (at minimum) support up to 256 terms in the output
* Terms with zero coefficients should be left as is, with exponents being properly combined
* Negative zero is allowed in the input, but is indistinguishable from positive zero semantically. Always output positive zero. Do not omit zero terms.

Happy Golfing! Good luck!

# Answer
# , ~~159~~ ~~153~~ 148 bytes

```
function(P,Q,a=h(P),b=h(Q))paste0(b[1,]%o%a[1,],"x^",outer(b,a,"+")[2,,2,],collapse=" + ")
h=function(s,`/`=strsplit)sapply(el(s/" . ")/"x.",strtoi)

```

Try it online!

I really wanted to use `outer`, so there's almost surely a more efficient approach.
> 4 votes

# Answer
# Haskell, ~~131~~ 122 bytes

```
(%)=drop
f s=do(a,t)<-reads s;(i,u)<-reads$2%t;(a,i):f(3%u)
p!q=3%do(a,i)<-f p;(b,j)<-f q;" + "++shows(a*b)"x^"++show(i+j)

```

Try it online!

`f` parses a polynomial from a string, `!` multiplies two of them and formats the result.

*H.PWiz saved 9 bytes. Thanks!*

## Ungolfed

```
type Monomial = (Int, Int) -- a^i
type Polynomial = [Monomial]

parse :: String -> Polynomial
parse s = do (a, s')  <- reads s
             (i, s'') <- reads (drop 2 s')
             (a, i) : parse (drop 3 s'')

(!) :: String -> String -> String
p!q = drop 3 (concat terms)
  where terms    = [term (a*b) (i+j) | (a,i) <- p', (b,j) <- q']
        term a i = concat [" + ", show a, "x^", show i]
        p'       = parse p
        q'       = parse q

```
> 4 votes

# Answer
# Ruby, ~~102 100~~ 98 bytes

```
->a,b{a.scan(w=/(.*?)x.(\d+)/).map{|x|b.scan(w).map{|y|(eval"[%s*(z=%s;%s),z+%s]"%y+=x)*"x^"}}*?+}

```

Try it online!

### How?

First step: get all the numbers from both polynomials: `scan` returns the numbers as an array of pairs of strings. Then, do a cartesian product of the 2 lists. Now we have all the numbers where we need them, but still in the wrong order.

Example: if we multiply `3x^4` by `-5x^2`, we get the numbers as `[["3","4"],["-5","2"]]`, the first idea was to zip and flatten this list, and then put the numbers into an expression to be evaluated as `[3*-5, 4+2]`. Actually, we don't need to reorder the numbers, we could do it inside the expression by using a temporary variable: the expression becomes `[3*(z=4,-5),z+2]`.

After evaluating these expressions, we get the coefficient and exponent, we need to join them using `"x^"`, and then join all the tems using `"+"`.
> 2 votes

# Answer
## Haskell, ~~124~~ 121 bytes

```
import Data.Lists
f!x=map f.splitOn x
z=read!"x^"!"+"
a#b=drop 3$do[u,v]<-z a;[p,q]<-z b;" + "++shows(u*p)"x^"++show(v+q)

```

Note: TIO lacks `Data.Lists`, so I import `Data.Lists.Split` and `Data.List`: Try it online!

Edit: -3 bytes thanks to @Lynn.
> 2 votes

# Answer
# Pyth - 39 bytes

```
LmsMcdK"x^"%2cb)j" + "m++*FhdKsedCM*FyM

```

Try it online.
> 1 votes

# Answer
# JavaScript (Babel Node), 118 bytes

Takes input as `(a)(b)`.

```
a=>b=>(g=s=>[...s.matchAll(/(-?\d+)x.(\d+)/g)])(a).flatMap(([_,x,p])=>g(b).map(([_,X,P])=>x*X+'x^'+-(-p-P))).join` + `

```

Try it online!
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~192~~ 176 bytes

```
	P =INPUT
	Q =INPUT
	D =SPAN(-1234567890)
P	P D . K ARB D . W REM . P	:F(O)
	B =Q
B	B D . C ARB D . E REM . B	:F(P)
	O =O ' + ' K * C 'x^' W + E	:(B)
O	O ' + ' REM . OUTPUT
END

```

Try it online!

```
	P =INPUT				;* read P
	Q =INPUT				;* read Q
	D =SPAN(-1234567890)			;* save PATTERN for Digits (or a - sign); equivalent to [0-9\\-]+
P	P D . K ARB D . W REM . P	:F(O)	;* save the Koefficient and the poWer, saving the REMainder as P, or if no match, goto O
	B =Q					;* set B = Q
B	B D . C ARB D . E REM . B	:F(P)	;* save the Coefficient and the powEr, saving the REMainder as B, or if no match, goto P
	O =O ' + ' K * C 'x^' W + E	:(B)	;* accumulate the output
O	O ' + ' REM . OUTPUT			;* match ' + ' and OUTPUT the REMainder
END

```
> 1 votes

# Answer
# JavaScript, ~~112~~ 110 bytes

I found two alternatives with the same length. Call with currying syntax: `f(A)(B)`

```
A=>B=>(P=x=>x.split`+`.map(x=>x.split`x^`))(A).flatMap(a=>P(B).map(b=>a[0]*b[0]+'x^'+(a[1]- -b[1]))).join` + `

```

```
f=
A=>B=>(P=x=>x.split`+`.map(x=>x.split`x^`))(A).flatMap(a=>P(B).map(b=>a[0]*b[0]+'x^'+(a[1]- -b[1]))).join` + `

console.log( f('5x^4')('3x^23') )
console.log( f('6x^2 + 7x^1 + -2x^0')('1x^2 + -2x^3') )
console.log( f('3x^1 + 5x^2 + 2x^4 + 3x^0')('3x^0') )
console.log( f('4x^3 + -2x^14 + 54x^28 + -4x^5')('-0x^7') )
console.log( f('4x^3 + -2x^4 + 0x^255 + -4x^5')('-3x^4 + 2x^2') )
```

```
A=>B=>(P=x=>x.split`+`.map(x=>x.split`x^`))(A).flatMap(([c,e])=>P(B).map(([C,E])=>c*C+'x^'+(e- -E))).join` + `

```

```
f=
A=>B=>(P=x=>x.split`+`.map(x=>x.split`x^`))(A).flatMap(([c,e])=>P(B).map(([C,E])=>c*C+'x^'+(e- -E))).join` + `

console.log( f('5x^4')('3x^23') )
console.log( f('6x^2 + 7x^1 + -2x^0')('1x^2 + -2x^3') )
console.log( f('3x^1 + 5x^2 + 2x^4 + 3x^0')('3x^0') )
console.log( f('4x^3 + -2x^14 + 54x^28 + -4x^5')('-0x^7') )
console.log( f('4x^3 + -2x^4 + 0x^255 + -4x^5')('-3x^4 + 2x^2') )
```

*-2 bytes (Luis): Remove spaces around `split` delimiter.*

---

# JavaScript, 112 bytes

Using `String.prototype.matchAll`.

```
A=>B=>(P=x=>[...x.matchAll(/(\S+)x.(\S+)/g)])(A).flatMap(a=>P(B).map(b=>a[1]*b[1]+'x^'+(a[2]- -b[2]))).join` + `

```

```
f=
A=>B=>(P=x=>[...x.matchAll(/(\S+)x.(\S+)/g)])(A).flatMap(a=>P(B).map(b=>a[1]*b[1]+'x^'+(a[2]- -b[2]))).join` + `

console.log( f('5x^4')('3x^23') )
console.log( f('6x^2 + 7x^1 + -2x^0')('1x^2 + -2x^3') )
console.log( f('3x^1 + 5x^2 + 2x^4 + 3x^0')('3x^0') )
console.log( f('4x^3 + -2x^14 + 54x^28 + -4x^5')('-0x^7') )
console.log( f('4x^3 + -2x^4 + 0x^255 + -4x^5')('-3x^4 + 2x^2') )
```
> 1 votes

# Answer
# Python 2, 193 bytes

```
import re
f=re.finditer
lambda a,b:' + '.join(' + '.join(`int(m.group(1))*int(n.group(1))`+'x^'+`int(m.group(2))+int(n.group(2))`for n in f('(-?\d+)x\^(\d+)',b))for m in f('(-?\d+)x\^(\d+)',a))

```

Try it online!

Side note: First time doing a code golf challenge, so sorry if the attempt sucks haha
> 1 votes

# Answer
# Retina, 110 bytes

```
\S\S+(?=.*\n(.+))
 $1#$&
|" + "L$v` (-?)(\d+)x.(\d+).*?#(-?)(\d+)x.(\d+)
$1$4$.($2*$5*)x^$.($3*_$6*
--|-(0)
$1

```

Try it online! Explanation:

```
\S\S+(?=.*\n(.+))
 $1#$&

```

Prefix each term in the first input with a `#`, a copy of the second input, and a space. This means that all of the terms in copies of the second input are preceded by a space and none of the terms from the first input are.

```
|" + "L$v` (-?)(\d+)x.(\d+).*?#(-?)(\d+)x.(\d+)
$1$4$.($2*$5*)x^$.($3*_$6*

```

Match all of the copies of terms in the second input and their corresponding term from the first input. Concatenate any `-` signs, multiply the coefficients, and add the indices. Finally join all of the resulting substitutions with the string `+`.

```
--|-(0)
$1

```

Delete any pairs of `-`s and convert `-0` to `0`.
> 1 votes

# Answer
# Jelly, 28 bytes

```
ṣ”+ṣ”xV$€)p/ZPSƭ€j⁾x^Ʋ€j“ +

```

Try it online!

Full program. Takes the two polynomials as a list of two strings.

### Explanation (expanded form)

```
ṣ”+ṣ”xV$€µ€p/ZPSƭ€j⁾x^Ʋ€j“ + ” Arguments: x
         µ                     Monadic chain.
          €                    Map the monadic link over the argument.
                               Note that this will "pop" the previous chain, so
                               it will really act as a link rather than a
                               sub-chain.
ṣ”+                             ṣ, right = '+'.
                                Split the left argument on each occurrence of
                                the right.
                                Note that strings in Jelly are lists of
                                single-character Python strings.
        €                       Map the monadic link over the argument.
       $                         Make a non-niladic monadic chain of at least
                                 two links.
   ṣ”x                            ṣ, right = 'x'.
                                  Split the left argument on each occurrence of
                                  the right.
      V                           Evaluate the argument as a niladic link.
            /                  Reduce the dyadic link over the argument.
           p                    Cartesian product of left and right arguments.
                       €       Map the monadic link over the argument.
                      Ʋ         Make a non-niladic monadic chain of at least
                                four links.
             Z                   Transpose the argument.
                 €               Map the monadic link over the argument.
                ƭ                 At the first call, call the first link. At the
                                  second call, call the second link. Rinse and
                                  repeat.
              P                    Product: ;1×/$
               S                   Sum: ;0+/$
                  j⁾x^           j, right = "x^".
                                 Put the right argument between the left one's
                                 elements and concatenate the result.
                        j“ + ” j, right = " + ".
                               Put the right argument between the left one's
                               elements and concatenate the result.

```

### Aliasing

`)` is the same as `µ€`.
A trailing  is implied and can be omitted.

### Algorithm

Let's say we have this input:

```
["6x^2 + 7x^1 + -2x^0", "1x^2 + -2x^3"]

```

The first procedure is the Parsing, applied to each of the two polynomials. Let's handle the first one, `"6x^2 + 7x^1 + -2x^0"`:

The first step is to split the string by `'+'`, so as to separate the terms. This results in:

```
["6x^2 ", " 7x^1 ", " -2x^0"]

```

The next step is to split each string by `'x'`, to separate the coefficient from the exponent. The result is this:

```
[["6", "^2 "], [" 7", "^1 "], [" -2", "^0"]]

```

Currently, it looks like there's a lot of trash in these strings, but that trash is actually unimportant. These strings are all going to be evaluated as niladic Jelly links. Trivially, the spaces are unimportant, as they are not between the digits of the numbers. So we could as well evaluate the below and still get the same result:

```
[["6", "^2"], ["7", "^1"], ["-2", "^0"]]

```

The `^`s look a bit more disturbing, but they actually don't do anything either! Well, `^` is the bitwise XOR atom, however niladic chains act like monadic links, except that the first link actually becomes the argument, instead of taking an argument, if it's niladic. If it's not, then the link will have an argument of `0`. The exponents have the `^`s as their first char, and `^` isn't niladic, so the argument is assumed to be `0`. The rest of the string, i.e. the number, is the right argument of `^`. So, for example, `^2` is \\$0\text{ XOR }2=2\\$. Obviously, \\$0\text{ XOR }n=n\\$. All the exponents are integer, so we are fine. Therefore, evaluating this instead of the above won't change the result:

```
[["6", "2"], ["7", "1"], ["-2", "0"]]

```

Here we go:

```
[[6, 2], [7, 1], [-2, 0]]

```

This step will also convert `"-0"` to `0`.

Since we're parsing both inputs, the result after the Parsing is going to be this:

```
[[[6, 2], [7, 1], [-2, 0]], [[1, 2], [-2, 3]]]

```

The Parsing is now complete. The next procedure is the Multiplication.

We first take the Cartesian product of these two lists:

```
[[[6, 2], [1, 2]], [[6, 2], [-2, 3]], [[7, 1], [1, 2]], [[7, 1], [-2, 3]], [[-2, 0], [1, 2]], [[-2, 0], [-2, 3]]]

```

Many pairs are made, each with one element from the left list and one from the right, in order. This also happens to be the intended order of the output. This challenge really asks us to apply multiplicative distributivity, as we're asked not to further process the result after that.

The pairs in each pair represent terms we want to multiply, with the first element being the coefficient and the second being the exponent. To multiply the terms, we multiply the coefficients and add the exponents together (\\$ax^cbx^d=abx^cx^d=ab(x^cx^d)=(ab)x^{c+d}\\$). How do we do that? Let's handle the second pair, `[[6, 2], [-2, 3]]`.

We first transpose the pair:

```
[[6, -2], [2, 3]]

```

We then take the product of the first pair, and the sum of the second:

```
[-12, 5]

```

The relevant part of the code, `PSƭ€`, doesn't actually reset its counter for each pair of terms, but, since they're pairs, it doesn't need to.

Handling all pairs of terms, we have:

```
[[6, 4], [-12, 5], [7, 3], [-14, 4], [-2, 2], [4, 3]]

```

Here, the Multiplication is done, as we don't have to combine like terms. The final procedure is the Prettyfying.

We first join each pair with `"x^"`:

```
[[6, 'x', '^', 4], [-12, 'x', '^', 5], [7, 'x', '^', 3], [-14, 'x', '^', 4], [-2, 'x', '^', 2], [4, 'x', '^', 3]]

```

Then we join the list with `" + "`:

```
[6, 'x', '^', 4, ' ', '+', ' ', -12, 'x', '^', 5, ' ', '+', ' ', 7, 'x', '^', 3, ' ', '+', ' ', -14, 'x', '^', 4, ' ', '+', ' ', -2, 'x', '^', 2, ' ', '+', ' ', 4, 'x', '^', 3]

```

Notice how we've still got numbers in the list, so it's not really a string. However, Jelly has a process called "stringification", ran right at the end of execution of a program to print the result out. For a list of depth 1, it really just converts each element to its string representation and concatenates the strings together, so we get the desired output:

```
6x^4 + -12x^5 + 7x^3 + -14x^4 + -2x^2 + 4x^3

```
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~192~~ 190 bytes

```
n=>m=>string.Join(g=" + ",from a in n.Split(g)from b in m.Split(g)select f(a.Split(p="x^")[0])*f(b.Split(p)[0])+p+(f(a.Split(p)[1])+f(b.Split(p)[1])));Func<string,int>f=int.Parse;string p,g;

```

Query syntax seems to be a byte shorter than method syntax.

Try it online!
> 1 votes

# Answer
# Perl 6, 114 bytes

```
{my&g=*.match(/(\-?\d+)x\^(\d+)/,:g)».caps».Map;join " + ",map {"{[*] $_»{0}}x^{[+] $_»{1}}"},(g($^a)X g $^b)}

```

Try it online!
> 1 votes

# Answer
# Python 2, 130 bytes

```
lambda a,b:' + '.join([`v*V`+'x^'+`k+K`for V,K in g(a)for v,k in g(b)])
g=lambda s:[map(int,t.split('x^'))for t in s.split(' + ')]

```

Try it online!
> 1 votes

---
Tags: code-golf, math, parsing, polynomials
---


title: Copodope Gopolopfop

text:
# Question
Title: Copodope Gopolopfop
### The Language: Oppification

A funny language to speak is created by applying the following process to each word:

1. Place `op` after each consonant. So `Code` becomes `Copodope`.

Yes, that's it. For the purpose of this challenge, `y` is always a consonant.

### The Challenge: De-oppification

Given an oppified word, return the original word. Input will only contain letters. The first letter may be capitalized. The original word will never be empty and will always contain a vowel.

### Test Cases:

```
Oppified      ->         Original
a                        a
I                        I
itop                     it
opop                     op
Opop                     Op
popopop                  pop
Copopop                  Cop
opopopop                 opop
Kopicopkop               Kick
Asopia                   Asia
soptopopop               stop
hopoopopsop              hoops
hopoopopedop             hooped
ooooohop                 oooooh
aaaopopaaa               aaaopaaa
Popopopsopicoplope       Popsicle
gopaloplopopopinopgop    galloping
aopopbopopopcopopop      aopbopcop

```

# Answer
> 10 votes
# , ~~12~~, 5 bytes

```
Í.“op

```

Try it online!

```
00000000: cd2e 936f 70                             ...op

```

Saved 7 bytes thanks to @Xnor's realization that since the input must always be opped, we don't have to check for vowels.

# Answer
> 12 votes
## Retina, 9 bytes

```
(?!\G)op

```

Try it online!

Instead of checking that the preceding character is a consonant, we just make sure that the current `op` is not adjacent to either the beginning of the string or the previous match. The only case where we could match an incorrect `op` is if the original string contained an `op` (resulting in `opop`). But in that case we'll just remove the first `op` instead of the second and the result will be the same.

# Answer
> 10 votes
# Python, 42 bytes

```
lambda s:re.sub('(.)op',r'\1',s)
import re

```

Try it online!

If I'm not mistaken, you can just substitute all `?op` with `?` without caring about vowels. If the original string contains `op`, then it's oppified to `opop`, and the replacement returns it to `op` and no further. This is because the pattern matches for `?op` cannot overlap, so only one `op` is removed.

A non-regex solution is 5 bytes longer.

**Python, 47 bytes**

```
f=lambda s:s and s[0]+f(s[1+2*(s[1:3]=='op'):])

```

Try it online

# Answer
> 5 votes
# Retina, ~~15~~ 8 bytes

```
(.)op
$1

```

Try it online!

*-7 bytes thanks to Kevin Cruijssen*

# Answer
> 5 votes
# Perl 5, 10 + 1 = 11 bytes

```
s/.\Kop//g

```

Try it online!

Run with `-p` (1 byte penalty); golfing languages might do implicit I/O automatically, but Perl needs an option for it.

When I saw @xnor's answer, I realised it could be improved using a Perl-specific regex feature; `s/a\Kb/c/g` is equivalent to `s/ab/ac/g` (in other words, the `s///` only replaces the things after the first `\K`). So here's how it looks in Perl.

# Answer
> 3 votes
# Go, ~~103~~ 92 bytes

Must... compile... Go built-in functions have weird names. :P

```
import."regexp"
func f(s string)string{return MustCompile("(.)op").ReplaceAllString(s,"$1")}

```

Try it online!

# Answer
> 3 votes
# PHP, 36 bytes

```
<?=preg_replace("#.\Kop#","",$argn);

```

Try it online!

# Answer
> 3 votes
# Haskell (~~93~~ ~~62~~ 61 Bytes)

```
a(x:'o':'p':r)|notElem x"aeiouAEIOU"=x:a r
a(x:r)=x:a r
a x=x

```

thanks to @nimi suggestions in comments!

# Answer
> 2 votes
# Japt, 9 bytes

```
r"%Vop"_g

```

Try it online

# Answer
> 1 votes
# JavaScript (ES6), 35 bytes

Add `f=` at beginning and invoke like `f(arg)`.

```
s=>s.replace(/([^aeiou])op/gi,"$1")

```

I am surprised no one posted a JavaScript solution yet....

## Test Snippet

```
let f=
s=>s.replace(/([^aeiou])op/gi,"$1")

console.log("a" + " -> " + f("a"));
console.log("I" + " -> " + f("I"));
console.log("itop" + " -> " + f("itop"));
console.log("opop" + " -> " + f("opop"));
console.log("Opop" + " -> " + f("Opop"));
console.log("popopop" + " -> " + f("popopop"));
console.log("Copopop" + " -> " + f("Copopop"));
console.log("opopopop" + " -> " + f("opopopop"));
console.log("Kopicopkop" + " -> " + f("Kopicopkop"));
console.log("Asopia" + " -> " + f("Asopia"));
console.log("soptopopop" + " -> " + f("soptopopop"));
console.log("hopoopopsop" + " -> " + f("hopoopopsop"));
console.log("hopoopopedop" + " -> " + f("hopoopopedop"));
console.log("ooooohop" + " -> " + f("ooooohop"));
console.log("aaaopopaaa" + " -> " + f("aaaopopaaa"));
console.log("Popopopsopicoplope" + " -> " + f("Popopopsopicoplope"));
console.log("gopaloplopopopinopgop" + " -> " + f("gopaloplopopopinopgop"));
console.log("aopopbopopopcopopop" + " -> " + f("aopopbopopopcopopop"));
```

# Answer
> 1 votes
# C (gcc), 83 bytes

```
main(c,v)char**v;{for(;*v[1];strchr("aAeEiIoOuU",putchar(*v[1]++))?:printf("op"));}

```

Try it online!

# Answer
> 0 votes
# Crystal, 39 Bytes

```
def o(s)s.gsub(/([^aeiou])op/,"\\1")end

```

## How it works

It simply searches for each consonant, followed by the sequence `op`. If so, replace that sequence only with the consonant found before: `([^aeiou])`.

Try it online

# Answer
> 0 votes
# Ruby, ~~34~~ ~~27~~ 22 + 1 = 23 bytes

*-4 bytes thanks to RJHunter.*

+1 byte for the `-p` flag.

```
$_.gsub!(/(.)op/,'\1')

```

Try it online!

# Answer
> 0 votes
# ///, 18 bytes

```
/op/.//../o\p//.//

```

Try it online!

Note that this snippet wants to replace `op` with a `.`, but later on there is a replacement defined where `op` is being put back into the string. That second instruction would have the `op` replaced by a `.` (and thus insert a `.` into the end result), so I've used a `\` between the `o` and `p` to break the pattern.

# Answer
> 0 votes
# APL (Dyalog), 13 bytes

```
'(.)op'⎕R'\1'

```

Try it online!

Simply PCRE **R**eplace any character followed by "op" with the character itself.

# Answer
> 0 votes
# Java 8, ~~36~~ 26 bytes

```
s->s.replaceAll("(.)op","$1")

```

-10 bytes by replacing `[^aeiou]` with `.`, thanks to *@xnor*'s explanation in his Python answer.

Try it here.

# Answer
> 0 votes
# sed, 22 bytes

```
sed -E 's/(.)op/\1/g'

```

Reads from STDIN until EOF and outputs de-oppified string
Uses same length reduction technique from @xnor's Python answer

# Answer
> 0 votes
# , 29 bytes

```
gsub("(.)op","\\1",scan(,''))

```

Try it online!

Much like most other solutions here, captures character followed by op, replaces it with character itself.

---
Tags: code-golf, string, natural-language
---


title: Today is the Center

text:
# Question
Title: Today is the Center
Given a date as input in any convenient format, output a calendar with that date as the exact center of a five-week window. The header of the calendar must include the two-letter abbreviations for the days of the week (i.e., `Su Mo Tu We Th Fr Sa`). Three-letter or other abbreviations of the days are not allowed.

For example, given `April 2 2019` as input, the output should be

```
Sa Su Mo Tu We Th Fr
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31  1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19

```

so that the given date is the exact middle of the calendar.

Given `February 19 2020`, output

```
Su Mo Tu We Th Fr Sa
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
 1  2  3  4  5  6  7

```

For `September 14 1752`, show the following:

```
Mo Tu We Th Fr Sa Su
28 29 30 31  1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30  1

```

---

* Input and output can be given by any convenient method.
* The input is guaranteed non-empty and valid (i.e., you'll never receive `""` or `Feb 31` etc.).
* Assume Gregorian calendar for all dates.
* Leap years must be accounted for.
* Input dates will range from `Jan 1 1600` to `Dec 31 2500`.
* You can print it to STDOUT or return it as a function result.
* Either a full program or a function are acceptable.
* Any amount of extraneous whitespace is acceptable, so long as the characters line up appropriately.
* Leading zeros on the single-digit days are allowed, as are aligning the single-digit days to be left-aligned instead.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# , ~~77~~ 72 bytes

```
function(d,`~`=format)write(c(strtrim(d+-3:3~"%a",2),d+-17:17~"%e"),1,7)

```

Try it online!

Fixed output to use 2 letter day abbreviations.

-1 byte using `strtrim` thanks to Aaron Hayman.

Pads date numbers with leading 0s; takes input as a `Date`, which can be created by using `as.Date("YYYY/MM/DD")`.

Weirdly short for an R answer...
> 12 votes

# Answer
# 05AB1E, ~~175~~ ~~174~~ ~~172~~ ~~171~~ 160 bytes

```
¦WΘ1š-1šVтFY`2ô0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝVY})DJIJk18+£35.£¬.•4ιõ÷‡o‹ƶ¸•2ôs`UÐ3‹12*+>13*5÷s3‹Xα©т%D4÷®т÷©4÷®·()DćsćsO7%._s€нT‰J«7ô»

```

Input in the format `[day, month, year]`. Output with leading `0`s for single-digit days, and lowercase `mo` through `su` (+1 byte can be added if titlecase is mandatory).

**Try it online or verify all test cases.**

Holy shit.. This might be my new record for longest 05AB1E answer, and then I include some very complex challenges I did... \>.\> EDIT: Hmm ok, almost.. ;p

**Important note:** 05AB1E doesn't have any builtins for Date objects or calculations. The only builtin regarding dates it has is today's year/month/day/hours/minutes/seconds/microseconds.

So because of that, almost all of the code you see are manual calculations to calculated the previous and next days (including transition over years and keeping in mind the leap years), and calculating the day of the week by using Zeller's congruence.

Huge parts of the code are copied from this earlier 05AB1E answer of mine, which will also be relevant for the explanation below.

**Explanation:**

We start by going to the first day of the previous month:

```
¦          # Remove the first item (the days) from the (implicit) input
 W         # Get the minimum (without popping the list itself)
           # (since the year is guaranteed to be above 1599, this is the month)
  Θ        # Check if its exactly 1 (1 if 1, 0 if in the range [2,31])
   1š      # Prepend a 1 as list (so we now have either [1,1] or [1,0]
     -     # Subtract this from the month and year
      1š   # And prepend a 1 for the day
        V  # Pop and store this first day of the previous month in variable `Y`

```

Then I use that date as start date, and calculate the next 100 days:

```
тF    # Loop 100 times:
  Y`2ô0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝV
      #  Calculate the next day in line
      #  (see the linked challenge above for a detailed explanation of this)
   Y  #  And leave it on the stack
 })   # After the loop: wrap the entire stack into a list, which contains our 100 days

```

Then, with the input-date as the middle, I only leave the 17 before and 17 after that input-date from the list:

```
DJ          # Duplicate the 100 dates, and join the day/month/year together to strings
  IJ        # Push the input, also joined together
    k       # Get the 0-based index of the input in this list
            # (the joins are necessary, because indexing doesn't work for 2D lists)
     18+    # Add 18 to this index (18 instead of 17, because the index is 0-based)
        £   # Only leave the first index+18 items from the 100 dates
     35.£   # Then only leave the last 35 items

```

Now we have our 35 days. Next step is to calculate the day of the week, and create the header of the output-table:

```
¬                # Get the first date of the list (without popping the list itself)
 .•4ιõ÷‡o‹ƶ¸•    # Push compressed string "sasumotuwethfr"
             2ô  # Split it into chunks of size 2
s                # Swap to get the first date again
 `UÐ3‹12*+>13*5÷s3‹Xα©т%D4÷®т÷©4÷®·()DćsćsO7%
                 # Calculate the day of the week (sa=0; su=1; ...; fr=6)
                 # (see the linked challenge above for a detailed explanation of this)
  ._             # Rotate the list of strings that many times

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•4ιõ÷‡o‹ƶ¸•` is `"sasumotuwethfr"`.

Then we create the days to fill the table itself based on our earlier created list of dates. Which we'll merge together with the header. After which we can print the final result:

```
s           # Swap to get the list of dates again
 €н         # Only leave the first item of each date (the days)
   T‰       # Take the divmod 10 of each
     J      # Join those divmod results together
            # (we now have leading 0s for single-digit days)
      «     # Merge this list together with the header list
       7ô   # Split it into chunks of size 7
         »  # Join each inner list by spaces, and then each string by newlines
            # (and output the result implicitly)

```
> 8 votes

# Answer
# JavaScript (ES6),  ~~141~~  126 bytes

*Saved 15 bytes by borrowing `.toUTCString().slice(0,2)` from Neil's answer*

Takes input as a Date object.

```
f=(d,n=0)=>n<42?(D=new Date(d-864e5*(24-n)),n<7?D.toUTCString().slice(0,2):(i=D.getDate())>9?i:' '+i)+`
 `[++n%7&&1]+f(d,n):''

```

Try it online!
> 6 votes

# Answer
# JavaScript (Node.js), ~~205~~ ~~152~~ 145 bytes

```
f=
d=>`012345`.replace(g=/./g,r=>`0123456
`.replace(g,c=>`${new Date(d-864e5*(24-c-r*7))[+r?`getUTCDate`:`toUTCString`]()}`.slice(0,2).padStart(3)))
```

```
<input type=date oninput=o.textContent=f(this.valueAsDate)><pre id=o>
```

Try it online! Takes input as JavaScript Date object or timestamp. Edit: Saved 1 byte thanks to @EmbodimentofIgnorance, which then allowed me to save a further 7 bytes by adding a trailing newline to the output. Saved 52 bytes when I discovered that I was working around behaviour that was not actually buggy in the first place...
> 4 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~124~~ 120 bytes

```
n=>{for(int i=0;i<42;)Write($"{(i<7?$"{n.AddDays(i-3):ddd}".Remove(2,1):n.AddDays(i-24).Day+""),3}"+(++i%7<1?"\n":""));}

```

Try it online!
> 3 votes

# Answer
# Perl 6, 87 bytes

```
{~rotate(<Th Fr Sa Su Mo Tu We>,.day-of-week),|comb 21,($_-17..$_+17)>>.day.fmt('%2d')}

```

Try it online!

Takes a `Date` object, returns a list of lines.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 123 bytes

```
(s=#;Grid@Join[{StringTake[ToString@DayName[s~d~#]&/@Range[-3,3],2]},Partition[Last@d[s,#]&/@Range[-17,17],7]])&
d=DatePlus

```

Try it online!

I don't know why `Grid` doesn't work on TIO but this code outputs this

@DavidC saved 1 byte
> 2 votes

# Answer
# PHP, ~~197~~ ~~189~~ 187 bytes

```
for($d=date_create($argn)->sub($i=new DateInterval(P17D)),$i->d=1;$x++<35;$h.=$x<8?substr($d->format(D),0,2).' ':'',$d->add($i))$o.=str_pad($d->format(j),3,' ',2);echo wordwrap($h.$o,20);

```

Try it online!

Input is `STDIN` as a date string. Run with `php -nF`.

```
$ echo April 2 2019|php -nF cal.php

Sa Su Mo Tu We Th Fr
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31  1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19

```

Verify all test cases

Or **174 bytes** with zero-padded single digits.
> 2 votes

# Answer
# Java (JDK), 149 bytes

```
d->{d.add(5,-24);for(int i=0,w;i<42;d.add(5,1))System.out.printf("%c%2s",i%7<1?10:32,i++<7?"SaSuMoTuWeThFr".substring(w=d.get(7)%7*2,w+2):d.get(5));}

```

Try it online!

## Credits
> 2 votes

# Answer
# MATL, ~~34~~ ~~33~~ 31 bytes

```
YO-17:17+t7:)8XOO3Z(!1ew7XOU7e!

```

Try it online!

### Explanation

```
YO       % Implicit input. Convert to date number. This is a single number
         % that specifies the date
-17:17   % Push [-17 -16 ... 16 17]
+        % Add to date number, element-wise. This gives a row vector of 35
         % date numbers centered around the input date
t        % Duplicate
7:       % Push [1 2 ... 7]
)        % Index into the 35-element vector. This keeps the first 7 entries
8XO      % Convert to day-of-week in 3 letters. Gives a 3-col char matrix
O3Z(     % Write char 0 (equivalent to space for display purposes) into the
         % 3rd column
!1e      % Tranpose and linearize into a row. This produces a string such as
         % 'Tu We Th Fr Sa Su Mo ', to be used as column headings
w        % Swap. This brings to top the row vector of 35 date numbers
         % computed from the input
7XO      % Convert to day-of-month. Gives a 2-col char matrix
U        % Convert each row to number
7e!      % Reshape into 7-row matrix and transpose
         % Implicit display. This prints the string with the headings and
         % the matrix. The latter has a minimum-one-space separation between
         % columns, so it is aligned with the headings

```
> 2 votes

# Answer
# Excel VBA, ~~190~~ 159 bytes

Thanks @TaylorScott

```
Function z(i)
Dim d(5,6)
v=DateValue(i)-17
For x=1To 5
For y=0To 6
d(0,y)=Left(WeekdayName(Weekday(v+y)),2)
d(x,y)=day(v+y+(x-1)*7)
Next y,x
z=d()
End Function

```

Takes input in the form of a valid date string for Excel VBA (e.g. February 19, 2020; 2/19/2020; 19-Feb-2019), and returns an array with the given calendar centered on it.
> 1 votes

# Answer
# Red, ~~153~~ 131 bytes

```
func[d][s: d - 24 loop 7[prin[""copy/part system/locale/days/(s/10) 2]s:
s + 1]loop 5[print""loop 7[prin pad/left s/4 3 s: s + 1]]]

```

Try it online!
> 0 votes

# Answer
# T-SQL, 203 bytes

```
DECLARE @f date='2020-02-19'

,@ char(20)=0,@d char(105)=0SELECT
@=left(format(d,'D'),2)+' '+@,@d=right(d,2)+char(32-n%7/6*19)+@d
FROM(SELECT dateadd(d,number-17,@f)d,number n
FROM spt_values WHERE'P'=type)x ORDER BY-n
PRINT @+'
'+@d

```

The online version is slightly different, this posted version works in MS-SQL Studio Management. It saves 1 bytes compared with the online version, but doesn't give the correct result online

**Try it online**
> 0 votes

# Answer
# Python 2, 115 bytes

```
from datetime import*
d=input()
for i in range(42):print(d+timedelta(i-24)).strftime('%'+'da'[i<7])[:2]+i%7/6*'\n',

```

Try it online!

Not sure if this is allowed... takes input from STDIN in the form `date(year, month, day)`. This can also be represented as `__import__('datetime').date(year, month, day)`. These are really `__import__('datetime').date` objects.
> 0 votes

---
Tags: code-golf, string, ascii-art, date
---


title: Rotate the anti-diagonals

text:
# Question
Title: Rotate the anti-diagonals
## Background

In most reasonable programming languages, it's very easy to rotate the rows or columns of a 2D array. In this challenge, your task is to rotate the *anti-diagonals* instead. Recall that the anti-diagonals of a 2D array are its 1D slices taken in the northeast direction ↗.

## Input

A non-empty rectangular 2D array of single-digit numbers in any reasonable format. Note that the array may not be a square.

## Output

The same array, but with each anti-diagonal rotated one step to the right.

## Example

Consider the `3x4` input array

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

```

The anti-diagonals of this array are

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

```

Their rotated versions are

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

```

Thus the correct output is

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

```

## Rules and scoring

You can write a full program or a function. It's also acceptable to write a function that modifies the input array in place, if your language allows that. The lowest byte count wins, and standard loopholes are disallowed.

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you want to include multiple numbers in your header (e.g. because your score is the sum of two files, or you want to list interpreter flag penalties separately, or you want to show old scores that you improved), make sure that the actual score is the *last* number in the header.

```
var QUESTION_ID=63755,OVERRIDE_USER=32014;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

## Additional test cases

```
Input:
4
Output:
4

Input:
5 6 1
Output:
5 6 1

Input:
0 1
6 2
Output:
0 6
1 2

Input:
6 3 0 8
4 6 1 4
6 2 3 3
9 3 0 3
Output:
6 4 6 1
3 6 2 3
0 9 3 0
8 4 3 3

Input:
5 8 2
6 7 3
2 6 1
6 0 6
6 4 1
Output:
5 6 7
8 2 6
2 6 0
3 6 4
1 6 1

Input:
9 9 4 0 6 2
2 3 2 6 4 7
1 5 9 3 1 5
0 2 6 0 4 7
Output:
9 2 3 2 6 4
9 1 5 9 3 1
4 0 2 6 0 4
0 6 2 7 5 7

```

# Answer
# CJam, 20

```
{z_)\zLa+(@+\.+s\,/}

```

Written as a function block. Try it online

**Explanation:**

The input can be viewed like this:

That is, we separate the top row and right column from the rest of the matrix, and consider those elements in the order shown by the arrow.

Then the output is like this:

The remaining rectangular block is moved diagonally as a whole, and the edge elements are rearranged in the order/positions showed by the new arrow.

The code does almost exactly that, except the output is first generated with the arrow going straight down (so the matrix has a tail, like the letter P), then corrected.

```
z      zip (transpose) the matrix
_      make a copy
)      take out the last row (right column before transposing)
\      swap with the rest of the matrix
z      transpose back
La+    append an empty row (needed for the single-column case,
        which leaves an empty matrix here)
(      take out the first row (top row without the corner)
@+     bring the right column to the top of the stack and concatenate
        obtaining an array of the edge elements (marked with the blue arrow)
\      swap with the remaining part (big white block in the diagrams)
.+     concatenate element by element
        each edge element is concatenated with a row of the white block
        after the white block runs out, the remaining elements form new rows
s      convert the whole thing to a string (concatenating all rows)
\      swap with the copy of the transposed matrix
,      get its length (number of original columns)
/      split the string into rows of that length

```
> 20 votes

# Answer
## CJam, ~~44~~ ~~43~~ ~~42~~ 40 bytes

```
qN/:ReeSf.*:sz1fm<{Rz,{(S-(o\}*~]{},No}h

```

Test it here.

Hmm, much better than my first attempt, but I have a feeling Dennis will solve this in much less anyway...

Input and output are as ASCII grids:

```
0123
4567
8901

```

gives

```
0456
1890
2371

```
> 9 votes

# Answer
# J, 24 char

Function taking one argument.

```
$$<@(1&|.)/./:&;</.@i.@$

```

J has an operator `/.` called *Oblique*. It can't invert it, so reconstruction isn't trivial, but you can consider "listing obliques" as a permutation of the elements of the array. So we invert that permutation with `/:` (dyadic *Sort*), by putting the "listing obliques" permutation for that size (`</.@i.@$`) on the right and our new oblique values, rotated properly, on the left. Then we reshape this list into the old rectangular array using good old `$$`.

```
   3 4$i.10
0 1 2 3
4 5 6 7
8 9 0 1
   ($$<@(1&|.)/./:&;</.@i.@$) 3 4$i.10
0 4 5 6
1 8 9 0
2 3 7 1

```

Try it online.
> 6 votes

# Answer
# J, ~~38~~ 30 bytes

*8 bytes saved thanks to @algorithmshark.*

```
{./.((}.~#),~({.~#),.])}:"1@}.

```

The function collects the top and left edges into a list, cuts the list to two pieces of sufficient sizes and stitches them to the right and bottom of the core part.

Usage:

```
   ]input=.0 1 2 3, 4 5 6 7,: 8 9 0 1
0 1 2 3
4 5 6 7
8 9 0 1
   ({./.((}.~#),~({.~#),.])}:"1@}.) input
0 4 5 6
1 8 9 0
2 3 7 1

```

Try it online here.
> 5 votes

# Answer
# Julia, ~~153~~ ~~149~~ 139 bytes

```
A->(length(A)>1&&((m,n)=size(A);r(X)=for i=1:n X[:,i]=reverse(X[:,i])end;r(A);for i=-m:m A[diagind(A,i)]=circshift(diag(A,i),1)end;r(A));A)

```

This creates an unnamed function that accepts an array and returns the input array modified in place.

Ungolfed:

```
# Create a function to reverse the columns of a matrix
function revcols!(X)
    for = 1:size(X, 2)
        X[:,i] = reverse(X[:,i])
    end
    return X
end

# Our main function
function zgarb!(A)
    # Only perform operations if the array isn't one element
    if length(A) > 1
        # Record the number of rows
        m = size(A, 1)

        # Reverse the columns in place
        revcols!(A)

        # Shift each diagonal
        for i = -m:m
            A[diagind(A, i)] = circshift(diag(A, i), 1)
        end

        # Reverse the columns back
        revcols!(A)
    end
    return A
end

```

Thanks to Martin Büttner for algorithmic advice and for saving 4 bytes!
> 4 votes

# Answer
# Pyth, 20 bytes

```
J+PhQ.)MQ++L.(J0tQ]J

```

Uses Adistu's approach of removing the top row and right column, then sticking them on the left and bottom. But with mutable data structures, not transpositions.
> 3 votes

# Answer
## ES6, 75 bytes

This accepts an array of arrays as a parameter and modifies it in place.

```
a=>{t=a.shift();a.map(r=>{t.push(r.pop());r.unshift(t.shift())});a.push(t)}

```

Ungolfed:

```
function anti_diagonal(array) {
    var temp = array.shift(); // strip off the first row
    array.forEach(row => temp.push(row.pop())); // strip off the last elements of each row
    array.forEach(row => row.unshift(temp.shift())); // distribute the elements to the beginning of each row
    array.push(temp); // the remaining elements become the last row
}

```

See @aditsu's diagram for further clarification.
> 3 votes

# Answer
# Octave, 85 bytes

```
@(a)[(b=[a(1,1:end),a(2:end,end)'])(1:(s=size(a)(1)))',[a(2:end,1:end-1);b(s+1:end)]]

```

I hope I could get rid of the `end`s.
> 2 votes

# Answer
# Python 2, ~~113~~ ~~104~~ 94 bytes

```
f=lambda i,b=[]:i and[b and b[:1]+i[0][:-1]]+f(i[1:],b[1:]or i[0][:-1]+[l[-1]for l in i])or[b]

```

Try it online!

This is a fairly literal interpretation of @aditsu's method. Python's syntax for treating empty lists as False helped save an extra 10 bytes.
> 1 votes

---
Tags: code-golf, array
---


title: Is it a prefix code?

text:
# Question
Title: Is it a prefix code?
In information theory, a "prefix code" is a dictionary where none of the keys are a prefix of another. In other words, this means that none of the strings starts with any of the other.

For example, `{"9", "55"}` is a prefix code, but `{"5", "9", "55"}` is not.

The biggest advantage of this, is that the encoded text can be written down with no separator between them, and it will still be uniquely decipherable. This shows up in compression algorithms such as Huffman coding, which always generates the optimal prefix code.

Your task is simple: Given a list of strings, determine whether or not it is a valid prefix code.

Your input:

* Will be a list of strings in any reasonable format.
* Will only contain printable ASCII strings.
* Will not contain any empty strings.

Your output will be a truthy/falsey value: Truthy if it's a valid prefix code, and falsey if it isn't.

Here are some true test cases:

```
["Hello", "World"]
["Code", "Golf", "Is", "Cool"]
["1", "2", "3", "4", "5"]
["This", "test", "case", "is", "true"]

["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]

```

Here are some false test cases:

```
["4", "42"]
["1", "2", "3", "34"]
["This", "test", "case", "is", "false", "t"]
["He", "said", "Hello"]
["0", "00", "00001"]
["Duplicate", "Duplicate", "Keys", "Keys"]

```

This is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

# Answer
> 12 votes
# Pyth, 8 bytes

```
.AxM.PQ2

```

Test suite

Take all 2 element permutations of the input, map each to the index of one string in the other (0 for a prefix) and return whether all results are truthy (non-zero).

# Answer
> 12 votes
## Haskell, 37 bytes

```
f l=[x|x<-l,y<-l,zip x x==zip x y]==l

```

Each element `x` of `l` is repeated once for every element that it's a prefix of, which is exactly once for a prefix-free list, giving the original list. The prefix property is checked by zipping both lists with `x`, which cuts off elements beyond the length of `x`.

# Answer
> 9 votes
# Java, 128 127 126 125 124 121 bytes

### (Thanks @Kenny Lau, @Maltysen, @Patrick Roberts, @Joba)

```
Object a(String[]a){for(int i=0,j,l=a.length;i<l;i++)for(j=0;j<l;)if(i!=j&a[j++].startsWith(a[i]))return 1<0;return 1>0;}

```

### Ungolfed

```
Object a(String[] a) {
    for (int i = 0, j, l = a.length; i < l; i++)
        for (j = 0; j < l;)
            if (i != j & a[j++].startsWith(a[i])) return 1<0;
    return 1>0;
}

```

### Output

```
[Hello, World]
true

[Code, Golf, Is, Cool]
true

[1, 2, 3, 4, 5]
true

[This, test, case, is, true]
true

[111, 010, 000, 1101, 1010, 1000, 0111, 0010, 1011, 0110, 11001, 00110, 10011, 11000, 00111, 10010]
true

[4, 42]
false

[1, 2, 3, 34]
false

[This, test, case, is, false, t]
false

[He, said, Hello]
false

[0, 00, 00001]
false

[Duplicate, Duplicate, Keys, Keys]
false

```

# Answer
> 6 votes
## Python 2, 48 ~~51~~ bytes

```
lambda l:all(1/map(a.find,l).count(0)for a in l)

```

For each element `a` of `l`, the function `a.find` finds the index of the first occurrence of `a` in the input string, giving `-1` for an absence. So, `0` indicates a prefix. In a prefix-free list, mapping this function returns only a single `0` for `a` itself. The function checks that this is the case for every `a`.

---

**51 bytes:**

```
lambda l:[a for a in l for b in l if b<=a<b+'~']==l

```

Replace `~` with a character with ASCII code 128 or higher.

For each element `a` in `l`, a copy is included for each element that's a prefix of it. For a prefix-free list, the only such element is `a` itself, so this gives the original list.

# Answer
> 4 votes
# JavaScript ES6, ~~65~~ ~~43~~ 40 bytes

```
a=>!/(.*)\1/.test(''+a.sort().join``)
      ^            ^               ^ embedded NUL characters

```

My previous solution, which handled string arrays of all UTF-8 characters:

```
a=>!/[^\\]("([^"]*\\")*[^\\])",\1/.test(JSON.stringify(a.sort()))

```

I was able to avoid `JSON.stringify` since the challenge specifies printable ASCII characters only.

## Test

```
f=a=>!/(\0.*)\1/.test('\0'+a.sort().join`\0`) // since stackexchange removes embedded NUL characters

O.textContent += 'OK: '+
[["Hello", "World"]
,["Code", "Golf", "Is", "Cool"]
,["1", "2", "3", "4", "5"]
,["This", "test", "case", "is", "true"]
,["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
].map(a=>f(a))

O.textContent += '\nKO: '+
[["4", "42"]
,["1", "2", "3", "34"]
,["This", "test", "case", "is", "false", "t"]
,["He", "said", "Hello"]
,["0", "00", "00001"]
,["Duplicate", "Duplicate", "Keys", "Keys"]
].map(a=>f(a))
```

```
<pre id=O></pre>
```

# Answer
> 4 votes
## CJam, 14 bytes

```
q~$W%2ew::#0&!

```

Test suite.

### Explanation

```
q~   e# Read and evaluate input.
$    e# Sort strings. If a prefix exists it will end up directly in front
     e# of a string which contains it.
W%   e# Reverse list.
2ew  e# Get all consecutive pairs of strings.
::#  e# For each pair, find the first occurrence of the second string in the first.
     e# If a prefix exists that will result in a 0, otherwise in something non-zero.
0&   e# Set intersection with 0, yielding [0] for falsy cases and [] for truthy ones.
!    e# Logical NOT.

```

# Answer
> 3 votes
# Haskell, 49 bytes

```
g x=[1|z<-map((and.).zipWith(==))x<*>x,z]==(1<$x)

```

This has a couple parts:

```
-- Are two lists (or strings) equal for their first min(length_of_1,length_of_2) elements, i.e. is one the prefix of the other?
(and.).zipWith(==)

-- Check whether one element is the prefix of the other, for all pairs of elements (including equal pairs)
map((and.).zipWith(==))x<*>x

-- This is a list of 1's of length (number of elements that are the prefix of the other)
[1|z<-map((and.).zipWith(==))x<*>x,z]

-- This is the input list, with all the elements replaced with 1's
(1<$x)

```

If the two lists are equal, then an element is only the prefix of itself, and it's valid.

# Answer
> 3 votes
## Retina, 19 bytes

Byte count assumes ISO 8859-1 encoding.

```
O`.+
Mm1`^(.+)¶\1
0

```

The input should be linefeed-separated. Output is `0` for falsy and `1` for truthy.

Try it online! (Slightly modified to support multiple space-separated test cases instead.)

### Explanation

```
O`.+

```

Sort the lines in the input. If a prefix exists it will end up directly in front of a string which contains it.

```
Mm1`^(.+)¶\1

```

Try to match (`M`) a complete line which is also found at the beginning of the next line. The `m` activates multiline mode such that `^` matches line beginnings and the `1` ensures that we only count at most one match such that the output is `0` or `1`.

```
0

```

To swap `0` and `1` in the result, we count the number of `0`s.

# Answer
> 3 votes
# Java, 97 bytes

```
Object a(String[]a){for(String t:a)for(String e:a)if(t!=e&t.startsWith(e))return 1<0;return 1>0;}

```

Uses most of the tricks found in @Marv's answer, but also makes use of the foreach loop and string reference equality.

Unminified:

```
Object a(String[]a){
    for (String t : a)
        for (String e : a)
            if (t != e & t.startsWith(e))
                return 1<0;
    return 1>0;
}

```

Note that, as I said, this uses string reference equality. That does mean that the code can behave oddly due to String interning. The code does work when using arguments passed from the command line, and also when using something read from the command line. If you want to hardcode the values to test, though, you'd need to manually call the String constructor to force interning to not occur:

```
System.out.println(a(new String[] {new String("Hello"), new String("World")}));
System.out.println(a(new String[] {new String("Code"), new String("Golf"), new String("Is"), new String("Cool")}));
System.out.println(a(new String[] {new String("1"), new String("2"), new String("3"), new String("4"), new String("5")}));
System.out.println(a(new String[] {new String("This"), new String("test"), new String("case"), new String("is"), new String("true")}));
System.out.println(a(new String[] {new String("111"), new String("010"), new String("000"), new String("1101"), new String("1010"), new String("1000"), new String("0111"), new String("0010"), new String("1011"), new String("0110"), new String("11001"), new String("00110"), new String("10011"), new String("11000"), new String("00111"), new String("10010")}));
System.out.println(a(new String[] {new String("4"), new String("42")}));
System.out.println(a(new String[] {new String("1"), new String("2"), new String("3"), new String("34")}));
System.out.println(a(new String[] {new String("This"), new String("test"), new String("case"), new String("is"), new String("false"), new String("t")}));
System.out.println(a(new String[] {new String("He"), new String("said"), new String("Hello")}));
System.out.println(a(new String[] {new String("0"), new String("00"), new String("00001")}));
System.out.println(a(new String[] {new String("Duplicate"), new String("Duplicate"), new String("Keys"), new String("Keys")}));

```

# Answer
> 3 votes
# PostgreSQL, 186, 173 bytes

```
WITH y AS(SELECT * FROM t,LATERAL unnest(c)WITH ORDINALITY s(z,r))
SELECT y.c,EVERY(u.z IS NULL)
FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z||'%' GROUP BY y.c

```

Output:

No live demo this time. http://sqlfiddle.com supports only 9.3 and to run this demo 9.4 is required.

How it works:

1. Split string array with number and name it `y`
2. Get all y
3. `LEFT OUTER JOIN` to the same derived table based on the same `i`(id), but with different `oridinal` that start with prefix `y.z LIKE u.z||'%'`
4. Group result based on `c` (initial array) and use `EVERY` grouping function. If every row from second table `IS NULL` it means there is no prefixes.

---

Input if someone is interested:

```
CREATE TABLE t(i SERIAL,c text[]);

INSERT INTO t(c)
SELECT '{"Hello", "World"}'::text[]
UNION ALL SELECT  '{"Code", "Golf", "Is", "Cool"}'
UNION ALL SELECT  '{"1", "2", "3", "4", "5"}'
UNION ALL SELECT  '{"This", "test", "case", "is", "true"}'
UNION ALL SELECT  '{"111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011","0110", "11001", "00110", "10011", "11000", "00111", "10010"}'
UNION ALL SELECT  '{"4", "42"}'
UNION ALL SELECT  '{"1", "2", "3", "34"}'
UNION ALL SELECT  '{"This", "test", "case", "is", "false", "t"}'
UNION ALL SELECT  '{"He", "said", "Hello"}'
UNION ALL SELECT  '{"0", "00", "00001"}'
UNION ALL SELECT  '{"Duplicate", "Duplicate", "Keys", "Keys"}';

```

**EDIT:**

`SQL Server 2016+` implementation:

```
WITH y AS (SELECT *,z=value,r=ROW_NUMBER()OVER(ORDER BY 1/0) FROM #t CROSS APPLY STRING_SPLIT(c,','))
SELECT y.c, IIF(COUNT(u.z)>0,'F','T')
FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z+'%'
GROUP BY y.c;

```

`**`LiveDemo`**`

Note: It is comma separated list, not real array. But the main idea is the same as in `PostgreSQL`.

---

**EDIT 2:**

Actually `WITH ORDINALITY` could be replaced:

```
WITH y AS(SELECT *,ROW_NUMBER()OVER()r FROM t,LATERAL unnest(c)z)
SELECT y.c,EVERY(u.z IS NULL)
FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z||'%' GROUP BY y.c

```

`**`SqlFiddleDemo`**`

# Answer
> 3 votes
# Brachylog, 8 bytes

```
¬(⊇pa₀ᵈ)

```

Try it online!

Outputs through predicate success/failure. Takes more than 60 seconds on the last truthy test case `["111","010","000","1101","1010","1000","0111","0010","1011","0110","11001","00110","10011","11000","00111","10010"]` but passes it quickly with an added byte which eliminates a large number of possibilities earlier than the program does otherwise (`Ċ` before checking permutations rather than  after checking permutations, to limit the length of the sublist to two).

```
¬(     )    It cannot be shown that
   p        a permutation of
  ⊇         a sublist of the input
      ᵈ     is a pair of values [A,B] such that
    a₀      A is a prefix of B.

```

Less trivial 9-byte variants than `¬(⊇Ċpa₀ᵈ)` which run in reasonable time are `¬(⊇o₁a₀ᵈ)`, `¬(⊇o↔a₀ᵈ)`, and `¬(⊇oa₀ᵈ¹)`.

# Answer
> 3 votes
# Perl 6, 24 bytes

```
{.all.starts-with(.one)}

```

Try it online!

Wow, surprisingly short while using a long built-in.

### Explanation

```
{                      }  # Anonymous code block taking a list
 .all                     # Do all of the strings
     .starts-with(    )   # Start with
                  .one    # Only one other string (i.e. itself)

```

# Answer
> 1 votes
# Racket, 70 bytes

```
(λ(l)(andmap(λ(e)(not(ormap(curryr string-prefix? e)(remv e l))))l))

```

# Answer
> 1 votes
# JavaScript (ES6), 52 ~~54~~

**Edit** 2 bytes saved thx @Neil

```
a=>!a.some((w,i)=>a.some((v,j)=>i-j&&!w.indexOf(v)))

```

**Test**

```
f=a=>!a.some((w,i)=>a.some((v,j)=>i-j&&!w.indexOf(v)))

O.textContent += 'OK: '+
[["Hello", "World"]
,["Code", "Golf", "Is", "Cool"]
,["1", "2", "3", "4", "5"]
,["This", "test", "case", "is", "true"]
,["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
].map(a=>f(a))

O.textContent += '\nKO: '+
[["4", "42"]
,["1", "2", "3", "34"]
,["This", "test", "case", "is", "false", "t"]
,["He", "said", "Hello"]
,["0", "00", "00001"]
,["Duplicate", "Duplicate", "Keys", "Keys"]
].map(a=>f(a))
```

```
<pre id=O></pre>
```

# Answer
> 1 votes
# Mathematica ~~75 69~~ 68 bytes

Loquacious as usual. But Martin B was able to reduce the code by 7 bytes.

## Method 1: Storing output in an `Array`

(68 bytes)

```
f@a_:=!Or@@(Join@@Array[a~Drop~{#}~StringStartsQ~a[[#]]&,Length@a])

```

---

```
f@{"111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011", "0110", "11001", "00110", "10011", "11000", "00111", "10010"}

```

> True

---

```
f@{"He", "said", "Hello"}

```

> False

---

## Method 2: Storing output in a `List`

(69 bytes)

```
f@a_:=!Or@@Flatten[a~Drop~{#}~StringStartsQ~a[[#]]&/@Range@Length@a]

```

# Answer
> 1 votes
## Mathematica, 41 bytes

```
!Or@@StringStartsQ@@@Reverse@Sort@#~Subsets~{2}&

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 13 bytesSBCS

-2 bytes:

```
≢=∘≢∘⍸∘.(⊃⍷)⍨

```

Try it online!

Explanation:

```
≢=∘≢∘⍸∘.(⊃⍷)⍨  ⍝ Monadic function train
         ⍷     ⍝ "Find": Convert the right argument into a boolean vector,
               ⍝ where ones correspond to instances of the left argument
        ⊃     ⍝ Take the first item of the above vector (i.e., only prefixes)
     ∘.(  )⍨  ⍝ Commutative outer product: take the above function and apply
              ⍝ it for each possible pair of elements in the input
              ⍝ If the input is a prefix code, the above should have a number of ones
              ⍝ equal to the length of the input (i.e., each item is a prefix of only itself)
              ⍝ To test this...
     ⍸        ⍝ Find the location of all ones in the above
   ≢∘         ⍝ Take the length of the above
≢=∘           ⍝ Compare to the length of the input

```

# Answer
> 1 votes
# , 17 bytes

```
#=1#.1#.{.@E.&>/~

```

Try it online!

*Note: I actually wrote this before looking at the APL answer, to approach it without bias. Turns out the approaches are almost identical, which is interesting. I guess this is the natural "array thinknig" solution*

Take boxed input because the strings are of unequal length.

Create a self-function table `/~` of each element paired with each element and see if there is a match at the start `{.@E.`. This will produce a matrix of 1-0 results.

Sum it twice `1#.1#.` to get a single number representing "all ones in the matrix", and see if that number is the same as the length of the input `#=`. If it is, the only prefix matches are self matches, ie, we have a prefix code.

## sorting solution, 18 bytes

```
0=1#.2{.@E.&>/\/:~

```

Attempt at different approach. This solution sorts and looks at adjacent pairs.

Try it online!

# Answer
> 1 votes
# , 48 bytes

```
function(s)sum(outer(s,s,startsWith))==length(s)

```

Try it online!

Explanation: `outer(s,s,startsWith)` outputs a matrix of logicals checking whether `s[i]` is a prefix of `s[j]`. If `s` is a prefix code, then there are exactly `length(s)` TRUE elements in the result, corresponding to the diagonal elements (`s[i]` is a prefix of itself).

# Answer
> 0 votes
# Pyth - ~~13~~ 12 bytes

```
!ssmm}d._k-Q

```

Try it online here.

# Answer
> 0 votes
# Ruby, 48 bytes

Uses arguments as input and stdout as output.

```
p !$*.map{a,*b=$*.rotate!
a.start_with? *b}.any?

```

# Answer
> 0 votes
# Python, ~~58~~ 55 bytes

```
lambda l:sum(0==a.find(b)for a in l for b in l)==len(l)

```

# Answer
> 0 votes
# Scala, 71 bytes

```
(s:Seq[String])=>(for{x<-s;y<-s}yield x!=y&&x.startsWith(y)).forall(!_)

```

# Answer
> 0 votes
## Racket 130 bytes

```
(define g #t)(for((n(length l)))(for((i(length l))#:unless(= i n))(when(string-prefix?(list-ref l i)(list-ref l n))(set! g #f))))g

```

Ungolfed:

```
(define(f l)
  (define g #t)
  (for ((n (length l)))
    (for ((i (length l)) #:unless (= i n))
      (when (string-prefix? (list-ref l i) (list-ref l n))
        (set! g #f))))g)

```

Testing:

```
(f [list "Hello" "World"])
(f [list "Code" "Golf" "Is" "Cool"])
(f [list "1" "2" "3" "4" "5"])
(f [list "This" "test" "case" "is" "true"])
(f [list "111" "010" "000" "1101" "1010" "1000" "0111" "0010" "1011"
         "0110" "11001" "00110" "10011" "11000" "00111" "10010"])

(f [list "4" "42"])
(f [list "1" "2" "3" "34"])
(f [list "This" "test" "case" "is" "false" "t"])
(f [list "He" "said" "Hello"])
(f [list "0" "00" "00001"])
(f [list "Duplicate" "Duplicate" "Keys" "Keys"])

```

Output:

```
#t
#t
#t
#t
#t
#f
#f
#f
#f
#f
#f

```

# Answer
> 0 votes
# C (gcc), 93 bytes

```
p(r,e,f,i,x)char**r;{for(f=i=0;i<e;++i)for(x=0;x<e;++x)f|=x!=i&&strstr(r[i],r[x])==r[i];r=f;}

```

Try it online!

Simple double for loop using `strstr(a,b)==a` to check for prefices. Mainly added since there doesn't seem to be a C answer yet.

# Answer
> 0 votes
# Japt, 8 bytes

```
á2 ËrbÃe

```

Try it

```
á2 ËrbÃe     :Implicit input of array
á2           :Permutations of length 2
   Ë         :Map each pair
    r        :  Reduce by
     b       :  Get the index of the second in the first - 0 (falsey) if it's a prefix
      Ã      :End map
       e     :All truthy (-1 or >0)

```

# Answer
> 0 votes
# 05AB1E, 13 bytes

```
2.ÆDí«ε`Å?}O_

```

Too long.. Initially I had a 9-byte solution, but it failed for the duplicated key test case.

Try it online or verify all test cases.

**Explanation:**

```
2.Æ             # Get all combinations of two elements from the (implicit) input-list
   Dí           # Duplicate and reverse each pair
     «          # Merge the lists of pairs together
      ε         # Map each pair to:
       `        #  Push both strings to the stack
        Å?      #  And check if the first starts with the second
          }O    # After the map: sum to count all truthy values
            _   # And convert it to truthy if it's 0 or falsey if it's any other integer
                # (which is output implicitly as result)

```

# Answer
> 0 votes
## C# (Visual C# Interactive Compiler), 70 bytes

```
l=>!l.Any(x=>l.Where((y,i)=>l.IndexOf(x)!=i).Any(z=>z.StartsWith(x)));

```

Try it online!

# Answer
> 0 votes
# Stax, 6 bytes

```
å·↑↑¶Ω

```

Run and debug it

This produces non-zero for truthy.

The general idea is to consider every pair of strings in the input. If the substring index of one in the other is ever zero, then it's not a valid prefix code. In stax, index of a non-existing substring yields `-1`. This way, all the pair-wise substring indices can be multiplied together.

This is the same algorithm as isaacg's pyth solution, but I developed it independently.

---
Tags: code-golf, string, compression, decision-problem
---