# Question
Title: A long long time ago, in a galaxy ... right here
# Task

Given a positive integer return the geologic era and period it was that many million years ago.

## Input/output

The input is a string or integer; the output is a string. Eras and periods are separated by slashes (`/`). Input will always be between `0` and `542` inclusive

# Data

The possible outputs for eras and periods and their corresponding time periods (in millions of years) are:

* **Cenozoic** 0 - 66
    + **Quaternary** 0 - 3
    + **Neogene** 4 - 23
    + **Paleogene** 24 - 66
* **Mesozoic** 67 - 252
    + **Cretaceous** 67 - 145
    + **Jurassic** 146 - 201
    + **Triassic** 202 - 252
* **Paleozoic** 253 - 542
    + **Permian** 253 - 299
    + **Carboniferous** 300 - 359
    + **Devonian** 360 - 419
    + **Silurian** 420 - 444
    + **Ordovician** 445 - 485
    + **Cambrian** 486 - 542

Submissions will be scored by byte count. Lowest byte count wins.

# Test cases

```
314 -> Paleozoic/Carboniferous
0 -> Cenozoic/Quaternary
542 -> Paleozoic/Cambrian
100 -> Mesozoic/Cretaceous

```

# Answer
> 14 votes
# Befunge-93, 537 bytes

```
&:"C"`#v_"neC">,,,"/ciozo",,,,,,:4`#v_"auQ",,,"yranret">,,,,,,,@
*54+65:<   >  ^"Mes"_v#!`*+3          >#>#             ^#
 "leogene"<^"ale","P"<     v_v#`*64:<>        "enegoeN"^
,,,"Cre"< ^ ,,"Pa"_v#!`"C":< >       ^^"taceous"
`*2"e":_^#`*+*5545:<v_v#
 ,"T"_v#!`*+*543+65:< >"J","cissaru"  ^"riassic"
*"d"3:<v_v#!`
"rmian"< >:"x"3*`!#v_:"F"6*`#v_"D",v  ^"Pe"
"ous",,,,,,"Carbon"<         :        ^"ifer"
"enovian"                          <  ^
"brian","C"_v#`*"Q"6_v#`*"Y"5<        ^"am"
"an",,,"Ord"<        >"S","nairuli"   ^"ovici"

```

Try it online!

This is basically a giant `if/elsif/if` chain (or rather, two of them), one for the era, and one for the period.

# Answer
> 10 votes
# Jelly,  ~~74~~  73 bytes

```
“¥Þ+O83/<<ı)‘Ä>⁸Sµ:3»1;ị"“¥nq9r&t\“¥Ḅr¶4ḍẏżæœġẓÆ$Ụ>¬ḞḂṂĊƁÄ`zṚƥṀȯ4N»Ḳ€¤j”/

```

A monadic Link accepting number in \\$\[0,542\]\\$ which yields a list of characters (or a full program which prints the result).

**Try it online!**

### How?

```
“...‘Ä>⁸Sµ:3»1;ị"“...“...»Ḳ€¤j”/ - Link: integer, N        e.g. 100
“...‘                            - list of code page indices    [4,20,43,79,56,51,47,60,60,25,41]
     Ä                           - cumulative sums              [4,24,67,146,202,253,300,360,420,445,486]
      >⁸                         - greater than N?              [0,0,0,1,1,1,1,1,1,1,1]
        S                        - sum                          8
         µ                       - start a new monadic chain, call that X
          :3                     - integer divide (X) by 3      2
            »1                   - maximum of that and 1        2
              ;                  - concatenate with X           [2,8]
                            ¤    - nilad followed by link(s) as a nilad:
                 “...“...»       -   list of compressed strings ["Paleozoic Mesozoic Cenozoic","Ordovician Silurian Devonian Carboniferous Permian Triassic Jurassic Cretaceous Paleogene Neogene Quaternary Cambrian"]
                          Ḳ€     -   split each at spaces       [["Paleozoic","Mesozoic","Cenozoic"],["Ordovician","Silurian","Devonian","Carboniferous","Permian","Triassic","Jurassic","Cretaceous","Paleogene","Neogene","Quaternary","Cambrian"]
                "                - zip with:
               ị                 -   index into (modular)       ["Mesozoic","Cretaceous"]
                             j”/ - join with a '/'              "Mesozoic/Cretaceous"

```

# Answer
> 7 votes
# Java (JDK), 260 bytes

```
n->(n<67?"Cen":n<253?"Mes":"Pale")+"ozoic/"+"QuaternaryNeogenePaleogeneCretaceousJurassicTriassicPermianCarboniferousDevonianSilurianOrdovicianCambrian".split("(?=[A-Z])")[(n=java.util.Arrays.binarySearch("B‘ÉüīŧƣƼǥȞ".toCharArray(),(char)n))<0?~n:n]

```

Try it online!

* Contains invisible characters. The binary search String is actually: `"\u0003\u0017\u0042\u0091\u00c9\u00fc\u012b\u0167\u01a3\u01bc\u01e5\u021e"`.

# Answer
> 6 votes
# , 195 bytes

Assumes that input is 0-542, otherwise ~+7 bytes.

```
(Cen`Mes`Pale{~66 252&I.);@,'ozoic/';Quaternary`Neogene`Paleogene`Cretaceous`Jurassic`Triassic`Permian`Carboniferous`Devonian`Silurian`Ordovician`Cambrian{~(+/\3 20 43 79 56 51 47 60 60 25 41)I.]

```

Try it online!

# Answer
> 5 votes
# Python 3, <sup>~~273~~</sup> 264 bytes

```
lambda y:(['Cen']*67+['Mes']*186+['Pale']*290)[y]+'ozoic/'+(['Quaternary']*4+['Neogene']*20+['Paleogene']*43+['Cretaceous']*79+['Jurassic']*56+['Triassic']*51+['Permian']*47+['Carboniferous']*60+['Devonian']*60+['Silurian']*25+['Ordovician']*41+['Cambrian']*57)[y]

```

Try it online!

# Answer
> 4 votes
# JavaScript (Node.js),  ~~226~~  221 bytes

```
n=>(Buffer('!%5LpYTP]]:JZ').some(c=>(n-=c-34)<j++,j=1),a='CenMesPaleQuaternaryNeogenePaleogeneCretaceousJurassicTriassicPermianCarboniferousDevonianSilurianOrdovicianCambrian'.match(/.[a-z]+/g))[j>8?2:j/6|0]+'ozoic/'+a[j]

```

Try it online!

# Answer
> 4 votes
# Charcoal, 148 bytes

```
Ｎθ§⪪Cen Mes Pale¦ ⁺‹θ⁶⁷‹θ²⁵³ozoic§⪪”↶0s⟧↶'⪪Q⟧⪪⪫(cＩ‹qκyＱυ⌕↖↙″⁼R¤´⁵σι↙¡Ｚ⟧+]IΦc№M⁰$✂%¹νν⬤～[Ｚ⊕←⊘↖τF¤Ｈ>¹Sk◨ⅈγδ；§⟦⬤▶%↨Φ；{θi∕Ｎβ” ＬΦＩ⪪”)¶5″⁶vρ⁶Ｓ⊘l²Ｋκ～y”³‹ιθ

```

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

```
Ｎθ

```

Input the year.

```
§⪪Cen Mes Pale¦ ⁺‹θ⁶⁷‹θ²⁵³

```

Print one of the three era prefixes depending on the year.

```
ozoic

```

Print the era suffix.

```
§⪪”...” ＬΦＩ⪪”...”³‹ιθ

```

Extract the years that the periods end from a compressed list of padded years and count how many periods have ended before the input year and index into a compressed list of names of periods to print the current period. (Padding the years to three digits saves 4 bytes overall due to not needing any separators.)

# Answer
> 4 votes
# 05AB1E, ~~127~~ ~~125~~ 124 bytes

```
.•TćFh/>ytTOb•#ć«•Í‡,®ǝ₁êË2•80в.¥I›©₆12ªèOè.•Hα^B·´‘›∞ÕΣHÄ±[šyZÙΣpK5|´Ø·ëu"dw$мïjéåpºöÒ@’»©\I›¼ä^и9ΣßƒôƶI<Ægª6XyrмÏ•#®Oè'/ý™

```

Try it online or verify all test cases.

**Explanation:**

```
.•TćFh/>ytTOb• # Push compressed string "ozoic cen pale mes"
 #             # Split it on spaces: ["ozoic","cen","pale","mes"]
  ć            # Extract head; pop and push remainder-list and first item separated
   «           # Append this head to each item in the list:
               #  ["cenozoic","paleozoic","mesozoic"]
•Í‡,®ǝ₁êË2•    # Push compressed integer 3656627291841362083337
 80в           # Convert it to base-80 as list: [4,20,43,79,56,51,47,60,60,25,41,57]
    .¥         # Undelta this list: [0,4,24,67,146,202,253,300,360,420,445,486,543]
      I›       # Check for each whether it's larger than the input-integer
               # (1 if truthy; 0 if falsey)
        ©      # Store this list of checks in variable `®` (without popping)
₆              # Push builtin 36
 12ª           # Convert it to a list of digits, and append 12: [3,6,12]
    è          # Index those into the checks (to get those for [67,253,543])
     O         # Sum those checks to get the amount of truthy values
      è        # Index it into the string-list (modulair 0-based,
               # so 3 indexes into "cenozoic")
.•Hα^B·´‘›∞ÕΣHÄ±[šyZÙΣpK5|´Ø·ëu"dw$мïjéåpºöÒ@’»©\I›¼ä^и9ΣßƒôƶI<Ægª6XyrмÏ•
              "# Push compressed string "quaternary cambrian ordevician silurian devonian carboniferous permian triassic jurassic cretaceous paleogene neogene"
 #             # Split it on spaces: ["quaternary","cambrian","ordevician","silurian","devonian","carboniferous","permian","triassic","jurassic","cretaceous","paleogene","neogene"]
  ®            # Push the list of checks from variable `®`
   Oè          # Do the same as we did earlier
'/ý           '# Join the two words on the stack with "/" delimiter
   ™           # And titlecase both words in this string
               # (after which the result is output implicitly)

```

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

# Answer
> 3 votes
# APL (Dyalog Unicode) 18.0, 213 bytes

```
(0 4 24 67 146 202 253 300 360 420 445 486 543⍸⎕)⊃⊃,/1(⌷,¨↓)¨(9⍴4↑1)⊂(∊∘⎕A⊂⊢)'Cenozoic/QuaternaryNeogenePaleogeneMesozoic/CretaceousJurassicTriassicPaleozoic/PermianCarboniferousDevonianSilurianOrdovicianCambrian'

```

Try it online! (uses `c` as a polyfill for  since TIO has not upgraded to 18.0 yet)

# Answer
> 3 votes
# perl -pl, 270 251 bytes

```
@a=((Cenozoic)x67,(Mesozoic)x186,(Paleozoic)x290);@b=((Quaternary)x4,(Neogene)x20,(Paleogene)x43,(Cretaceous)x79,(Jurassic)x56,(Triassic)x51,(Permian)x47,(Carboniferous)x60,(Devonian)x60,(Silurian)x25,(Ordovician)x41,(Cambrian)x57);$_=$a[$_].$".$b[$_]

```

Try it online!

This creates two arrays with 543 elements each. Finding the era and period is then just a matter of indexing in the arrays.

Edit: The challenge was changed; we can now assume the input is between 0 and 542 inclusive. So we don't need to test the input anymore. And we don't require a slash between era and period either.

# Answer
> 3 votes
# JavaScript (Node.js), 339 bytes

```
f=(a)=>{g=(b,q,w)=>{for(i=0;;i++){if(a<q[i])return w[i]}}
x=[67,253,543]
y=['Cenozoic/','Mesozoic/','Paleozoic/']
n=[4,24,67,146,202,253,300,360,420,445,486,543]
m=['Quaternary','Neogene','Paleogene','Cretaceous','Jurassic','Triassic','Permian','Carboniferous','Devonian','Silurian','Ordovician','Cambrian']
console.log(g(a,x,y)+g(a,n,m))}

```

Try it online!

simplest solution to start golfing

# Answer
> 3 votes
# Whitespace, ~~1841~~ ~~1830~~ 1819 bytes

```

```

Try it online!
For some reason it doesn't work quite right on TIO, try it using the IDE I wrote it in, Whitelips

## Explanation

Since the only conditionals in whitespace are `jump-if-negative` and `jump-if-zero`, I figure out if the inputed number minus the number for the era plus one is negative, then jump to the respective label and push the era onto the stack. I then jump into a loop that prints the entire stack. (loops until it reaches a `-1`, which I push at the very start of the program.) I save repetive bytes by pushing "ogene" and then "Ne" or "Pale", "ozoic/" and then "Mes" or "Cen", etc.

# Answer
> 2 votes
# FEU, 268 bytes

```
u/x
m/x{486}x*/"Cambr#/x{445}x*/"Ordov%#/x{420}x*/"Silur#/x{360}x*/"Devon#/x{300}x*/"Carbonifer&/x{253}x*/"Perm#/x{202}x*/'Tri,/x{146}x*/'Jur,/x{67}x*/'Cretace&/x{24}x*/- 0/x{4}x*/-N0/x*/-Quaternary/0/eogene/-/Cen!/,/ass%/'/Mes!/&/ous/#/ian/"/ e!/!/ozo%\//%/ic/ /Pal/g

```

Try it online!

Basically just compression.

# Answer
> 2 votes
# Io, 417 bytes

Port of Noodle9's Python answer.

```
method(y,("Pale "repeated(67).."Mes "repeated(186).."Pale "repeated(290))split at(y).."ozoic/"..("Quaternary "repeated(4).."Neogene "repeated(20).."Paleogene "repeated(43).."Cretaceous "repeated(79).."Jurassic "repeated(56).."Triassic "repeated(51).."Permian "repeated(47).."Carboniferous "repeated(60).."Devonian "repeated(60).."Silurian "repeated(25).."Ordovician "repeated(41).."Cambrian "repeated(57))split at(y))

```

Try it online!

# Answer
> 2 votes
# PHP with -r, 261 bytes

Lots of ternary operators is the shortest solution I've found. Then golfed for some redundant suffixes. Only twice the amount of bytes needed to spell out each era uncompressed.

```
$a=$argv[1];echo($a<67?Cen:($a<253?Mes:Pale)).'ozoic/'.($a<4?Quarternary:($a<24?Neogene:($a<67?Paleogene:($a<146?Cretaceous:($a<202?Jurassic:($a<253?Triassic:($a<300?Permian:($a<360?Carboniferous:($a<420?Devon:($a<445?Silur:($a<486?Ordovic:Cambr))).ian))))))));

```

Try it online!

# Answer
> 2 votes
# Ruby, 317 bytes

```
->a{a<31?"Cenozoic/"+(a<4?"Quaternary":(a<24?"Neogene":(a<67?"Paleogene":""))):a<253?"Mesozoic/"+(a<146?"Cretaceous":(a<202?"Jurassic":(a<253?"Triassic":""))):a<543?"Paleozoic/"+(a<300===a ?"Permian":(a<360 ?"Carboniferous":(a<420?"Devonian":(a<445===a ?"Silurian":(a<486 ?"Ordovician": (a<543?"Cambrian":"")))))):""}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 235 bytes

```
67‹i’¦ì€¸zo¾ã/’™?¹4‹i’QuâìÒÇry’?ë¹₂Í‹i’ÖÌž¹’™?ë’æ§ož¹’™?}}ë¹253‹i’€á€Êzo¾ã/’™?¹145‹i’±ƒˆÆÁàÔºs’™?ë¹т·Ì‹i’JÒ¢í„¾ã’?ë’Æ×í„¾ã’™?}}ë’æ§¢äo¾ã/’™?¹3т*‹i’„œéên’™?ë¹₆T*‹i’®´€¬²¡Ôºs’™?ë¹420‹i’Ùç·‹’™?ë¹445‹i’¯ë„¹´€¤’™?ë¹486‹i’€—€·É²·‹’™?ë’§è¢°’™?

```

Try it online!

```
   i                                                         # if
                                                             # implicit input
67‹                                                          # is less than 67
                ?                                            # then output without trailing newline
    ’¦ì€¸zo¾ã/’™                                             # "Cenozoic/"
                    i                                        # if
                 ¹                                           # first item from input history
                  4‹                                         # is less than 4
                               ?                             # then output without trailing newline
                     ’QuâìÒÇry’                              # "Quaternary"
                                ë    i                       # elif
                                 ¹                           # first item from input history
                                    ‹                        # is less than
                                  ₂                          # 26
                                   Í                         # - 2 = 24
                                             ?               # then output without trailing newline
                                      ’ÖÌž¹’™                # "Neogene"
                                              ë              # else
                                                       ?     # output without trailing newline
                                               ’æ§ož¹’™      # "Paleogene"
                                                        }}   # end if statement (2x)
ë     i                                                      # elif
 ¹                                                           # first item from input history
  253‹                                                       # is less than 253
                   ?                                         # then output without trailing newline
       ’€á€Êzo¾ã/’™                                          # "Mesozoic/"
                         i                                   # if
                    ¹                                        # first item from input history
                     145‹                                    # is less than 145
                                      ?                      # then output without trailing newline
                          ’±ƒˆÆÁàÔºs’™                       # "Cretaceous"
                                       ë     i               # elif
                                        ¹                    # first item from input history
                                            ‹                # is less than
                                         т                   # 100
                                          ·                  # * 2 = 200
                                           Ì                 # + 2 = 202
                                                       ?     # then output without trailing newline
                                              ’JÒ¢í„¾ã’      # "Jurassic"
ë                                                            # else
          ?                                                  # output without trailing newline
 ’Æ×í„¾ã’™                                                   # "Triassic"
           }}                                                # end if statement (2x)
             ë                                               # else
                         ?                                   # output without trailing newline
              ’æ§¢äo¾ã/’™                                    # "Paleozoic"
                               i                             # if
                          ¹                                  # first item from input history
                              ‹                              # is less than
                           3т*                               # 3 * 100 = 300
                                        ?                    # then output without trailing newline
                                ’„œéên’™                     # "Permian"
                                         ë     i             # elif
                                          ¹                  # first item from input history
                                              ‹              # is less than
                                           ₆                 # 36
                                            T*               # * 10 = 360
                                                            ?# then output without trailing newline
                                                ’®´€¬²¡Ôºs’™ # "Carboniferous"
ë     i                                                      # elif
 ¹                                                           # first item from input history
  420‹                                                       # is less than 420
              ?                                              # then output without trailing newline
       ’Ùç·‹’™                                               # "Devonian"
               ë     i                                       # elif
                ¹                                            # first item from input history
                 445‹                                        # is less than 445
                                ?                            # then output without trailing newline
                      ’¯ë„¹´€¤’™                             # "Silurian"
                                 ë     i                     # elif
                                  ¹                          # first item from input history
                                   486‹                      # is less than 486
                                                   ?         # then output without trailing newline
                                        ’€—€·É²·‹’™          # "Ordovician"
                                                    ë        # else
                                                            ?# output without trailing newline
                                                     ’§è¢°’™ # "Cambrian"
                                                             # implicit end if statement (5x)

```

---
Tags: code-golf, kolmogorov-complexity, integer
---


title: Peel away the layers - Robbers

text:
# Question
Title: Peel away the layers - Robbers
This is the **Robbers** thread. For the Cops challenge, see here

As the robbers, your job is to crack the cops' answers. Choose an uncracked, unsafe cop answer and attempt to figure out which languages, in which order, the cop used.

Note that a crack is valid *even if the languages are different*. So long as the the languages you find, in the order you state them, produce the specified final phrase, the crack is valid, even if the languages are not the same as the intended or original cop answer.

If you are unable to fully crack a cop's answer and decide to abandon your attempt, you can (but are by no means expected to) comment underneath the cop's answer with the languages you've already figured out, in order to help other users.

Having fully cracked a cop's answer, post an answer to this thread listing all the languages, along with their outputs in the following format:

```
# [<cop>'s answer](<link to answer>), <N> layers

Languages used:
- Layer 1: [<language 1>](<link to interpreter>), outputted <output>
- Layer 2: [<language 2>](<link to interpreter>), outputted <output>
...
- Layer <N>: [<language N>](<link to interpreter>), outputted <final phrase>

---

<anything else>

```

After posting an answer, leave a comment below the cop's post to let them know it's been cracked. If you have \\$\<50\\$ reputation at the time of posting, and therefore cannot comment, I (or another able user) will be happy to do so for you, simply make a note of this in your answer and someone will take care of it.

This challenge can result in some very difficult answers to crack - more so than the standard - due to the fact that the number of languages a cop could've used increases exponentially per layer they have. Therefore, be sure to check out the Robbers' chatroom to get help cracking an answer, or to help others.

Your score is calculated the following way:

* If you crack \\$n\\$ answers, with \\$x\_1, x\_2, ..., x\_n\\$ languages being used (i.e. the first has \\$x\_1\\$ languages, the second \\$x\_2\\$ etc.), your score is

$$\frac{1}{n}\sum^n\_{i=1}x\_i$$

i.e. the total number of languages you cracked, divided by the total number of answers you cracked. The lower your score, the better. Don't bother editing your score into your answers, a winner will be declared when all cop answers are either cracked or safe.

Good luck!

# Answer
# Bubbler's answer, 3 layers

```
101;1111011;0000;11011111;{110000;11100010;11011110;00110;10111011;000110;10001;0100000;11011;000;11010101;0000010000;10100000;101101;0100000;1101111;0101111;}1001010;0000;100000;10110001;011001;011"00001101110100100010011001000;{111;011111;}1000\1101100;010110;110011;0\;110001;0111010;110010\10110;110001;0110000;\11011;0010;11001;011\11;0100000;11010100\;10110001;101110;1\001;001010;110111\0000;10110001;10\1011;0000;10100\000;0100110111\101101111111"@

```

Layer 1: Hexagony, outputted

```
echo'@',~;0j1":&.>10#.#:91 7 4 5 160 127 7 172 30 198

```

Layer 2: , outputted

```
1011011.0111.0100.0101.010100000.01111111.0111.010101100.011110.011000110.0@

```

Layer 3: Labyrinth, outputted

```
Code Golf.

```
> 6 votes

# Answer
# Sisyphus's Answer, 33 layers

```
i=496;a=     0
print('gREETINGS!'.swapcase()if a==447775else'i=%3s;a=%6s%s'%(i-16,a+(int(1/2*2)*int('syd0s6ncczl7ka1ioletm9t1atoqjq2awpshwfxcorai94tcmzim91j2zzq2c08wxjmfmzr0x9euhjojhltjpay0g8t1o78y83a',36)>>i&0xFFFF),open(__file__).read().strip()[14:]))

```

All layers are Python, in this order: 3, 3, 3, 3, 3, 2, 3, 3, 2, 2, 2, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2/3 (the last layer does not matter).

Special thanks to @Riolku for helping me find the right algorithm for subset sum (because I'm bad at computer science and Google)

Since there are so many layers, writing them all as a list would be rather difficult and take me a lot of time (and anyone who wants to verify it a ton of time), so instead you can verify it by running all 33 layers with this Bash program that compiles all of the layers together.

Let me know if this posting format is invalid.
> 10 votes

# Answer
# User's Answer, 3 layers

```
class Main:
  print(
"""class Main {public static void main(String[] args) {String a="ɗefine";char c=10;String z="pɼint";char d=23;String y="⁸fẇ×ịṛs⁷";String e="";char x=90;String b="⁺°`¬²ịĿ°£Oḋ®ẋṄ¢¦";String w="⁸Ḷ⁸Ŀ~ʋ^ḋ*Ẓ>{S";String i="return";String n=" ";String f="Game";String s="main";String t="def";String k="#";String u="ƈlass";String m="Іt'ѕ Dоnе.";String o="¨";String g="ƊƝƤƬƲȤɓ";
    if (""")
  print(((1 ^ (29 * -54) + 23 & 103) / 3))
  print(">")
  print(302 - 67 + (2 % 590) | 930 - 123 * (-169))
  print(""") {
      System.out.printf("73----T---|---111-T   T46%c      |     /     |   1%c 39-  1      %c    |   0%c/   %c 1       |   1   1%c|    -6      /    1   |%cL115----    |     0  /%c        %c   8     L76%c         3  6%c          2-J",10,10,92,10,92,10,10,10,92,10,10,10);
    } else if (""")
  print((65 % (59 - 20 * 24)) / -193 * 134)
  print(">")
  print((624 & 13 + 3012) / 23 * 9)
  print(""") {
      System.out.printf("%cm=%cIt's Done%c;print %c$m%c;", 36, 34, 34, 34, 34);
    } else if (""")
  print(12345 * 4 / 910 - 2 * 401)
  print(">")
  print((1 + 3 / 3) % (24 - 36 * 90))
  print(""") {
      System.out.printf("Flexibility speaks for yard%cairport announces all lies%cring a ring a rosie%ccaesars sat bad%csay %cIt's Done.%c%cAmerica is great",10,10,10,10,34,34,10,10);
    } else if (""")
  print((393 / 91 * 56) - 12 * 78 + 192)
  print(">")
  print(67 | -123 + 21 * 34 - 193)
  print(""") {
        System.out.printf("You are done%cSay %cIt's Done.%c(It really is that simple!!)",10,34,34);
    } else if (""")
  print(154 % 91 * 10 + 345 - 2)
  print(">")
  print(89 + -920 | 65 * 2 ^ 12)
  print(""") {
      System.out.printf("4@abƤḞ⁹%dỴ !Ṙȯ/ṣƥA^?rCs>Y|°ỵ4$m(0a+4r  /ZÐæ⁽e)D1ṖÐ,Ḅ Ḃ &ẉ1ɗḌ¢ġʋḞṬŒ$c “¢¤ƲgṖḳ®[⁾»",29,10,90,3,102,11,1234,95,666);
    } else if (""")
  print(10203 / 192 + 182)
  print(">")
  print(12 - 45 * 69 | 3)
  print(""") {
      System.out.println("YoucAnTryTofIguReoUtwHatThislaNgUagEiSButyOUwoNtBeaBleTobEcaUseiamToOpoWeRFulmWahAHaHaAnDhEreIssOmefilLeRteXtCOmmeNTcOmmeNtCommenTpRInTLpAreNcAPeitSiNGLeQsCaPeDonEdoTrpArencoMmEntCoMMentCoMMeNTfOOBaRyAbBaDabbadAbBAdOOcAnyOuFIndoUtTHEsEcREtBUrIEdINtHIsMEaNInGLeSStEXtNOYoUcaNTbEcaUseIhaVetHepOweRofNopUncTUatIoNandilItERaCYoNmySiDEbyeByePPl");
    } else {
      System.out.printf("%s"+e+"ẊD.%1$s",o);
    }
  }
}""")

def main(Main:Main):
  Main=Main

@main
def mian():
  Main=main(Main())

```

layer 1, Scala (with Dotty), Outputted

```
class Main {public static void main(String[] args) {String a="ɗefine";char c=10;String z="pɼint";char d=23;String y="⁸fẇ×ịṛs⁷";String e="";char x=90;String b="⁺°`¬²ịĿ°£Oḋ®ẋṄ¢¦";String w="⁸Ḷ⁸Ŀ~ʋ^ḋ*Ẓ>{S";String i="return";String n=" ";String f="Game";String s="main";String t="def";String k="#";String u="ƈlass";String m="Іt'ѕ Dоnе.";String o="¨";String g="ƊƝƤƬƲȤɓ";
    if (32>21757) {
      System.out.printf("73----T---|---111-T   T46%c      |     /     |   1%c 39-  1      %c    |   0%c/   %c 1       |   1   1%c|    -6      /    1   |%cL115----    |     0  /%c        %c   8     L76%c         3  6%c          2-J",10,10,92,10,92,10,10,10,92,10,10,10);
    } else if (0>225) {
      System.out.printf("%cm=%cIt's Done%c;print %c$m%c;", 36, 34, 34, 34, 34);
    } else if (-748>2) {
      System.out.printf("Flexibility speaks for yard%cairport announces all lies%cring a ring a rosie%ccaesars sat bad%csay %cIt's Done.%c%cAmerica is great",10,10,10,10,34,34,10,10);
    } else if (-520>463) {
        System.out.printf("You are done%cSay %cIt's Done.%c(It really is that simple!!)",10,34,34);
    } else if (973>-817) {
      System.out.printf("4@abƤḞ⁹%dỴ !Ṙȯ/ṣƥA^?rCs>Y|°ỵ4$m(0a+4r  /ZÐæ⁽e)D1ṖÐ,Ḅ Ḃ &ẉ1ɗḌ¢ġʋḞṬŒ$c “¢¤ƲgṖḳ®[⁾»",29,10,90,3,102,11,1234,95,666);
    } else if (235>-3093) {
      System.out.println("YoucAnTryTofIguReoUtwHatThislaNgUagEiSButyOUwoNtBeaBleTobEcaUseiamToOpoWeRFulmWahAHaHaAnDhEreIssOmefilLeRteXtCOmmeNTcOmmeNtCommenTpRInTLpAreNcAPeitSiNGLeQsCaPeDonEdoTrpArencoMmEntCoMMentCoMMeNTfOOBaRyAbBaDabbadAbBAdOOcAnyOuFIndoUtTHEsEcREtBUrIEdINtHIsMEaNInGLeSStEXtNOYoUcaNTbEcaUseIhaVetHepOweRofNopUncTUatIoNandilItERaCYoNmySiDEbyeByePPl");
    } else {
      System.out.printf("%s"+e+"ẊD.%1$s",o);
    }
  }
}

```

Layer 2, Groovy, Outputted

```
4@abƤḞ⁹29Ỵ !Ṙȯ/ṣƥA^?rCs>Y|°ỵ4Іt'ѕ Dоnе.(0a+4r  /ZÐæ⁽e)D1ṖÐ,Ḅ Ḃ &ẉ1ɗḌ¢ġʋḞṬŒ
 “¢¤ƲgṖḳ®[⁾»

```

Layer 3, Jelly, Outputted (for real this time)

```
Іt'ѕ Dоnе.

```
> 5 votes

# Answer
# Kevin Cruijssen's answer, 2 layers

```
,322,241,245,241,245,313,245,241,241,315,245,241,245,241,315,245,245,245,245,245,245,315,315,245,245,241,241,315,313,245,313,245,245,315,241,241,241,241,241,315,245,245,315,245,241,245,315,322,241,245,245,245,245,245,241,315

```

Layer 1: μ6, outputted

```
zaeaeueaaweaeaweeeeeewweeaawueueewaaaaaweeweaewzaeeeeeaw

```

Layer 2: evil, outputted

```
Greetings!

```
> 4 votes

# Answer
# Dion's Answer, 4 layers

Layer 1: MAWP 2.0, outputted

```
print('112;114;105;110;116;39;84;104;101;32;76;97;115;116;32;49;39;')

```

Layer 2: Python 3, outputted

```
112;114;105;110;116;39;84;104;101;32;76;97;115;116;32;49;39;

```

Layer 3: MAWP 2.0, outputted

```
print'The Last 1'

```

Layer 4: Python 2, outputted

```
The Last 1

```

---

You need to set the 'Max executions' to a high number on the online interpreter for the first one.
> 3 votes

# Answer
# Aiden4's answer, 3 layers

```
"D'`;#]8JIY4jEhw5uRQ+rpLo98*Z('D2CAdbx>+<)yxZpunsl2SRngfe+Lhg`_^$EaZ_^]V[TxXQ9UNrLQJOHMLEiCBAF?>=a;@?8=<54X876/4-Q10/o-&Jkj"75*1-"F&%edAbaw|{tyr8vuWVlkj0Qgfejib(`H^]#a`YA]\[TxXWP8TSLQJnHlkE-CHAeED&B;_?>=}|4Xy1U543s+O/o-&Jk)"75*1-"!&}C{c!x>|{zyxqY6Wsrqpi/mleMiha'HG]#a`_^W?[ZYRvPUTMqQJ2NMLKDhBG@?>b%;:?876;:3W10543,P0/on&J*)('&%${z@~w|uts9Zvutmlk1oQPfkd*bg`_%cbaCYX|\U=YXWPtT6RKoOHMFEi,HGF?DC<A:^>~6;4381Uv4-2+*Non&+*#Gh~}|{"75*1-"y?wvuzyr8vXWsl2ponmfN+Lbgfe^c\"75*1-"`Y^WVUySRWVOTMqQPONM/EiCHG@EDCB;_?>=}|49870/.R,1*N.n&%$Hi!EDC#zb~}|uts9Zpo5Vlkj0Qgfejib(`edc\"75*1-"`B^]VUTxXWP8Nr54PImML.DhHA@EDCB;_?>~<5Y9270Tu-,+Op.-&+$)"75*1-"Fg%|B"75*1-"!~wv<)"rooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo;

```

Layer 1: \>\<\>

```
D'`;#]8JIY4jEhw5uRQ+rpLo98*Z('D2CAdbx>+<)yxZpunsl2SRngfe+Lhg`_^$EaZ_^]V[TxXQ9UNrLQJOHMLEiCBAF?>=a;@?8=<54X876/4-Q10/o-&Jkj"F&%edAbaw|{tyr8vuWVlkj0Qgfejib(`H^]#a`YA]\[TxXWP8TSLQJnHlkE-CHAeED&B;_?>=}|4Xy1U543s+O/o-&Jk)"!&}C{c!x>|{zyxqY6Wsrqpi/mleMiha'HG]#a`_^W?[ZYRvPUTMqQJ2NMLKDhBG@?>b%;:?876;:3W10543,P0/on&J*)('&%${z@~w|uts9Zvutmlk1oQPfkd*bg`_%cbaCYX|\U=YXWPtT6RKoOHMFEi,HGF?DC<A:^>~6;4381Uv4-2+*Non&+*#Gh~}|{"y?wvuzyr8vXWsl2ponmfN+Lbgfe^c\"`Y^WVUySRWVOTMqQPONM/EiCHG@EDCB;_?>=}|49870/.R,1*N.n&%$Hi!EDC#zb~}|uts9Zpo5Vlkj0Qgfejib(`edc\"`B^]VUTxXWP8Nr54PImML.DhHA@EDCB;_?>~<5Y9270Tu-,+Op.-&+$)"Fg%|B"!~wv<)

```

Layer 2: Malbolge

```
macro_rules!f{($t:tt$i:ident$m:ident)=>{fn$i$t{$m!["The Last 1"]}}}f!{()main print}

```

Layer 3: Rust

```
The Last 1

```
> 3 votes

# Answer
# JosiahRyanW's Answer, 4 layers

```
"/-G^A_:;aT$e}qz\"7\"y^&'7T|-q3ZO@,]GN6==3g4U^Y)S_L7:fVp6_4'!s,a8IUK1[ Sp.)Ae)/P%ZY&D*K>j6feVfN1Fky,Vl2Z'?ie%\"<f,nv\\VS&T^e]5ZP}j!6/AivE` 0>9x<DdQL# kdzrz~sSO\"7[&U"{32-}%95base
3base{'
    '1/=}%

```

Layer 1: Golfscript, outputs:

```

```

Layer 2, Whitespace, outputs:

```
print" ".join("o"*int(c)for c in str(int("hevvbe0ammyi19tg9ubck4j315jnmd5y0ppsvgebn",36)))

```

Layer 3, Python 2, outputs:

```
ooo o o o oooooo o ooo o ooooo ooo ooo o oooooo oo oooo ooo oo ooo oo ooooo o oooo o oo oooooo oooooooo oooo oo ooooooo oooooo ooooo ooo o ooooooo ooooo o ooo ooo ooooooo ooo o ooooooo oooooo oo ooooooo oooooo o ooooooo ooooo oo ooooooo oooo ooo ooooooo ooooo o ooo o ooooooo ooooo ooo ooo oooo ooooooo

```

Layer 4, Poetic, outputs:

```
Code Golf.

```
> 2 votes

# Answer
# Quintec's Answer, 2 Layers

```
//"/pr/in/t('C/o/de /G/o/lf./')"#ec/ho/'C/o/d/e/ G/o/l/f/.'#con/sole/.l/og/('C/o/d/e/ G/o/l/f/.')#g))#:jd@#$%6a

```

Layer 1, Laser, outputs:

```
print('Code Golf.')

```

Layer 2, Python 3, outputs:

```
Code Golf.

```
> 2 votes

# Answer
# PkmnQ's Answer, 2 layers

```
printf("Code %s." % "Golf") # Python doesn't use printf?? (Of course I know what Python uses. (print))
# ^ The letter i. Superb letter. Seriously, it's one of the only two letters that can be a word by itself.

```

Layer 1: Underload, outputs:

```
print("Code %s." % "Golf")

```

Layer 2: Python 3, outputs:

```
Code Golf.

```
> 2 votes

---
Tags: kolmogorov-complexity, cops-and-robbers, code-generation, obfuscation
---


title: Alphabetically permute a string

text:
# Question
Title: Alphabetically permute a string
## Task

Your goal, should you choose to accept it, is to write a program, that, given an input string (or array of characters), outputs every possible permutation of the letters in that string. I'm finicky with my output, so it should be sorted alphabetically, with no duplicates.

**Example:**

Input: `buzz`

Output:

```
buzz
bzuz
bzzu
ubzz
uzbz
uzzb
zbuz
zbzu
zubz
zuzb
zzbu
zzub

```

## Rules

* This is so the shortest code wins.
* Trailing spaces on each/any line are ok
* A single newline after the last line is allowed (but no more)

# Answer
> 23 votes
# Jelly, 5 bytes

```
ṢŒ!QY

```

Try it online!

### Explanation

```
Ṣ         Sort
 Œ!       All permutations
   Q      Unique
    Y     Join by linefeeds

```

# Answer
> 12 votes
# 05AB1E,  ~~4~~  3 bytes

Updated, since an update to `œ` broke the old version,
which also saved a byte as suggested by *Magic Octopus Urn*.

```
œê»

```

Try it online!

**Explanation**

```
œ     # get all permutations of input
 ê    # sort and remove duplicates
  »   # join list by newlines

```

# Answer
> 10 votes
# MATL, 4 bytes

```
Y@Xu

```

Try it online!

### Explanation

```
Y@    % Implicit input. Push 2D array of all permutations, each on a row, sorted
Xu    % Unique rows. Implicitly display

```

# Answer
> 10 votes
# CJam, 5 bytes

*Thanks to @EriktheOutgolfer for a correction (`q` instead of `r`)*

```
qe!N*

```

Try it online!

### Explanation

```
q        e# Read input as a string
 e!      e# Unique permutations, sorted
   N*    e# Join by newline. Implicitly display

```

# Answer
> 10 votes
## Python 3.5, 79 bytes

```
def f(s,w=''):
 s or print(w)
 for c in sorted({*s}):t=s*1;t.remove(c);f(t,w+c)

```

A function that takes input as a list of characters and outputs by printing.

Recursively makes every distinct permutation by taking each possible next character alphabetically out of the remaining distinct characters, and appending it to the output in progress `w`. Then, we recurse with this character removed. Once the input is emptied, we print `w`.

# Answer
> 8 votes
# Pyth - 5 bytes

```
jS{.p

```

Try it online here.

```
j        Join. Implictly joins on newlines.
 S       Sort
  {      Uniquify
   .p    All permutations, implicitly run on input.

```

# Answer
> 6 votes
## Haskell, 46 bytes

```
import Data.List;unlines.sort.nub.permutations

```

2 bytes saved thanks to nimi

# Answer
> 5 votes
# J, 19 bytes

```
/:~@~.@:{~!@#A.&i.#

```

## Test case

```
   f =: /:~@~.@:{~!@#A.&i.#
   f 'buzz'
buzz
bzuz
bzzu
ubzz
uzbz
uzzb
zbuz
zbzu
zubz
zuzb
zzbu
zzub

```

## Explanation

This is a 4-train:

```
                     /- ~ --- /:
               /- @ -^- ~.
  /- ~ --- @: -^- {
  |
  |            /- !
--<     /- @ --^- #
  |     |
  \-----<      /- A.
        >- & --^- i.
        \- #

```

Basically:

```
/:~@~.@:{~!@#A.&i.#
          !  A.&     get permutations
           @#   i.#  of range (0..length)
        {~           map indices to chars in string
      @:             then
    ~.               unique
   @                 then
/:~                  sort

```

# Answer
> 4 votes
# JavaScript (Firefox 30+), ~~129~~ 124 bytes

```
f=(a,i=-1)=>a[1]?[for(x of a.sort())if(a.indexOf(x)==++i)f([...a.slice(0,i),...a.slice(i+1)]).replace(/^/gm,x)].join`
`:a[0]

```

Not too bad for a language with no permutation built-ins...

# Answer
> 3 votes
# Python 3.5, 81 bytes:

```
from itertools import*;lambda i:'\n'.join(sorted({*map(''.join,permutations(i))}))

```

Really...81 bytes when the next longest answer is 48 bytes...*sigh*. Well, I will try this golf this more as much as I can, but golfing tips are still very much appreciated.

Also, here is the shortest solution I could get in Python 2 at **86 bytes**:

```
from itertools import*;lambda f:'\n'.join(sorted({''.join(i)for i in permutations(f)}))

```

Apparently in Python 2, `[*...]` returns a `Syntax Error`, and since `permutations` returns `itertools.permutations object at 0x...`, the next shortest way (that I know) of extracting the *unique* permutations is using `{''.join(i)for i in permutations(f)}` where `f` is the input string.

Finally, note that these are both lambda functions and thus must be called in the format `print(<Function Name>(<Input String>))`.

# Answer
> 3 votes
# Brachylog, 9 bytes

```
:pfdo~@nw

```

Try it online!

### Explanation

```
:pf         Find all outputs of p - Permute with the main Input as input
   d        Remove Duplicates
    o       Order
     ~@n    Concatenate into a single string with linebreaks as separator
        w   Write to STDOUT

```

# Answer
> 3 votes
# Perl 6,  ~~49~~  44 bytes

String as input

```
*.comb.permutations.sort».join.squish.map: *.put

```

List of characters as input

```
*.permutations.sort».join.squish.map: *.put

```

# Expanded

```
*\              # Whatever lambda
# .comb\        # split into a list of characters
.permutations\  # returns a list of lists
.sort\
».join\         # join the second level lists
.squish\        # remove adjacent repeated values
.map: *.put     # print each on its own line

```

# Answer
> 3 votes
# Brachylog (v2), 5 bytes

```
pᵘoẉᵐ

```

Try it online!

Find nique `p`ermutations of input, s`o`rt them, ap riteln (write with newline) over that array.

# Answer
> 2 votes
# Mathematica, ~~34~~ 23 bytes

```
Print@@@Permutations@#&

```

The input must be a list of characters.

**Explanation**

```
Permutations@

```

Find all permutations of the input, sorted and duplicate-free.

```
Print@@@

```

Print them one by one.

# Answer
> 2 votes
# Python 3, ~~77~~ 85 bytes

Now sorts!

```
import itertools as i
for a in sorted(set(i.permutations(input()))):print("".join(a))

```

# Answer
> 2 votes
## PowerShell v3+, 171 bytes

```
param([char[]]$x)$a,$b=$x;$a=,$a;while($b){$z,$b=$b;$a+=$a|%{0..($y=($c="$_").Length)|%{-join($c[0..$_]+$z+$c[++$_..$y])};"$z$c";"$c$z"}}$a|?{$_.length-eq$x.count}|sort -u

```

PowerShell v3 introduced the `-Unique` flag on the `Sort-Object` cmdlet, so it's a few bytes shorter than the below v2 version, since we don't need to `Select` first.

v2 version, 178 bytes:

```
param([char[]]$x)$a,$b=$x;$a=,$a;while($b){$z,$b=$b;$a+=$a|%{0..($y=($c="$_").Length)|%{-join($c[0..$_]+$z+$c[++$_..$y])};"$z$c";"$c$z"}}$a|?{$_.length-eq$x.count}|select -u|sort

```

---

PowerShell doesn't have any built-in permutations, so I borrowed my code from Prime Factors Buddies and slightly tweaked it for use here.

This is essentially three portions, which I'll expand on below.

`param([char[]]$x)$a,$b=$x;$a=,$a` Takes input `$x`, casts it as a `char`-array, strips off the first letter into `$a` and the rest into `$b`, and then recasts `$a` as an array with the comma-operator.

`while($b){$z,$b=$b;$a+=$a|%{0..($y=($c="$_").Length)|%{-join($c[0..$_]+$z+$c[++$_..$y])};"$z$c";"$c$z"}}` Loops through the remaining letters (`$b`), each iteration taking the next letter and storing it into `$z` and leaving the remaining in `$b`, then array-concatenating onto `$a` the result of sending `$a` through its own loop -- each item of `$a` (temporarily stored into `$c`) is looped over its own `.length`, and then `$z` is inserted into every position, including prepending and appending with `$z$c` and `$c$z`. For example, for `$c = '12'` and `$z = '3'`, this will result in `'132','312','123'` being concatenated back into `$a`.

The final portion `$a|?{$_.length-eq$x.count}|select -u|sort` takes each element of `$a` and uses `Where-Object` clause to filter out only those that have the same length as the input string, then `select`s only the `-u`nique items, and finally `sort`s those alphabetically. The resulting strings are all left on the pipeline, and output via implicit `Write-Output` happens at program completion.

```
PS C:\Tools\Scripts\golfing> .\alphabetically-permute-a-string.ps1 'PPCG'
CGPP
CPGP
CPPG
GCPP
GPCP
GPPC
PCGP
PCPG
PGCP
PGPC
PPCG
PPGC

```

# Answer
> 2 votes
## JavaScript (ES6), 119 bytes

```
f=(s,t=[...s].sort().join``,p=``)=>t?t.replace(/./g,(c,i)=>t.indexOf(c)==i?f(s,t.slice(0,i)+t.slice(i+1),p+c):``):p+`\n`

```

Where `\n` represents the literal newline character. Port of @ETHproduction's answer to use strings instead of arrays. Reversing the output, or moving the trailing newline to the beginning, saves 3 bytes.

# Answer
> 1 votes
## R, 113 bytes

```
x=scan(,"");cat(sort(unique(apply(matrix(x[permute:::allPerms(l<-length(x))],,l),1,paste,collapse=""))),sep="\n")

```

Reads input from stdin. The `permute` package is assumed to be installed in order to call the `allPerms` function.

Will add an explanation as I get home from work.

# Answer
> 1 votes
# Java ~~302~~ 300 bytes

```
import java.util.*;class M{public static void main(String[]a){for(Object s:p(new TreeSet(),"",a[0]))System.out.println(s);}static Set p(Set l,String p,String s){int n=s.length(),i=0;if(n>1)for(;i<n;p(l,p+s.charAt(i),s.substring(0,i)+s.substring(++i,n)));else if(!l.contains(p+=s))l.add(p);return l;}}

```

**Ungolfed & test code:**

Try it here.

```
import java.util.*;
class M{
  static Set p(Set l, String p, String s){
    int n = s.length(),
        i = 0;
    if(n > 1){
      for(; i < n; p(l, p + s.charAt(i), s.substring(0, i) + s.substring(++i, n)));
    } else if(!l.contains(p+=s)){
      l.add(p);
    }
    return l;
  }

  public static void main(String[] a){
    for(Object s : p(new TreeSet(), "", a[0])){
      System.out.println(s);
    }
  }
}

```

**Input:** test
**Output:**

```
estt
etst
etts
sett
stet
stte
test
tets
tset
tste
ttes
ttse

```

# Answer
> 1 votes
## Racket 82 bytes

```
(sort(remove-duplicates(map list->string(permutations(string->list s)))) string<?)

```

Ungolfed:

```
(define(f s)
 (sort
  (remove-duplicates
   (map
    list->string
    (permutations
     (string->list s))))
  string<?))

```

Testing:

```
(f "buzz")

```

Ouput:

```
'("buzz" "bzuz" "bzzu" "ubzz" "uzbz" "uzzb" "zbuz" "zbzu" "zubz" "zuzb" "zzbu" "zzub")

```

# Answer
> 1 votes
# Husk, 3 bytes

```
uOP

```

Try it online!

No Unicode!

# Answer
> 0 votes
# Groovy, 69 Bytes

```
{(it as List).permutations().unique().sort().each{println it.join()}}

```

# Answer
> 0 votes
# Ruby, 51 bytes

```
->s{puts s.chars.permutation.map(&:join).uniq.sort}

```

# Answer
> 0 votes
# Actually, 8 bytes

Golfing suggestions welcome! Try it online!

```
;l@╨♂Σ╔i

```

**Ungolfing**

```
     Implicit input s.
;l   Get len(s).
@╨   Get all len(s)-length permutations of s.
♂Σ   Sum them all back into strings.
╔    uniq() the list of strings.
i    Flatten the list of strings.
     Implicit print the stack, separated by newlines.

```

# Answer
> 0 votes
## Pip, 8 bytes

7 bytes of code, +1 for `-n` flag.

```
SSUQPMa

```

Takes a string as a command-line argument. Try it online!

Pip's scanner breaks runs of uppercase letters into two-letter chunks. So this code is `SS UQ PM a`--i.e. `SortString(UniQue(PerMutations(a)))`, with `a` being the command-line arg. The `-n` flag ensures the result list is newline-separated. That's all there is to it.

# Answer
> 0 votes
# K (oK), 14 bytes

**Solution:**

```
?x@<x@:prm@#x:

```

Try it online!

**Explanation:**

Use the built-in permutation function, `prm`, to generate permutations of length of the input, apply these permutations to the input, sort alphabetically and then take distinct values.

```
?x@<x@:prm@#x: / the solution
            x: / store input as x
           #   / count length of x
       prm@    / apply (@) function prm
    x@:        / apply indices to x and save result back into x
   <           / indices to sort ascending
 x@            / apply to x
?              / take distint

```

# Answer
> 0 votes
# Japt v2.0a0 `-R`, 5 bytes

```
á â n

```

Try it

# Answer
> 0 votes
# Perl 5 `-MList::Util=uniq -F`, 68 bytes

```
$"=',';@b=sort@F;map{say if"@b"eq join$",sort/./g}uniq glob"{@b}"x@b

```

Try it online!

# Answer
> 0 votes
# C++ (gcc), ~~132~~ 128 bytes

```
#include<bits/stdc++.h>
using namespace std;int main(){string s;for(cin>>s;cout<<s<<endl,next_permutation(s.begin(),s.end()););}

```

Try it online!

# Answer
> 0 votes
# Clam, 9 bytes

```
p_D`Sq@~Q

```

## Explanation

```
          - Implicit Q = first input
p         - Print...
 _        - Sorted ascending value (alphabetical order)
  D       - Distinct from...
   `Sq    - Joined (map(q=>q.join(""))
      @~Q - Permutations of Q

```

---
Tags: code-golf, string, permutations
---


# Question
Title: Bijection between binary strings and pairs thereof
**Input**: Either one or two strings consisting of `'0'`s and `'1'`s. If there are 2, they are separated by a space. All strings are of length at least 1.

**Output**:

* If a single input was given as input, 2 are output.
* If 2 were input, 1 is output.

The output strings can be whatever you like, but if running your program with input A gives you B, then running it with B must give A (if inputting `111 11` gives `00000`, then inputting `00000` must give `111 11`).

That means if you pipe your program to itself, you should get back whatever you input. If your program is called `foo`, you can test that like this:

```
>echo 101 101|foo|foo
101 101

```

To prevent the use of brute force techniques, your code should be able to run with 1000 digit strings in under 10 seconds. My Python solution for this takes less than 1 second on 10000 digit strings so this shouldn't be a problem.

Shortest code wins.

# Answer
> 3 votes
## Python, 183

Bijection is cached on disk.

```
x=raw_input()
try:d=eval(open('d').read())
except:d={'':'','1 ':'1 '}
t='1 '*not' 'in x
if x not in d:
 while t in d:t+=`(id(t)/9)%2`
 d[t]=x;d[x]=t
 open(*'dw').write(`d`)
print d[x]

```

edit: Oops, looks like this isn't the first smartassed answer. Mine's consistent between runs!

# Answer
> 2 votes
# Python, 326

```
s=lambda i,l:bin(i)[2:].zfill(l)
f=lambda n:2**n*(n-3)+4
g=lambda n:2**n-2
i=raw_input()
if' 'in i:
 a,b=i.split();n=len(a+b);r=f(n)+int(a+b,2)*(n-1)+len(a)-1;l=1
 while g(l+1)<=r:l+=1
 print s(r-g(l),l)
else:
 n=len(i);r=g(n)+int(i,2);l=2
 while f(l+1)<=r:l+=1
 r-=f(l);p=r%(l-1)+1;w=s(r/(l-1),l);print w[:p],w[p:]

```

Example inputs/outputs:

```
     input | output
-----------+-----------
         0 | 0 0
       0 0 | 0
     10 10 | 10101
     10101 | 10 10
0000000000 | 101 0100
  101 0100 | 0000000000

```

# Answer
> 2 votes
### Perl 5, 197 characters

```
sub n{'0'x$_[0].sprintf'%b',$_[1]}sub N{/0*(?=.)/;length$&,oct"0b$'"}$_=<>;print/ /?n map{($a,$b)=N;($a+$b)*($a+$b+1)/2+$b}split:"@{[map{$w=int((sqrt(8*$_+1)-1)/2);$y=$_-($w*$w+$w)/2;n$w-$y,$y}N]}"

```

With some line breaks:

```
sub n{'0'x$_[0].sprintf'%b',$_[1]}
sub N{/0*(?=.)/;length$&,oct"0b$'"}
$_=<>;print/ /?n map{
  ($a,$b)=N;($a+$b)*($a+$b+1)/2+$b
}split:"@{[map{
  $w=int((sqrt(8*$_+1)-1)/2);$y=$_-($w*$w+$w)/2;n$w-$y,$y
}N]}"

```

This program operates by composing two bijections:

* A pair of natural numbers may be mapped to a binary string by converting one to a base-2 number and the other to extraneous leading zeroes. `n` is this function and `N` is its inverse (except that `N` uses `$_` as its parameter).
* A pair of natural numbers may be mapped to a single natural number using the Cantor pairing function. The first `map`'s block is this function and the second is its inverse.

Thus two binary strings are split into four numbers, combined into two numbers, and then combined into one binary string — or vice versa.

Tested on 100 random inputs of each type with strings up to 8 symbols long. I've been finding lots of ways to make this a little bit shorter, but I'm going to stop and post it. If there's room to optimize further, it's probably in the arithmetic expressions.

# Answer
> 1 votes
## Perl, 56 chars

added +1 char for `-p` command line switch

```
$s.=1;$h{$h{$_}||=(split>1?$s:"$s $s").$/}=$_;$_=$h{$_}

```

# Answer
> 1 votes
# , 209 bytes

*Note that this code will fail for numbers outside 's native numeric range; the approach should be valid for any number, though, and this could be solved using arbitrary-precision calculations (for instance, with the  GMP library).*

```
function(x,z=2^nchar(x)+strtoi(x,2)-1,s=function(v,l=log2(v+1)%/%1)paste((v+1)%/%2^(l:1-1)%%2,collapse=''),d=sum(cumsum(0:z)<z),y=z-sum(0:(d-1)))`if`(length(x)>1,s(sum(0:(sum(z)-2))+z[2]),sapply(c(d+1-y,y),s))

```

Try it online!

**How does it work?**

First, we convert each string `x` of `0`s & `1`s into an integer value `z`, corresponding to its lexicographical index. The code for this is:

```
z=2^nchar(x)+strtoi(x,2)-1

```

And at the end of the bijection, we'll convert this back to a string using the opposite function:

```
s=function(v,l=log2(v+1)%/%1)paste((v+1)%/%2^(l:1-1)%%2,collapse='')

```

Using this scheme, the following strings correspond to the integer values `1` to `20`:

```
sapply(1:20,string)
 [1] "0"    "1"    "00"   "01"   "10"   "11"   "000"  "001"  "010"  "011"
[10] "100"  "101"  "110"  "111"  "0000" "0001" "0010" "0011" "0100" "0101"

```

Now, to get a single number from a pair of numbers, we consider each number pair to be `x` and `y` coordinates of a grid, and we sequentially number each position in the grid by moving along the diagonals (so the linear sequence gradually fills the two-dimensional space): This function calculates the number for each pair of coordinates:

```
num=function(c)sum(0:(sum(c)-2))+c[2]

```

Which leads to the following mapping:

```
matrix(apply(which(matrix(T,6,6),T),1,num),6,6)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    3    6   10   15   21
[2,]    2    5    9   14   20   27
[3,]    4    8   13   19   26   34
[4,]    7   12   18   25   33   42
[5,]   11   17   24   32   41   51
[6,]   16   23   31   40   50   61

```

The 'bijection' function just rolls all these steps together.

# Answer
> 0 votes
# Python, 394

I'm sure this can be golfed further, but this monolith uses the Cantor Pairing Function and its inverse.

```
import math
s=lambda n:n*(n+1)/2
p=lambda a:'0'*a[0]+bin(a[1])[2:]
q=lambda t:t.index('1')
B=raw_input().split()
def f(x,y):r=x+y+1;return s(r)-[y,x][r%2]-1
def g(z):r=int(math.ceil((2*(z+1)+1/4.)**(1/2.)-1/2.))-1;d=s(r+1)-z-1;return [(d,r-d),(r-d,d)][r%2]
if len(B)<2:a=[g(q(B[0])),g(int(B[0],2))];print p(a[0])+' '+p(a[1])
else:print p([f(q(B[0]),int(B[0],2)),f(q(B[1]),int(B[1],2))])

```

# Explanation

There is a natural association between a binary string and a pair of natural numbers: the first number of the image is the number of leading zeros, and the second is the integer value of the binary number. Knowing that we have:

`S ~ N^2`

and with the Cantor bijection

`N ~ N^2`

therefore:

`S ~ N^2 ~ N^4 ~ S^2`

`S ~ S^2`

Where S is set of all binary strings. This solution implements the bijection between S and S^2.

---
Tags: code-golf, math, number-theory, open-ended-function
---


title: Clark's Triangle

text:
# Question
Title: Clark's Triangle
Ok I've been on a bit of a triangle kick recently so here's another one.

Clark's Triangle is a triangle where the leftmost entry of each row is 1 and the rightmost entries are made up of multiples of 6 which increase as the row number increases. Here's a visualization

```
     1 6
    1 . 12
   1 . . 18
  1 . . . 24
 1 . . . . 30
1 . . . . . 36

```

Just like Pascal's Triangle all other entries are the sum of the numbers to their upper right and upper left.

Here are the first few rows filled in

```
          1   6
        1   7  12
      1   8  19  18
    1   9  27  37  24
  1  10  36  64  61  30
1  11  46  100 125 91  36

```

# Task

Given a row number (starting from the top) and an column number (starting from the first non-zero item on that row) output the value at that particular cell. Both inputs may be either 1 or 0 indexed (you may mix and match if you desire). Out of the bounds of the triangle is undefined and you may do whatever you wish when queried for these values.

This is , the goal is to minimize the number of bytes in your solution.

OEIS A046902

# Answer
# Pascal, 132 bytes

```
function f(n,k:integer):integer;begin if k=1 then f:=1 else if k>n then f:=6*n else if k<0 then f:=0 else f:=f(n-1,k-1)+f(n-1,k)end;

```

Try it online!

1-indexed.
> 7 votes

# Answer
# MATL, 15 bytes

```
[lBB]i:"TTY+]i)

```

First input is 0-based row; second is 1-based column.

**Try it online!**

### Explanation

```
[lBB]   % Push [1 6 6]
i       % Input: row number (0-based)
:"      % Repeat that many times
  TT    %   Push [1 1]
  Y+    %   Convolution, increasing size. This computes the sum of overlapping
        %   pairs, including the endpoints. So for example [1 6 6] becomes
        %   [1 7 12 6], which will later become [1 8 19 18 6], ...
]       % End
i       % Input: column number (1-based)
)       % Use as index. Implicit display

```
> 7 votes

# Answer
# CJam, ~~22~~ 18 bytes

*-4 bytes thanks to Martin Ender*

```
X6_]ri{0X$+.+}*ri=

```

Input is `(0-based row) (0-based column)`

Try it online!

### Explanation

```
X6_]  e# Push the list [1 6 6]. This is the first row, but each row will have an extra 6 at
      e# the end, which is out of bounds.
ri    e# Push the first input as an integer.
{     e# The following block calculates the next row given a row on top of the stack:
 0X$+ e#  Copy the top list on the stack and prepend 0.
 .+   e#  Element-wise addition with the list before prepending 0. This adds each element of
      e#  with the one to its left, except the initial 1 gets added to 0 and the final number
      e#  gets added to the out-of-bounds 6. The out-of-bounds 6 is unchanged since one list
      e#  is longer.
}*    e# Run this block (row index) times.
ri=   e# Get the (column index)th item of the final list.

```
> 5 votes

# Answer
# C#, 157 bytes

```
using System.Linq;(b,c)=>{var f=new[]{1,6};for(;c>0;c--){int s=f.Length;f=new int[s+1].Select((e,i)=>i<1?1:i==s?f[s-1]+6:f[i-1]+f[i]).ToArray();}return f[b];

```

Try it online
> 4 votes

# Answer
# Python 2, 67 bytes

```
a,b=input()
x=[1,6]
exec"x=map(sum,zip([0]+x,x+[6]));"*a
print x[b]

```

Try it online!

Brute-force approach, calculate the `a`th row, and then print the `b`th number, both inputs are 0-based
> 3 votes

# Answer
# Python 3, ~~64~~ ~~60~~ 52 bytes

```
f=lambda r,c:c<2or c>r and r*6or f(r-1,c-1)+f(r-1,c)

```

Try it online!

Recursive solution using 1-indexing. Outputs "True" instead of 1 for the sake of golfing.

---

**Thanks to:**

* @totallyhuman for saving 4 bytes!
* @Rod for saving 8 bytes!
> 3 votes

# Answer
# Haskell, 41 bytes

```
n#1=1
n#m|m>n=6*n
n#m=(n-1)#(m-1)+(n-1)#m

```

Try it online!

Call using `n # m` where `n` is the row number and `m` is the column number, both 1-indexed.
> 3 votes

# Answer
# Husk, ~~15~~ 12 bytes

```
!!¡S`JẊ+d166

```

Try it online!

-3 bytes from Dominic Van Essen.

Same method as the MATL answer, except it uses an infinite list of rows of Clark's triangle.
> 3 votes

# Answer
# Mathematica, 32 bytes

```
b=Binomial;b[#,#2-1]6+b[#-1,#2]&

```

input

> \[row,column\]
> \[1-indexed,0-indexed\]
> 2 votes

# Answer
# Haskell, ~~40~~ 36 bytes

*Thanks to Lynn for pointing out the obvious and saving me 4 bytes.*

```
n#1=1
n#m|m>n=6*n|q<-n-1=q#(m-1)+q#m

```

Try it online!

---

Works like this answer but ~~1 byte~~ 5 bytes shorter.
> 2 votes

# Answer
# K (oK), ~~28~~ 18 bytes

```
{(x{+':x,6}/1 6)y}

```

Try it online!

Rows and columns are both 0-indexed. Out of bounds return null.
> 2 votes

# Answer
# Scala, 75 bytes - Brute-force solution

```
n=>k=>2.to(n)./:(Seq(1,6))((s,i)=>1+:s.sliding(2).map(_.sum).toSeq:+6*i)(k)

```

Try it online!

# Scala, 88 bytes - Recursive solution

```
n=>k=>{def g(m:Int,l:Int):Int=if(m==l)m*6 else if(l<1)1 else g(m-1,l-1)+g(m-1,l)
g(n,k)}

```

Try it online!
> 2 votes

# Answer
# Desmos, ~~118~~ ~~71~~ 55 bytes

Saved a whopping 47 bytes thanks to **@ovs**!

\\$f(r,c)=\sum\_{k=c-2}^c(6-5\*0^{c-k})/k!\prod\_{n=r-k+1}^rn\\$

```
f(r,c)=\sum_{k=c-2}^c(6-5*0^{c-k})/k!\prod_{n=r-k+1}^rn

```

Both the row and column are 0-indexed.
> 2 votes

# Answer
# PHP, 64 bytes

recursive function

rows 1-indexing columns 0-indexing

Output for row=0 and column=0 is 0 like in the OEIS sequence

```
function f($r,$c){return$c-$r?$c?f($r-=1,$c-1)+f($r,$c):1:$r*6;}

```

Try it online!

# PHP, 126 bytes

rows 1-indexing columns 0-indexing

Output for row=0 and column=0 is 0 like in the OEIS sequence

```
for(;$r<=$argv[1];$r++)for($z++,$c=~0;++$c<$z;)$t[+$r][$c]=$c<$r?$c?$t[$r-1][$c-1]+$t[$r-1][$c]:1:$r*6;echo$t[$r-1][$argv[2]];

```

Try it online!
> 1 votes

# Answer
# , 77 bytes

```
Reduce(function(x,y)zoo::rollsum(c(0,x,6),2),double(scan()-1),c(1,6))[scan()]

```

Requires the `zoo` library; reads from stdin (the inputs separated by two newlines) and returns the value, with `NA` for out of bounds selections.

Try it online!
> 1 votes

# Answer
## JavaScript (ES6), 38 bytes

```
f=(r,c)=>c?r>c?f(--r,c)+f(r,--c):r*6:1

```

Crashes for negative columns, and returns multiples of six for negative rows or overlarge columns.
> 1 votes

# Answer
# C# (.NET Core), 44 bytes

```
f=(c,r)=>c<=1?1:c>r?6*r:f(c-1,r-1)+f(c,r-1);

```

Takes column then row, both 1-indexed. Can take row then column by swapping the inputs: `(r,c)`. Will return `row * 6` for coordinates outside the bounds on the right (i.e. `column > row + 1`), and `1` for coordinates outside the bounds on the left (i.e. `column < 1`).
> 1 votes

# Answer
# Jelly, 13 bytes

```
,"’U0¦c/x6,1S

```

A monadic link taking a list of `[row, entry]` (0-indexing for entries, 1-indexing for rows), returning the value.

**Try it online!**

### How?

```
,"’U0¦c/x6,1S - Link: list of numbers, [row, entry]
  ’           - decrement     -> [row-1, entry-1]
 "            - zip with:
,             -   pair        -> [[row, row-1], [entry, entry-1]]
     ¦        - sparse application of:
   U          -   upend
    0         - for indexes: 0 -> [[row, row-1], [entry-1, entry]]
       /      - reduce by:
      c       -   choose       -> [(row choose entry-1), (row-1 choose entry)]
         6,1  - 6 paired with 1 = [6,1]
        x     - times        i.e. [a, a, a, a, a, a, a, b]
            S - sum            -> 6*(row choose entry-1) + (row-1 choose entry)

```
> 1 votes

---
Tags: code-golf, math, number
---


title: Pseudo-deterministic number generator

text:
# Question
Title: Pseudo-deterministic number generator
# Task

Write a function/full program that will be able to produce two different sequences of integers in `[0, ..., 9]`. You will take an input `seed` to decide whether to output your `s`pecific sequence or the `c`ommon one. For that matter, you must choose one non-negative integer, let us call it `k`. When the input `seed` is equal to `k`, you will be dealing with your specific sequence `s`; when the input `seed` is anything else, you will be dealing with your common sequence `c`.

Both sequences should be such that the relative frequencies with which each digit appears tend to \\$10\\%\\$. Be prepared to prove this if needed. Said another way, the running fraction of that digit's appearances needs to have a defined limit that equals \\$0.1\\$. Formally, this means that for every \\$d \in \\{0,...,9\\}\\$,

$$\lim\_{n\rightarrow \infty}\dfrac{\left|\\{i : i \in \\{1\dots n\\}, s\_i=d\\}\right|}{n} = 0.1$$

*Adapted from What an Odd Function*

There should be one extra restriction your sequences should satisfy: when zipped together\* to form a sequence `a` of terms in `[0, ..., 99]`, the relative frequency of each number should converge to `0.01` via a limit like the formula above.

\*That is, the \\$n\\$th term of the sequence `a` is the two-digit number built this way: the digit in the tens place is the \\$n\\$th term of the sequence `c` and the digit in the units place is the \\$n\\$th term of the sequence `s`.

# Input

A non-negative integer representing the "seed", which you use to decide whether to output the common sequence or the specific one.

# Output

Your output may be one of the following:

* an infinite stream with the sequence (and you take no additional input);
* output the `n`th term of the sequence (by taking an additional input `n` that is `0`\- or `1`-indexed);
* output the first `n` terms of the sequence (by taking an additional positive input `n`).

# Example pseudo-algorithm

Assuming I have defined `seed` as an integer, and for these choices I made for `s` and `c`:

```
input_seed ← input()
n ← input()
if input_seed = seed: print (n mod 10) # this is my sequence s
else: print ((integer div of n by 10) mod 10) # this is my sequence c

```

Both sequences output numbers in `[0, ..., 9]` and the frequency with which each digit appears tends to `0.1` as `n → infinity`. Similarly, zipping `c` and `s` together gives `n mod 100` so it is also true that as `n → infinity` we have that the relative frequency with which each number in `[0, ..., 99]` shows up goes to `0.01`.

# Answer
# Python 2, ~~23~~ 22 bytes

*Thanks @xnor for figuring out a really cool way to convert the seed to `-1` or `-2`, which saved 1 byte.*

```
lambda s,n:`n+9`[2/~s]

```

Try it online!

**Input**: The seed `s` (non-negative) and an index `n` (positive).
**Output**: The element at the nth index (the sequence is one-indexed)

If the seed is positive, the sequence is `0123456789` repeated infinitely.
If the seed is `0`, the sequence is: `1111111111 2222222222 ... 9999999999 0000000000` (where each digit repeats 10 times) repeated infinitely.

**How**

* ``n+9`` creates a string from a number that has at least 2 digits.
* `2/~s` evaluates to -2 if `s` is 0, or -1 if `s` is positive
* Thus ``n+9`[2/~s]` takes the last digit (unit digit) of \\$n+9\\$ if `s` is positive, or the second to last digit (ten digit) if `s` is 0.
> 9 votes

# Answer
# 05AB1E,  ~~4~~  3 bytes

```
ΘÍè

```

Try it online!

Takes the seed then n and outputs the nth term, outputs different sequence for seed of 1

---

## Explanation

```
Θ                  - truthified (so 1 if input is 1, else 0)
 Í                 - subtract 2 (so -1 if input is 1, else -2)
  è                - take this index of the nth term

```

Since 05AB1E uses modular indexing it won't go out of bounds, and `a[-1]` is the last element of a. Likewise `a[-2]` is the penultimate.

---

Alternatively to output an infinite sequence.

### 05AB1E, 6 bytes

```
∞εIΘÍè

```

Try it online!
> 5 votes

# Answer
# C (gcc), 24 bytes

```
f(s,n){s=(s?n/10:n)%10;}

```

Try it online!

***Input***: seed (\\$s\\$) and \\$n\\$.
***Output***: \\$n^{\text{th}}\\$ term zero-indexed.

For \\$s=0\\$ the sequence is: \\$0,1,2,\dots,9,\dots\\$
For \\$s\>0\\$ the sequence is: \\$\underbrace{0,0,\dots,0}\_{10},\underbrace{1,1,\dots,1}\_{10},\underbrace{ 2,2,\dots,2}\_{10},\dots,\underbrace{9,9,\dots ,9}\_{10},\dots\\$
> 5 votes

# Answer
# Wolfram Language (Mathematica), 38 bytes

Takes Input \[n,seed\] and outputs nth term
Specific seed is 0

```
If[#2>0,#~Mod~10,Floor[#~Mod~100/10]]&

```

Try it online!
> 4 votes

# Answer
# Charcoal, ~~9~~ 5 bytes

```
§Ｓ⊕¬Ｎ

```

Try it online! Link is to verbose version of code. Takes input as `n`, `s` and outputs the (1-indexed) third digit of `n` if `s` is zero otherwise the second digit of `n` (so somewhat similar to @ExpiredData's answer, although this was unintentional). The two sequences separately always output an exact 10% frequency after a power of 10 terms, while the combined sequence outputs an exact 1% frequency between the (0-indexed) 10th term and a higher power of 10 terms. Explanation:

```
    Ｎ   Input `s`
   ¬    Logical Not
  ⊕     Incremented
 Ｓ      Input `n` as a string
§       Cyclically indexed
        Implicitly print

```

Version that outputs the first `n` terms for each of the first `s` seeds:

```
ＥＩθ⭆Ｉη§Ｉλ⊕¬ι

```

Try it online! Link is to verbose version of code.
> 3 votes

# Answer
# JavaScript (ES7), 19 bytes

Takes input as `(seed)(n)` and returns the \\$n\\$-th term. The special seed is \\$0\\$.

```
s=>n=>n/10**!s%10|0

```

Try it online!
> 3 votes

# Answer
# Bash, ~~25~~ 23 bytes

Saved 2 bytes thanks to Mitchell Spector!!!

```
echo $[$2/($1?10:1)%10]

```

Try it online!

***Input***: seed (\\$s\\$) and \\$n\\$.
***Output***: \\$n^{\text{th}}\\$ term zero-indexed.

For \\$s=0\\$ the sequence is: \\$0,1,2,\dots,9,\dots\\$
For \\$s\>0\\$ the sequence is: \\$\underbrace{0,0,\dots,0}\_{10},\underbrace{1,1,\dots,1}\_{10},\underbrace{ 2,2,\dots,2}\_{10},\dots,\underbrace{9,9,\dots ,9}\_{10},\dots\\$
> 3 votes

# Answer
# JavaScript (Node.js), 15 bytes

```
s=>n=>n[!s+1]|0

```

Try it online!

If seed is 0 it will take the 3rd digit of the number, else it will take the 2nd digit of the number
> 2 votes

# Answer
# Retina 0.8.2, 16 bytes

```
^(0,.+).
$1
!`.$

```

Try it online! Link includes test cases. Takes input as `s,n` and outputs the second last digit of `n` if it has one and `s` is zero otherwise the last digit of `n`. The individual sequences are 10% of each digit but the combined sequence only approaches 1% after the 10th term. (I have a 16 byte answer in Retina 1 for which the combined sequence contains 1% of each pair.) Explanation:

```
^(0,.+).
$1

```

If `s` is `0` then delete the last digit of `n` unless that is its only digit.

```
!`.$

```

Output the last digit of `n`.
> 1 votes

# Answer
# dc, ~~15~~ 13 bytes

Saved 2 bytes thanks to Mitchell Spector!!!

```
[A/]sa?0=aA%p

```

Try it online!

***Input***: \\$n\\$ and seed (\\$s\\$).
***Output***: \\$n^{\text{th}}\\$ term zero-indexed.

For \\$s\>0\\$ the sequence is: \\$0,1,2,\dots,9,\dots\\$
For \\$s=0\\$ the sequence is: \\$\underbrace{0,0,\dots,0}\_{10},\underbrace{1,1,\dots,1}\_{10},\underbrace{ 2,2,\dots,2}\_{10},\dots,\underbrace{9,9,\dots ,9}\_{10},\dots\\$
> 1 votes

# Answer
# MATLAB, 45 bytes

```
v=input('');rng(fix(~v(1)));randi(10,v(2),1)-1

```

`randi(N,n,1)` generates an n-length sequence of uniform random integers in the range 1,...,N. Taking two digits of the resulting sequence of realizations at a time, the required distribution follows naturally, which can be checked using the example code below.

```
N = 50000 ;
[h,x] = hist(10*(randi(10,N,1)-1) + (randi(10,N,1)-1), 100) ;
h = h/sum(h) ;
stem(x,h) ;
axis([0 10 0 0.1]) ;

```

`rng(fix(~s))` sets the random number generator seed to one if `s=0` otherwise to zero.

# Inputs

Read from the console in the format (incl brackets) "\[s n\]".

# Comments

* This method can be extended to generate limitless number of sequences which satisfy the required properties.
* Now compatible with several versions of MATLAB
> 1 votes

# Answer
# , 22 19 17 bytes

Following earlier resolutions, this R code is producing two different sequences with the correct limiting frequencies whether \\$s=0\\$ (penultimate digits) or \\$s\ne 0\\$ (last digits):

```
1:n%/%10^(!s)%%10

```

Try it online!

As for checking whether or not the merged sequences work as well, one can run, e.g.,

```
summary(as.factor((10*(1:n%/%10%%10)+(1:n%%10))))

```
> 1 votes

# Answer
# Husk, 5 bytes

```
!←±⁰d

```

Try it online! Gives a single term, given `seed` and `n` as arguments. `k` is equal to 0.
> 1 votes

# Answer
# perl -apple, 18 bytes

```
$F[0]&&chop;$_%=10

```

Try it online!

Prints the last digit of `n` for the special sequence (`c = 0`), otherwise, the penultimate digit of `n`. It doesn't quite work for single digit `n`'s, but since we only have to tend towards equal distribution, it doesn't matter what it prints.
> 0 votes

# Answer
# , 2 bytes

(Port of the Charcoal answer.) How in the world can a 3-byter ever compress in the compressor‽

```
H≡

```

Uncompressed:

```
!)[

```

# Explanation

```
!   % Logical negate the first input.
 )  % Increment the negated input.
  [ % Cyclic index the second input by that result.

```
> 0 votes

---
Tags: code-golf, math, sequence
---


title: Exponentiation Sequence

text:
# Question
Title: Exponentiation Sequence
The oldest Polish salt mine, located in Bochnia\*, was started in year 1248, which we can consider a *magical number*. We can see that it's equal to 4 digits from the sequence of exponentiations: .

As the date is actually 4 digits from the sequence, we could make it longer. We could repeat the process until we reach infinity. The sequence would look like this, if we limit it to number `2048`

```
124816326412825651210242048

```

To make it look a bit better, we can separate the numbers:

```
1|2|4|8|16|32|64|128|256|512|1024|2048

```

Let's try a custom, longer sequence than the date. Let's say, we want it to have 5 digits - there are more than one possibility:

* `24816`
* `81632`
* `64128`

Or 3 digit ones:

* `124`
* `248`
* `816`

We could also add the 3 digit numbers to this, but let's say, that a sequence must have **at least two numbers**.

* There is no information about this on the English Wikipedia. If you enter the Polish version - then there is. If you visit the mine, the workers will also tell you, that it started in 1248.

## The challenge

Create a exponentiation sequence like in examples above with 2 as the base.

Given a number from range 2-27, output **all possible** parts of the sequence (The 2048 one or larger if you want) with amount of digits equal to the input. You cannot cut a number, so output like `481` is invalid, because 16 is cut in half.

Rules:

* Standard loopholes are forbidden.
* You can assume the input is a number inside the range.
* Your program can accept inputs larger than the range (28+), but that won't increase/decrease score.
* Spaces in output are ignored. You can output like `124` or like `4 8 16`.
* Different possibilities should be separated by any character from the list: `,./|` or a line feed.
* You can output as an array.
* Every possibility should include **at least 2 different numbers**.
* You must output **a part** of the sequence, you cannot mix numbers that aren't next to each other, like: `14`.
* Hardcoded output isn't allowed, however, you can hardcode a string/number/array containing the full sequence.
* Input 27 should return the full 2048 sequence.
* As already mentioned before, **do not cut numbers**. Ex. `16` must stay `16` \- you can't use `481` \- you must use `4816`.
* **EDIT:** I might have said something wrong there; 2048 is the last number which your program should support, you can add support for larger int's.

## Test cases

Input: `2`

```
12, 24, 48

```

Input: `3`

```
124, 248, 816

```

Input: `4`

```
1248, 4816, 1632, 3264

```

Input: `5`

```
24816, 81632, 64128

```

Input: `27`

```
124816326412825651210242048

```

And later numbers...

If I made a mistake in any of the test cases, tell me or edit the question.

---

This is , so the shortest code in bytes wins!

# Answer
> 8 votes
# 05AB1E, ~~12~~ ~~11~~ 10 bytes

Supports the sequence up to `2^95 = 39614081257132168796771975168`

```
₃ÝoŒʒg≠}Jù

```

Try it online!

**Explanation**

```
₃Ý            # push range [0 ... 95]
  o           # raise 2 to the power of each
   Œ          # get a list of all sublists
    ʒ         # filter, keep elements that satisfy:
     g        # length
      ≠       # false (not equal to 1)
       }      # end filter
        J     # join each
         ù    # keep numbers of length matching the input

```

Saved 1 byte thanks to *Erik the Outgolfer*
Saved 1 byte thanks to *Riley*

# Answer
> 6 votes
# Pyth, ~~22~~ ~~21~~ ~~20~~ 17 bytes

```
fqQlTjLkt#.:^L2yT

```

Try it Online

### Explanation

```
fqQlTjLkt#.:^L2yT
            ^L2yT  Get the powers of 2 up to 2^20
        t#.:       Get all consecutive sequences of at least 2
     jLk           Concatenate each
fqQlT              Get the ones whose length is the input

```

# Answer
> 5 votes
# Jelly,  ~~19 18~~  16 bytes

There may be a shorter solution now that we may use any cut-off (not just 2048), although this change to the specification has allowed a one byte save from this implementation by moving to a cut-off of 32768.
--yep...

-2 bytes thanks to Erik the Outgolfer (use of `V` to allow implicit right argument of the filter and tightening)
--yes it is very similar to his inefficient one now; go upvote his!

```
⁴Ḷ2*Ẇṫ17VDL$⁼¥Ðf

```

A monadic link taking a number and returning a list of numbers.

**Try it online!**

### How?

```
⁴Ḷ2*Ẇṫ17VDL$⁼¥Ðf - Link: number, n        e.g. 3
⁴                - literal sixteen             16
 Ḷ               - lowered range               [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
  2              - literal two                 2
   *             - exponentiate                [1,2,4,8,16,32,...,32768]
    Ẇ            - all sublists                [[1],[2],...,[1,2],[2,4],...,[1,2,4],...]
      17         - literal seventeen           17
     ṫ           - tail from index             [[1,2],[2,4],...,[1,2,4],...]]
        V        - evaluate as Jelly code      [12,24,...,124,...]
              Ðf - filter keep:
             ¥   -   last two links as a dyad
           $     -     last two links as a monad:
         D       -       decimal list (of entry) (i.e. 816 -> [8,1,6] or 24 -> [2,4])
          L      -       length                  (i.e. 816 -> 3, or 24 -> 2)
            ⁼    -   equals (n)                  (i.e. 816 -> 1, or 24 -> 0)
                 - ...resulting in             [816, 124, 248]

```

# Answer
> 4 votes
# Perl 6, ~~62~~ 59 bytes

```
{grep *.comb==$_,map {[~] 2 X**[...] $_},combinations 12,2}

```

Try it online!

# Answer
> 4 votes
# Japt, ~~22~~ ~~20~~ ~~19~~ 16 bytes

Supports input up to `639` but gaps start appearing in the sequence after `234` (See the full list of supported input ranges here). Outputs an array of strings.

```
IÆIo!²ãX m¬lUÃ¤c

```

Test it

`I` (64) could be replaced with `L` (100) but we'd be getting into scientific notation and precision inaccuracies. Filtering those out would, obviously, increase the byte count and only raise the maximum input to `736`.

```
                     :Implicit input of integer U
I                    :64
 Æ                   :Map each X in [0,64)
  Io                 :  Range [0,64)
    !²               :  Raise 2 to the power of each
      ãX             :  Subsections of length X
         m           :  Map
          ¬          :    Join
           lU        :  Filter elements of length U
             Ã       :End map
              ¤      :Slice off the first 2 elements
               c     :Flatten

```

# Answer
> 3 votes
# Husk, ~~18~~ 17 bytes

Output is separated by newlines

```
fo=⁰LmṁsftQ↑12¡D1

```

Try it online!

### How?

```
           ↑12¡D1    The sequence [1,2,4...2048]
              ¡      Repeatedly apply function, collecting results in a list
               D     double
                1    initially applying to 1
           ↑12       Take the first 12 elements
          Q          Get all sublists
        ft           With a length greater than 1
     mṁs             Convert each list into a string, e.g [4,8,16] -> "4816"
fo=⁰L                Keep only those whose length is equal to the input

```

# Answer
> 3 votes
# Python 2, 105 bytes

```
lambda l,r=range:[x for x in[''.join(`2**n`for n in r(i,j+2))for i in r(13)for j in r(i,11)]if len(x)==l]

```

Try it online!

# Answer
> 3 votes
# Haskell, ~~72~~ 67 bytes

```
f n=[s|i<-[0..99],j<-[i+1..99],s<-[show.(2^)=<<[i..j]],length s==n]

```

Try it online!

*Saved 5 bytes thanks to Laikoni*

I used a limit of `99` because `2^99` has a length `> 27`.

# Answer
> 3 votes
# Jelly, 16 bytes

```
ȷḶ2*ẆṫȷḊVDL$⁼¥Ðf

```

Try it online!

Note: very inefficient. Returns a list of numbers.

# Answer
> 3 votes
# JavaScript (ES7), ~~102~~ 100 bytes

Prints all matching sub-sequences with `alert()`.

```
l=>[...1e11+''].map((_,k,a)=>a.map((_,x)=>(s=(g=n=>x<=k|n<k?'':g(n-1)+2**n)(x)).length-l||alert(s)))

```

### Demo

**NB**: This snippet is buffering the results and printing them to the console for user-friendliness.

```
let f =

l=>[...1e11+''].map((_,k,a)=>a.map((_,x)=>(s=(g=n=>x<=k|n<k?'':g(n-1)+2**n)(x)).length-l||alert(s)))

alert = s => res += ' ' + s;

for(l = 2; l <= 27; l++) {
  res = '';
  f(l);
  console.log('L = ' + l + ' -->' + res);
}
```

# Answer
> 2 votes
# Mathematica, 122 bytes

```
(s=#;FromDigits@F[f/@#]&/@Select[Subsequences[Array[2^#&,99,0]],l@#>1&&(l=Length)@(F=Flatten)[(f=IntegerDigits)/@#]==s&])&

```

**Input**

> \[27\]

**Output**

> {879609302220817592186044416, 134217728268435456536870912, 524288104857620971524194304, 163843276865536131072262144, 204840968192163843276865536, 256512102420484096819216384, 641282565121024204840968192, 163264128256512102420484096, 124816326412825651210242048}

```
Input [1000]
Output  1441151880758558722882303761517117445764607523034234881152921504606846976230584300921369395246116860184273879049223372036854775808184467440737095516163689348814741910323273786976294838206464147573952589676412928295147905179352825856590295810358705651712118059162071741130342423611832414348226068484722366482869645213696944473296573929042739218889465931478580854784377789318629571617095687555786372591432341913615111572745182864683827230223145490365729367654460446290980731458735308812089258196146291747061762417851639229258349412352483570327845851669882470496714065569170333976494081934281311383406679529881638685626227668133590597632773712524553362671811952641547425049106725343623905283094850098213450687247810566189700196426901374495621121237940039285380274899124224247588007857076054979824844849517601571415210995964968969903520314283042199192993792198070406285660843983859875843961408125713216879677197516879228162514264337593543950336158456325028528675187087900672316912650057057350374175801344

```

# Answer
> 2 votes
# C, 170 bytes

```
i,j;f(n){char t[99],s[12][5]={"1"};for(i=j=1;i<12;)sprintf(s+i++,"%d",j*=2);for(i=0;i<12;++i,strlen(t)-n||j>1&&puts(t))for(j=*t=0;strlen(t)<n&&j+i<12;)strcat(t,s+i+j++);}

```

Try it online!

**Unrolled:**

```
i,j;
f(n)
{
    char t[99], s[12][5] = {"1"};
    for (i=j=1; i<12;)
        sprintf(s+i++, "%d", j*=2);
    for (i=0; i<12; ++i, strlen(t)-n || j>1 && puts(t))
        for (j=*t=0; strlen(t)<n && j+i<12;)
            strcat(t, s+i+j++);
}

```

# Answer
> 2 votes
# K (ngn/k), 33 bytes

```
{(x=#:')#,/{,/'$x':|2/=12}'2+!11}

```

Try it online!

Generates all possible sublists, then selects those of the proper length. Returns a list of strings.

* `{...}'2+!11` generate 2..12 (the valid sublist lengths for input from 2..27), and run the code in `{...}` on each of those numbers

+ `|2/=12` generate the sequence `1 2 4 8 16 32 64 128 256 512 1024 2048`
    + `,/'$x':` take `x`-length rolling windows, converting each to strings, then concatenate them (e.g., `1 2 4 8` =\> `(1 2;2 4;4 8)` =\> `((,"1";,"2");(,"2";,"4");(,"4";,"8"))` =\> `("12";"24";"48")`)
* `(x=#:')#,/` flatten the potential strings, keeping those of the desired length

# Answer
> 1 votes
# , 99 bytes

```
function(n)for(i in 1:11)for(j in i:11+1)if(sum(nchar(x<-2^(0:11))[i:j])==n)cat(x[i:j],"\n",sep="")

```

Try it online!

# Answer
> 1 votes
# Perl 5, 76 bytes

75 bytes of code + 1 for `-a`

```
for$i(0..10){$/='',(map$/.=2**$_,$i..$_)&&$F[0]-length$/||say$/for$i+1..11}

```

Try it online!

# Answer
> 0 votes
# Ruby, 94 bytes

```
->n{a=*b=1;a<<b*=2until b>3**n;(2..n).flat_map{|x|a.each_cons(x).map &:join}.grep /^.{#{n}}$/}

```

Try it online!

---
Tags: code-golf, sequence, number-theory
---


title: Polygons in a cube

text:
# Question
Title: Polygons in a cube
Inspired in part by this Mathologer video on gorgeous visual "shrink" proofs, and my general interest in the topic, this challenge will have you count regular polygons with integer coordinates in 3D.

You'll be provided an input `n`, which is a non-negative integer. Your program should find the number of subsets of \\$\\{0, 1, \dots, n\\}^3\\$ such that the points are the vertices of a regular polygon. That is, the vertices should be 3D coordinates with nonnegative integers less than or equal to \\$n\\$.

### Examples

For \\$n = 4\\$, there are \\$2190\\$ regular polygons: \\$1264\\$ equilateral triangles, \\$810\\$ squares, and \\$116\\$ regular hexagons. An example of each:

* Triangle: \\$(1,0,1), (0,4,0), (4,3,1)\\$
* Square: \\$(1,0,0), (4,3,0), (3,4,4), (0,1,4)\\$
* Hexagon: \\$(1,1,0), (0,3,1), (1,4,3), (3,3,4), (4,1,3), (3,0,1)\\$

The (zero-indexed) sequence begins:

```
0, 14, 138, 640, 2190, 6042, 13824, 28400, 53484, 94126, 156462, 248568, 380802, 564242, 813528, 1146472, 1581936, 2143878, 2857194, 3749240, 4854942, 6210442

```

### Rules

To prevent the most naive and uninteresting kinds of brute-forcing, your program must be able to handle up to \\$a(5) = 6042\\$ on TIO.

This is a challenge, so the shortest code wins.

---

This is now on the On-Line Encyclopedia of Integer Sequences as A338323.

# Answer
# Python 2, 330 313 bytes

```
import numpy as N,itertools as I
L=list
D=N.dot
n=input()
def G((a,b,c)):
 A=a
 while 1:
	u=b-a;v=c-b;d=D(v,v)
	if D(u,u)-d:return 0
	p=2*D(u,v)*v
	a,b,c=b,c,c+a-b+p/d
	if(p%d|(c<0)|(c>n)).any()or L(a)<L(A):return 0
	if L(a)==L(A):return 1
print sum(map(G,I.permutations(N.indices((n+1,)*3).reshape(3,-1).T,3)))/2

```

Try it online!

TIO spent `36.893 s` calculating `a(5) = 6042`, so this solution is just fast enough.

Given 3 consecutive points of a regular polygon `a,b,c`, the next point is `d = c + a - b + 2*proj(b-a, c-b)` (where `proj` is vector projection). My solution iterates through all triples of points and determines if they form a polygon using this formula.

Verified up to `a(7) = 28400` on my machine.

-17 bytes from ovs
> 7 votes

---
Tags: code-golf, sequence, geometry, combinatorics, grid
---


title: Implement Smokey's !!/alive command

text:
# Question
Title: Implement Smokey's !!/alive command
> ***Note**: SmokeDetector is a bot that detects spam and offensive posts on the network and posts alerts to chat.*

# What to implement

Smokey's `!!/alive` command uniformly at random picks one of these messages:

* Yup
* You doubt me?
* Of course
* ... did I miss something?
* plz send teh coffee
* Watching this endless list of new questions never gets boring
* Kinda sorta
* You should totally drop that and use jQuery
* ¯\\\_(ツ)\_/¯
* ... good question

and prints it to the screen.

Your task is to implement that command.

# Rules

Regular code-golf — the shortest answer in bytes wins ;)

*Good luck!*

# Answer
# Python 2, 240 bytes

Hexdump:

```
00000000: efbb bf65 7865 6322 2222 789c 3d4f 3b4e  ...exec"""x.=O;N
00000010: c430 10bd ca53 aa84 221c 8082 1a51 202a  .0...S.."....Q *
00000020: b4d2 4a6b 6f3c 498c 1c8f f18c 414b 0bf7  ..Jko<I.....AK..
00000030: d93b ec55 b808 0348 54a3 d1fb cf95 3754  .;.U...HT.....7T
00000040: 9f83 9db8 15ae 7a75 536a cc8a 69e5 3851  ......zuSj..i.8Q
00000050: dfed 5a71 f731 070f 31d4 bb1d 3704 6e47  ..Zq.1..1...7.nG
00000060: c546 b76e 1c47 8418 7087 2d8a 1865 235d  .F.n.G..p.-..e#]
00000070: 635e fe90 8539 e0a5 9168 e4ec 4a7a 8750  c^...9...h..Jz.P
00000080: 0e50 5a31 f13c 13b9 27af d30f 1fa6 1218  .PZ1.<..'.......
00000090: 98c8 6c52 1405 cfc8 f4f6 2f17 fb5e a962  ..lR....../..^.b
000000a0: 2115 1cd9 3a2e ee61 369f 5685 dce5 bc3f  !...:..a6.V....?
000000b0: f45f 1f9f c3e1 fa72 feed 282b b764 59ac  ._.....r..(+.dY.
000000c0: 3ea5 1342 e562 215e 6163 d184 f0fc d8a8  >..B.b!^ac......
000000d0: 9eba 514a 8ada 77ae 1b86 6f8b b863 c922  ..QJ..w...o..c."
000000e0: 2222 2e64 6563 6f64 6528 227a 6970 2229  "".decode("zip")

```

Try it online!
> 13 votes

# Answer
# 05AB1E, 123 bytes

```
Žmõç”¡¸€îååªç€î”#`“Yup
ÿ¬³€á?
Of…£
...ƒ§ Iš§†á?
plzƒ¨ teh™²
ÿ€Œèá‚‡€‚€¢…é†™–ÜÜÀ
ÿŠœa
ÿ‚©§À›Â€Š€ƒ€Å jÿ
¯\_(ÿ)_/¯
...‚¿†ä“¶¡Ω

```

Try it online!

**Note:** *Prints a random response with a trailing newline.*

Golfed using @KevinCruijssen's well known golf tip.

## Explanation

```
Žmõç                         # Push the katakana character 'ツ'
”¡¸€îååªç€î”#`               # Push some uncompressible words onto the stack
“...“                        # Then push a compressed string containing the following contents:
  Yup                        # "Yup"
  ÿ¬³ me?                    # "You doubt me?"
  Of…£                       # "Of course"
  ...ƒ§ Iš§†á?               # "... did I miss something?"
  plzƒ¨ teh™²                # "plz send teh coffee"
  ÿ€Œèá‚‡€‚…é†™–ÜÜÀ          # "Watching this endless list of new questions never gets boring"
  ÿŠœa                       # "Kinda sorta"
  ÿ‚©§À›Â€Š€ƒ€Å jQuery       # "You should totally drop that and use jQuery"
  ¯\_(ÿ)_/¯                  # shruggy boy
  ...‚¿†ä                    # "... good question"

¶¡                           # Split the responses into a good ol' list
Ω                            # Randomly pick a response
                             # At the end, yell the response out to STDOUT implicitly

```

---

Random fact: I was in halfway in the making of this program when my laptop crashed. I had to start coding again. Oh well, at least my answer is winning at the time of writing this!
> 10 votes

# Answer
# , 265 bytes

```
cat(sample(c('Yup','You doubt me?','Of course','... did I miss something?','please send teh coffee','Watching this endless list of new questions never gets boring','Kinda sorta','You should totally drop that and use jQuery','¯\\_(ツ)_/¯','... good question'),1))

```

Try it online!
> 6 votes

# Answer
# Jelly, 145 bytes

```
“þkċṁṚFọẏ_ỌƤ:ZfCðƓ$6ṛtẓ2JƇMɼ¤ẆƥyɼȧẒ¡ƇƘ9Ɲŀẏ®ỊH\.ƒgFĊ#Ọṁv;`Ä?ḄƒXƲeȥẹ$Ḟ-Ṿṙ"zḄfWẊkEƓẇẇṢ¶ż²ṘzḄ¢ɼQ2³{Ėṃ"B¡f÷ṅƇ0@bSḟ⁶E⁶ėẇefðRẹȤ»O_33o142+33+197¦12309ỌỴX

```

Try it online!

Encodes the whole string but replacing the shrug with `!\_(!)_/!` (since `!` doesn't show up in the string and only printable ASCII / newlines are allowed), and then replaces `!` with the upper bar symbol, and then just sets the Japanese character at that index manually.

Then, split by newlines and select a random one.
> 5 votes

# Answer
# Pyth, 230 bytes

```
Oc"Yup	You doubt me?	Of course	... did I miss something?	plz send teh coffee	Watching this endless list of new questions never gets boring	Kinda sorta	You should totally drop that and use jQuery	¯\_(\u30C4)_/¯	... good question"\

```

Try it online!

Fun fact: If you used a "packed" string, the byte count would jump up to 388.
> 5 votes

# Answer
# Python 3, ~~283~~ 274 bytes

-9 bytes thanks to ovs

```
from random import*
print(choice('Yup,You doubt me?,Of course,... did I miss something?,please send teh coffee,Watching this endless list of new questions never gets boring,Kinda sorta,You should totally drop that and use jQuery,¯\_(ツ)_/¯,... good question'.split(',')))

```

Try it online!
> 4 votes

# Answer
# JavaScript, ~~297~~ ~~287~~ ~~285~~ ~~277~~ 265 bytes

-10 bytes by replacing `Math.floor()` with `~~()`

-2 bytes by replacing `~~()` with `|0` thanks to Neil

-8 bytes by replacing array with `string.split(',')`

-12 bytes by placing options directly inside of `alert()` and replacing `string.split(',')` with `string.split`,``

```
alert('Yup,You doubt me?,Of course,... did I miss something?,please send teh coffee,Watching this endless list of new questions never gets boring,Kinda sorta,You should totally drop that and use jQuery,¯\\_(ツ)_/¯,... good question'.split`,`[Math.random()*10|0])
```
> 4 votes

# Answer
# Charcoal, ~~152~~ 151 bytes

```
‽⊞Ｏ⪪”}∧Ｐπ↙!▶�▶τ×Ｂlal⁰FＷ⊕← ″»yε⦃σ$L}⊖0!…Ｒf»V?⌕ΦＹV'∕ⅉ)>ιη¤=▷∧p{<ψ;↶～⌊″≔↔≡m≦ζＸ"´j\`⁹WＳ⌕Ｖ›w}ＬV>ＤＴY(Y⪪h‽ＢＲＶ⌕↥↘⮌\L∨⁰ＭPφFY5^ＩG↑~c‖"⌕ν﹪ηVＥ\`êＶω”A¦¯\_(ツ)_/¯

```

Try it online! Link is to verbose version of code. Edit: Saved 1 byte by using `A` as a separator. Note: The deverbosifier claims ~~148~~ 147 bytes, but I believe `¯` (like ) needs to be encoded using 3 bytes in Charcoal. Explanation: Charcoal can only compress strings of printable ASCII, so the shrug is appended separately.

```
    ”...”               Compressed string
   ⪪     ¶              Split on newlines
 ⊞Ｏ        ¯\_(ツ)_/¯    Push literal string
‽                       Random element
                        Implicitly print

```
> 3 votes

# Answer
# K (oK), 237 bytes

```
`0:*1?";"\"Yup;You doubt me?;Of course;... did I miss something?;plz send teh coffee;Watching this endless list of new questions never gets boring;Kinda sorta;You should totally drop that and use jQuery;¯\\_(ツ)_/¯;... good question";

```

Try it online!

If returning a string is acceptable, the leading ``0:` and trailing `;` can be elided to save 4 bytes.
> 3 votes

# Answer
# Bash, 269 267 266 264 bytes

-2: @user42589

-1: @nthnchu

-2: @Nahuel Fouilleul

```
q=(Yup "You doubt me?" Of\ course "... did I miss something?" "plz send teh coffee" "Watching this endless list of new questions never gets boring" Kinda\ sorta "You should totally drop that and use jQuery" "¯\_(ツ)_/¯" "... good question");echo ${q[RANDOM%10]}

```

Try it online!
> 3 votes

# Answer
# C (gcc), ~~294~~ ~~290~~ 289 bytes

Saved 4 bytes thanks to ErikF!!!
Saved a byte thanks to ceilingcat!!!

```
*s[]={"Yup","You doubt me?","Of course","... did I miss something?","please send teh coffee","Watching this endless list of new questions never gets boring","Kinda sorta","You should totally drop that and use jQuery","¯\\_(ツ)_/¯","... good question"};f(){puts(s[rand(srand(time(0)))%10]);}

```

Try it online!

Straightforward `rand()` selection from an array of strings.
> 2 votes

# Answer
# Retina, ~~232~~ 228 bytes

```

Yup,You doubt me?,Of course,... did I miss something?,please send teh coffee,Watching this endless list of newqs never gets boring,Kinda sorta,You should totally drop that and use jQuery,¯\_(ツ)_/¯,... goodq
q
 question
?S`,

```

Try it online! Explanation: The first two stages replace the empty input with the given string, the second stage saving 4 bytes by deduplicating the substring  `question`, while the last stage splits it on commas and outputs a random element. Note that the byte count has been adjusted for UTF-8 (Retina normally uses ISO-8859-1 if it can, which is why TIO only shows the character count rather than the byte count). Edit: I used @Leo's Retina Kolmogorov golfer to detect the duplication and save 4 bytes.
> 2 votes

# Answer
# Scala, ~~278~~ 267 bytes

```
print("Yup#You doubt me?#Of course#... did I miss something?#plz send teh coffee#Watching this endless list of new questions never gets boring#Kinda sorta#You should totally drop that and use jQuery#¯\\_(ツ)_/¯#... good question".split("#")((math.random*10)toInt))

```

Try it online!
> 2 votes

# Answer
# PHP, 261 253 bytes

-8: Change `<?php echo`  to `<?=` (@nthnchu)

```
<?=explode(",","Yup,You doubt me?,Of course,... did I miss something?,plz send teh coffee,Watching this endless list of new questions never gets boring,Kinda sorta,You should totally drop that and use jQuery,¯\_(ツ)_/¯,... good question")[rand(0,9)];

```

Try it online!
> 1 votes

# Answer
# Vyxal, 150 bytes

```
`Yup|λ⍎ řð me?|Of ⟑ₑ|... ¬⁌ I ɾ⟑ ⟇↜?|plz ¬Ĵ teh ʁƛ|←⍋ λ« ⊛⟑ λ′ of λÞ ∨Œ ∨ſ Ô₂ ℅⁑|ₑ¥ °⊛a|λ⍎ ƛð ∺⁂ ɽ∫ λ⟇ λ¬ λʗ jßø|\¯\\_(`12484C+`)_\\\¯|... ƛ∫ ⟇¹`+\|/℅

```

Try it Online!

I decided to use an alternate approach with the new built-ins
> 1 votes

---
Tags: code-golf, kolmogorov-complexity, random
---


# Question
Title: Can I print my picture on {A,B,C}{0-10} paper?
The task is to find the smallest paper size on which it is possible to print a picture of the dimensions given in milimetres. The image will be printed without margins.

# Input:

Two integers (bigger than zero) and a letter a, b, or c, for example:

```
290
200
A

```

# Output:

Paper size, for example:

> A4

Another examples:

```
218,297,a      A3
1,1,c          C10
9999,9999,c    ??? (error)
74,52,A        A8
31,44,B        B10
26,1100,A       A0
250,177,b     b4
250,176,b    b5
1189,841,a    a0

```

The dimensions of the paper for \\$i \in \\{0,\dots, 10\\} \\$ are:

$$ \left( \frac{\alpha}{\sqrt{2}^{i+1}} , \frac{\alpha}{\sqrt{2}^{i}} \right) $$

where \\$\alpha\\$ depends on the type of paper:

$$ \begin{eqnarray} \alpha\_A &=& 2 ^ {1/4} \\ \alpha\_B &=& 2 ^ {1/2} \\ \alpha\_C &=& 2 ^ {3/8} \\ \end{eqnarray} $$

---

* Upper- and lowercase variants of letters "A", "B" and "C" are allowed on input and on output. You need to handle both of them.
* The image can be printed vertically or horizontally.
* The values can be passed as a parameter or entered by the user.
* Width and height of picture will be always \> 0 (and they will be always integers), and letters will be always 'a', 'b', or 'c'. You don't need to validate them.
* You need to handle paper sizes A0 - A10, B0 - B10 and C0 - C10. If the image is too large, you can throw an exception, print an error or whatever you want, as long as it is clearly different from valid result and the application will not hung up.

Paper sizes, please ignore inch values (source: Wikipedia) :

---

This is - fewest bytes wins.

# Answer
> 7 votes
# Charcoal, 38 bytes

```
η⊞θ×⌊θ₂²Ｉ⊖Ｌ↨⌊Ｘ∕×φＸ²∕⁺²⌕ACB↥η⁸⁻⌈θ·²¦²¦²

```

Try it online! Link is to verbose version of code. Takes input as a pair of integers and a characters. Explanation:

```
η

```

Output the paper letter.

```
⊞θ×⌊θ₂²

```

Multiply the smaller dimension by √2 and use that if it is larger than the larger dimension.

```
Ｉ⊖Ｌ↨⌊Ｘ∕×φＸ²∕⁺²⌕ACB↥η⁸⁻⌈θ·²¦²¦²

```

Calculate the largest size of paper, divide by the larger dimension (less 0.2 due to rounding errors), square the result, convert to binary, and count the digits (because Charcoal has no logarithm function).

# Answer
> 3 votes
# Python 3, 99 bytes

```
f=lambda a,c,i=10:max(a)<=1e3*2**(2**ord(c)%5/8-i/2)>=min(a)*2**.5and c+str(max(-1,i))or f(a,c,i-1)

```

Try it online!

-2 bytes thanks to ceilingcat.

-12 bytes thanks to ovs.

# Answer
> 2 votes
# Python 3.8 (pre-release), 157 bytes

```
lambda x,y,a:a+str((k:=[*zip(A:=[(int(2**((2+-(~-ord(a)%32)%3)/8)/2**(i/2)*1e3+.2))for i in range(12)],A[1:])])and~-sum(y<=q>r>=x or x<=q>r>=y for q,r in k))

```

Try it online!

Outputs `X-1` if the image is too large.

-4 bytes thanks to ErikF

# Answer
> 2 votes
# C (gcc), ~~189~~ ~~174~~ ~~161~~ 152 bytes

Thanks to ceilingcat for the -37.

The function normalizes the dimensions and then iterates through the sizes until one fits. To return the paper size, `asprintf()` works and makes it so I don't have to have a static array to store the string.

```
f(w,h,z,x){float q;z=~-z&3,w>h?x=w:(x=h,h=w);for(w=11;round(q=exp2(~z/4./~(z/2)-.5*--w)*1e3)<x|round(q/sqrt(2))<h&&~w;);asprintf(&h,"%c%d",z+65,w);w=h;}

```

Try it online!

# Answer
> 1 votes
# Haskell, ~~154 135~~ 139 bytes

```
f a b c|d<-[y|(x,y)<-zip"abcABC"$cycle[1189.4,1414.4,1297],x==c]!!0=c:(show$sum[1|x<-[0..10],max a b<d*2**(-x/2)&&(d/min a b)**2/2>2**x]-1)

```

Try it online!

* Saved 21 bytes thanks to @ovs !
* Fixed bug notified by @HyperNeutrino Added 0.2 to the precomputed constants `1189.2071150027211, 1414.213562373095, 1296.8395546510096` to fix rounding issues. The resulting table here .

```
f a b c=    - function tacking sizes(a,b) and format (c).
|d<-[y|(x,y)<-zip"abcABC"$cycle[1189.4,1414.4,1297],x==c]!!0
            - get the precomputed constant relative to input(c)
c:(show$    - returns a string composed of format followed by result
sum[...]-1  - count all valid sizes => 0 index
[1|x<-[0..10],max a b<d*2**(-x/2)&&(d/min a b)**2/2>2**x]
            - compute 0..10 sized and yield 1 if valid

```
* outputs "{format}-1" for invalid input.

# Answer
> 1 votes
# 05AB1E, ~~41~~ 40 bytes

```
ƵàS8/o¤11Ýmδ/₄*εü2í}5z+ï²Ç`8%èε¹{‹O_}O<«

```

Pair with the dimensions of the picture as as first input; letter as second input.
Outputs in the same case as the input, and with `-1` for error-cases above paper size `0`.

Try it online or verify all test cases.

**Explanation:**

```
Ƶà       # Push compressed integer 324
  S      # Convert it to a list of digits: [3,2,4]
   8/    # Divide each by 8: [3/8, 1/4, 1/2]
     o   # Take 2 to the power each of these: [1.296..., 1.189..., 1.414...]
¤        # Push the last item of the list (without popping the list itself):
         #  1.414... (which is sqrt(2))
 11Ý     # Push a list in the range [0,11]
    m    # Take sqrt(2) to the power each of these integers
     δ   # Apply double-vectorized over the two lists:
      /  #  Divide
₄*       # Multiply each by 1000
  ε      # Map each list of lists to:
   ü2    #  Create overlapping pairs of the list
     í   #  And then reverse each pair
  }5z+   # After the map: add 1/5 to each value (fix for A0 and C0)
      ï  # Floor every decimal by casting it to an integer

```

We now have a list of paper sizes, grouped per letter:

```
[[[917,1297],[648,917],[458,648],[324,458],[229,324],[162,229],[114,162],[81,114],[57,81],[40,57],[28,40]],
 [[841,1189],[594,841],[420,594],[297,420],[210,297],[148,210],[105,148],[74,105],[52,74],[37,52],[26,37]],
 [[1000,1414],[707,1000],[500,707],[353,500],[250,353],[176,250],[125,176],[88,125],[62,88],[44,62],[31,44]]]

```

```
²        # Push the second input-letter
 Ç       # Convert it to a list of codepoint integers
  `      # Pop that list, and push its only integer to the stack
   8%    # Take modulo-8 on it (A→1, B→2, C→3, a→1, b→2, c→3)
     è   # Index it into the list of lists (0-based modulair, so 3 will index into the
         # first inner list)
ε        # Map each pair in the list to:
 ¹       #  Push the first input-pair
  {      #  Sort this pair from lowest to highest
   ‹     #  Check if the sorted input-pair is higher than the current pair
    O    #  Sum those checks together
     _   #  And check that it's 0 (thus both were falsey)
}O       # After the map: get the amount of truthy values by summing
  <      # Decrease this by 1
   «     # And append it to the (implicit) second input-letter
         # (after which it is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ƶà` is `324`.

---
Tags: code-golf
---