title: How good am I at CS:GO?

text:
# Question
Title: How good am I at CS:GO?
Your task is given an input string of the full/short name of a CS:GO (Counter-Strike: Global Offensive, a computer game) rank return an integer from 1-18 representing the rank number. A higher number means you are a higher rank and so "better" at CS:GO.

**Input**

A string representing either the full name or short name of the CS:GO rank. Your code must be able to handle both cases.

**Output**

An integer representing the rank number of the given input. You can output in either 0-indexing or 1-indexing as 0-17 and 1-18 respectively.

**Test cases:**

The test cases use 1 - 18 as the output, just subtract one if you are using 0-indexing. Where SN means short name.

```
Full name                     SN   -> output

Silver I                      S1   -> 1
Silver II                     S2   -> 2
Silver III                    S3   -> 3
Silver IV                     S4   -> 4
Silver Elite                  SE   -> 5
Silver Elite Master           SEM  -> 6
Gold Nova I                   GN1  -> 7
Gold Nova II                  GN2  -> 8
Gold Nova III                 GN3  -> 9
Gold Nova Master              GNM  -> 10
Master Guardian I             MG1  -> 11
Master Guardian II            MG2  -> 12
Master Guardian Elite         MGE  -> 13
Distinguished Master Guardian DMG  -> 14
Legendary Eagle               LE   -> 15
Legendary Eagle Master        LEM  -> 16
Supreme Master First Class    SMFC -> 17
Global Elite                  GE   -> 18

```

# Answer
# Jelly,  ~~51 49 46~~  45 bytes

```
Oḅ4%⁽+Þ%63“¬>ṬṿḄḋḷ<¶Ġþṛṫ9ṡt[`3"G£ḳọċ’b59¤i‘:2

```

A monadic link accepting a list of characters and returning an integer.
Result is 0-indexed.

**Try it online!** or see all valid inputs at the **test suite**.

### How?

```
Oḅ4%⁽+Þ%63“ ... ’b59¤i‘:2 - Main link: list of characters, s  e.g. "Global Elite"
O                         - cast to ordinals                       [71,108,111,98,97,108,32,69,108,105,116,101]
 ḅ4                       - convert from base 4                    448653509 (71 * 4 ^ 15 + 108 * 4 ^ 14 + ... + 116 * 4 + 101 = 448653509)
    ⁽+Þ                   - base 250 compressed number             11771
   %                      - modulo                                 1844 (448653509 = 11771 * 38115 + 1844)
       %63                - modulo 63                              17 (1844 = 63 * 29 + 17)
                     i    - first index (or 0 if not found) in:    33  -----------------------------------------------------------------------+
                    ¤     - nilad followed by link(s) as a nilad:                                                                             |
          “ ... ’         -   base 250 integer = 29327561081972369663135271131767983884313794468054748055733                                  v
                 b59      -   convert to base 59 = [1,4,5,44,6,14,7,23,43,45,16,48,21,49,50,51,13,55,2,53,28,54,10,37,18,36,8,58,31,57,24,47,17,37]
                          -   i.e. all valid results of the hashing except Silver I (40) and S1 (3) in ascending rank order.
                      ‘   - increment                              34
                       :2 - integer divide by 2                    17

```

(another 45 byter: `Oḅ30%⁽EÐ%53“ḷṡ{Żiȧ)ßØẊ×HuÑç%Ɱȧḷ9)×ḍỊ’b53¤i‘:2`)
> 3 votes

# Answer
# JavaScript (ES6), ~~164~~ ~~150~~ 135 bytes

```
s=>'GE S1|S2|S3|S4|SE|SEMGN1GN2GN3GNMMG1MG2MGEDMGLE LEMSMFC'.search(s[r='replace'](/[a-z ]/g,'')[r]('IV',4)[r](/I+/,a=>a.length))/3||18

```

(Saved a bunch of bytes thanks to @Craig Ayre and @Steve Bennett.)

**Explanation:**

`s[r='replace'](/[a-z ]/g,'')[r]('IV',4)[r](/I+/,a=>a.length)` converts **Full names** to the **SN** equivalents. It doesn't change **SN**s.

We then simply index into the array of **SN**s created by `split`.

**Snippet:**

```
f=
s=>'GE S1|S2|S3|S4|SE|SEMGN1GN2GN3GNMMG1MG2MGEDMGLE LEMSMFC'.search(s[r='replace'](/[a-z ]/g,'')[r]('IV',4)[r](/I+/,a=>a.length))/3||18

console.log(f('Silver I'));                      // S1   -> 1
console.log(f('Silver II'));                     // S2   -> 2
console.log(f('Silver III'));                    // S3   -> 3
console.log(f('Silver IV'));                     // S4   -> 4
console.log(f('Silver Elite'));                  // SE   -> 5
console.log(f('Silver Elite Master'));           // SEM  -> 6
console.log(f('Gold Nova I'));                   // GN1  -> 7
console.log(f('Gold Nova II'));                  // GN2  -> 8
console.log(f('Gold Nova III'));                 // GN3  -> 9
console.log(f('Gold Nova Master'));              // GNM  -> 10
console.log(f('Master Guardian I'));             // MG1  -> 11
console.log(f('Master Guardian II'));            // MG2  -> 12
console.log(f('Master Guardian Elite'));         // MGE  -> 13
console.log(f('Distinguished Master Guardian')); // DMG  -> 14
console.log(f('Legendary Eagle'));               // LE   -> 15
console.log(f('Legendary Eagle Master'));        // LEM  -> 16
console.log(f('Supreme Master First Class'));    // SMFC -> 17
console.log(f('Global Elite'));                  // GE   -> 18

console.log(f('S1'));
console.log(f('S2'));
console.log(f('S3'));
console.log(f('S4'));
console.log(f('SE'));
console.log(f('SEM'));
console.log(f('GN1'));
console.log(f('GN2'));
console.log(f('GN3'));
console.log(f('GNM'));
console.log(f('MG1'));
console.log(f('MG2'));
console.log(f('MGE'));
console.log(f('DMG'));
console.log(f('LE'));
console.log(f('LEM'));
console.log(f('SMFC'));
console.log(f('GE'));
```
> 6 votes

# Answer
## Ruby, ~~120~~ ~~111~~ ~~100~~ 99 bytes

```
->x{x.tr!'a-z ','';x.gsub!(/I.*/){$&.sum%18%11};'

   '[x.sum%36%20+x.ord%4].ord}

```

Hexdump, since the Stack Exchange software mangles lots of the unprintables in the source code:

```
00000000: 2d3e 787b 782e 7472 2127 612d 7a20 272c  ->x{x.tr!'a-z ',
00000010: 2727 3b78 2e67 7375 6221 282f 492e 2a2f  '';x.gsub!(/I.*/
00000020: 297b 2426 2e73 756d 2531 3825 3131 7d3b  ){$&.sum%18%11};
00000030: 270e 0f0d 0920 2010 0102 0304 0511 0a20  '....  ........
00000040: 1206 200b 0c20 0708 275b 782e 7375 6d25  .. .. ..'[x.sum%
00000050: 3336 2532 302b 782e 6f72 6425 345d 2e6f  36%20+x.ord%4].o
00000060: 7264 7d                                  rd}

```

Try it online!

(Note: I can't figure out how to get a carriage return into the "Code" box on TIO, so the TIO version has it replaced with an `X` and hence outputs `88` instead of `13` for MGE.)

Explanation:

```
x.tr!'a-z ',''

```

This deletes all lowercase letters and spaces from the input.

```
x.gsub!(/I.*/){$&.sum%18%11}

```

This searches for an `I` in the string and, if found, replaces it to the end of the string with the result of a black-magic algorithm (found by brute force search) that produces the numeric equivalent of the Roman numeral.

```
'junk'[more junk].ord

```

The first section of junk (and the `ord`) maps the values `[7, 8, 9, 10, 11, 16, 21, 22, 3, 13, 18, 19, 2, 0, 1, 6, 12, 15]` to the range `1..18` by indexing into the string, which contains the appropriate bytes at their corresponding indices.

The second section of junk maps the values `["S1", "S2", "S3", ...]` to the values `[7, 8, 9, ...]`. The formula was produced by a simple brute force search minimizing the maximum value obtained while ensuring that 18 unique values still exist.
> 6 votes

# Answer
# PHP, 151 Bytes

0-Indexing

Remove all characters that not Uppercase or digit

After that replace the digits with their roman numbers

Search and Output the Key in the Array

```
<?=array_flip([SI,SII,SIII,SIV,SE,SEM,GNI,GNII,GNIII,GNM,MGI,MGII,MGE,DMG,LE,LEM,SMFC,GE])[strtr(preg_replace("#[^C-V\d]#","",$argn),[_,I,II,III,IV])];

```

Try it online!

# PHP, 158 Bytes

0-Indexing

Remove all characters that not Uppercase

After that replace the roman numbers with their digit

Search and Output the Key in the Array

```
<?=array_flip([S1,S2,S3,S4,SE,SEM,GN1,GN2,GN3,GNM,MG1,MG2,MGE,DMG,LE,LEM,SMFC,GE])[preg_replace(["#[^C-V]#","#IV#","#III#","#II#","#I#"],["",4,3,2,1],$argn)];

```

Try it online!

# PHP, 295 Bytes

0-Indexing Without Regex

Search and Output the Key of an Array

If more than 4 characters are set in the input take the array with the longer names else take the array with the short names

```
<?=array_flip(explode(_,$argn[4]?strtr("0I_0II_0III_0IV_03_03 4_1I_1II_1III_14_45I_45II_453_Distinguished 45DMG_2_2 4_Supreme 4 First Class_Global 3",["Silver ","Gold Nova ","Legendary Eagle",Elite,Master," Guardian "]):S1_S2_S3_S4_SE_SEM_GN1_GN2_GN3_GNM_MG1_MG2_MGE_DMG_LE_LEM_SMFC_GE))[$argn];

```

Try it online!
> 5 votes

# Answer
# Retina, 70 bytes

```
V
3
G.*N.*M|L
55
G.*N
6
M.*G.*E
67
G.*E
99
D
4
E
5
F
88
G
9
\d
$*I
I|M

```

Try it online! Works by converting specific upper case letter combos into digits and totalling the digits.
> 5 votes

# Answer
# Python 3 + Roman, 291 bytes

```
import roman as r,sys
a=sys.argv
x,y,o=a[1],a[-1],{r:i for i,r in enumerate(["S1","S2","S3","S4","SE","SEM","GN1","GN2","GN3","GNM","MG1","MG2","MGE","DMG","LE","LEM","SMFC","GE"])}
print(o[x if x in o else "".join([n[0] for n in a[1:-1]] + [str(r.fromRoman(y)) if y in "IIIV" else y[0]])])

```

Non-golfed version:

```
import roman
from sys import argv

if __name__ == "__main__":
    ranks = ["S1", "S2", "S3", "S4", "SE", "SEM", "GN1", "GN2", "GN3", "GNM",
             "MG1", "MG2", "MGE", "DMG", "LE", "LEM", "SMFC", "GE"]
    output = {rank : i for i, rank in enumerate(ranks)}

    if argv[1] in output:
        print(output[argv[1]])
    else:
        argv[-1] = str(roman.fromRoman(argv[-1])) if argv[-1] in "IIIV" else argv[-1][0]
        print(output["".join([x[0].upper() for x in argv[1:]])])

```
> 3 votes

# Answer
# Python 2,  ~~100~~  96 bytes

```
lambda s:"F]u^B_&`5qDy,MeN<O$iW'?(d;hHQ2Y:1o%a".find(chr((9*ord(s[0])+ord((s*18)[35]))%92+33))/2

```

An unnamed function accepting the string `s` and returning an integer.
Result is 0-indexed.

**Try it online!**

### How?

Takes the 1st and 36th (modulo the length) characters of the input using `s[0]` and `(s*18)[35]` respectively, that produces the mapping:

```
{"Silver I":"Sv", "S1":"S1", "Silver II":"SI", "S2":"S2", "Silver III":"Sr", "S3":"S3", "Silver IV":"SV", "S4":"S4", "Silver Elite":"Se", "SE":"SE", "Silver Elite Master":"St", "SEM":"SM", "Gold Nova I":"Gl", "GN1":"G1", "Gold Nova II":"GI", "GN2":"G2", "Gold Nova III":"G ", "GN3":"G3", "Gold Nova Master":"Gd", "GNM":"GM", "Master Guardian I":"Ma", "MG1":"M1", "Master Guardian II":"MI", "MG2":"M2", "Master Guardian Elite":"Mn", "MGE":"ME", "Distinguished Master Guardian":"Dg", "DMG":"DG", "Legendary Eagle":"Ld", "LE":"LE", "Legendary Eagle Master":"Ll", "LEM":"LM", "Supreme Master First Class":"Sa", "SMFC":"SC", "Global Elite":"Ge", "GE":"GE"}

```

Converts them to ordinals and converts that from base 9 (ignoring the "base 9 only has 9-digits" restriction) by multiplying the first ordinal by nine and adding it to the second (`9*ord(s[0])+ord((s*18)[35])`).

Reduces the range of those numbers while maintaining uniqueness by taking the modulo 92 of the result. Adds 33 to make the range fit across printable characters (while avoiding the pesky `\` which would require escaping).

Looks up the index of the resulting character in a string, using `find` and integer divides the result by two with `/2` (since every two characters represent a "class" - one for the long name and one for the short name).
> 1 votes

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


title: Golf my Shakespeare quote references

text:
# Question
Title: Golf my Shakespeare quote references
While writing my essay for Shakespeare, I realized that I needed to shorten my quote references to more manageable lengths. I had previously been writing this:

```
(Act 1, Scene 2, Lines 345-346)

```

But I've now been told to write them like this:

```
(I.ii.345-6)

```

Clearly, I need some golfed code to golf my Shakespeare quote references down a bit.

# The Task

Write a program or function that, given a string input following Template 1 or 2, print or return a string following Template 3 or 4, respectively. You only have to support Acts 1 through 5 and Scenes 1 through 9.

# Templates

### Template 1

```
(Act x, Scene y, Lines a-b)

```

You may assume that `x` never exceeds 5, `y` never exceeds 9, `a` and `b` are always positive integers not exceeding your language's maximum positive standard integer value, and `a` is always exclusively less than `b`.

### Template 2

```
(Act x, Scene y, Line a)

```

Same conditions as Template 1, excluding information about `b`.

### Template 3

```
(x.y.a-b)

```

Where `x` is a capital roman numeral, `y` is a lowercase roman numeral, `a` and `b` are numbers, and `b` is shortened to only the digits less than the first differing digit of equal significance from `a`.

### Template 4

```
(x.y.a)

```

Same conditions as Template 3, excluding information about `b`.

# Test Cases

Let `f(s)` be the function defined in the Task. `""` denotes a string value.

```
>>> f("(Act 1, Scene 2, Lines 345-346)")
"(I.ii.345-6)"

>>> f("(Act 3, Scene 4, Lines 34-349)")
"(III.iv.34-349)"

>>> f("(Act 5, Scene 9, Lines 123-234)")
"(V.ix.123-234)"

>>> f("(Act 3, Scene 4, Line 72)")
"(III.iv.72)"

>>> f("(Act 2, Scene 3, Lines 123-133)")
"(II.iii.123-33)"

>>> f("(Act 4, Scene 8, Lines 124-133)")
"(IV.viii.124-33)"

```

For the purposes of this challenge, the following arabic to roman numeral translations must be supported:

```
1 i     I
2 ii    II
3 iii   III
4 iv    IV
5 v     V
6 vi    (you do not have to support past 5)
7 vii
8 viii
9 ix

```

# Answer
# The Shakespeare Programming Language (non-competing)

I really liked this question, and as there was some interest in a Shakespeare-language answer, here is one.

```
A Tale of Two Cites (sic).

Julius Caesar, the first citizen of the Roman Republic.
Brutus, a traitor -- member of the Fifth Column.
Cicero, the greatest Roman orator.
Cleopatra, a proud queen, whom the Romans want to make one of their own.
Romeo, a man who's sometimes there.
Juliet, a maiden who can follow Romeo or stand on her own.

           Act I: Imperium Romanum.

           Scene I: Cleopatra puts men in their place.

[Enter Cleopatra and Julius Caesar]

Julius Caesar:
    Thou art as lovely as the sum of an amazing delicious gentle blossoming warm angel and a charming noble reddest rose.
    Speak your mind. Open your mind. Open your mind. Open your mind! Open your mind!

Cleopatra:
    You are as stuffed as the sum of a hard old green horse and the sum of a grandmother and
    a normal tiny bottomless furry small purple roman.

[Exit Julius Caesar]
[Enter Brutus]

Cleopatra:
    You are as sorry as the difference between a rich morning and a leech.
    You are as smelly as the difference between yourself and a sunny rural blue bold uncle.
    You are as vile as the difference between Julius Caesar and yourself.

[Exit Brutus]
[Enter Cicero]

Cleopatra:
    You are as half-witted as the difference between Brutus and the bluest death.

           Scene II: How do you solve a problem like Cleopatra?

[Exeunt]
[Enter Cleopatra and Julius Caesar]

Julius Caesar:
    Listen to your heart!

[Exit Cleopatra]
[Enter Brutus]

Julius Caesar:
    Is Cleopatra more pretty than a fair charming noble angel?

Brutus:
    If so, we must proceed to Scene IV. Is Cleopatra not worse than the sweetest small aunt?

Julius Caesar:
    If so, let us proceed to Scene III.

Brutus:
    Speak your mind.

Julius Caesar:
    Is Cleopatra nicer than the moon?

Brutus:
    If so, speak your mind.

Julius Caesar:
    Is Cleopatra better than a golden King?

Brutus:
    If so, speak your mind.

Julius Caesar:
    We shall proceed to Scene V.

          Scene III: Brutus and his friends.
Julius Caesar:
    Is Cleopatra as fair as the blossoming smooth sky?

Brutus:
    If so, speak your mind!

Julius Caesar:
    Speak your mind!

Julius Caesar:
    Is Cleopatra jollier than the sum of a yellow sweet road and a summer's day?

Brutus:
    If so, speak your mind!

Julius Caesar:
    Is Cleopatra friendlier than the sum of a sweet large angel and a white cow?

Brutus:
    If so, speak your mind!

Julius Caesar:
    Is Cleopatra as furry as a rich handsome huge mistletoe?

Brutus:
    If so, speak your mind!

Julius Caesar:
    We shall proceed to Scene V.

          Scene IV: Cicero is asked to speak.
[Exit Brutus]
[Enter Cicero]

Julius Caesar:
    Is Cleopatra as beautiful as the sum of a small furry white angel and a summer's day?

Cicero:
    If so, speak your mind!

Julius Caesar:
    Speak YOUR mind!

          Scene V: A period piece -- Cleopatra's reprisal.
[Exeunt]
[Enter Cleopatra and Julius Caesar]

Julius Caesar:
    You are as beautiful as the sum of a embroidered sweetest sunny delicious trustworthy Lord
    and a reddest charming mighty honest King.
    You are as healthy as the difference between yourself and a embroidered Lord. Speak your mind!
    Open your mind! Open your mind! Open your mind! Open your mind! Open your mind! Open your mind!

Cleopatra:
    Are you jollier than the sum of a little rural white bottomless blue blue sky and a rural furry white green old morning?

Julius Caesar:
    If so, we must proceed to Act II. Open your mind! Open your mind!

Cleopatra:
    You are as damned as the difference between yourself and a half-witted dusty snotty rotten oozing death.

[Exit Julius Caesar]
[Enter Brutus]

Cleopatra:
    You are as rotten as the difference between yourself and a rural rotten bottomless evil miserable famine.

[Exit Brutus]
[Enter Cicero]

Cleopatra:
    You are as fatherless as the difference between Brutus and a normal pig. Let us return to Scene II.

          Act II: Lovers' arithmetick.

          Scene I: Our lovers discuss what they have in common.

[Exeunt]
[Enter Romeo and Juliet]

Romeo:
    Thou art as bold as a curse. Listen to your heart!

Juliet:
    Am I better than nothing? If so, let us proceed to Scene III.

Romeo:
    Open your mind. Open your mind.

Juliet:
    Listen to your heart! Open your heart!

Romeo:
    Thou art as amazing as the product of the difference between a handsome white proud white grandfather and an aunt
    and the sum of a loving niece and the Heaven. Speak your mind! Open your mind.
    Listen to your heart. Is the quotient between yourself and the sum of the sum of
    a noble noble mighty blossoming embroidered good father
    and a gentle large large normal old joy and an old happy squirrel as yellow as the quotient between
    myself and the sum of the sum of a pretty beautiful yellow green bold charming kingdom and
    a beautiful blue normal cute large nephew and a pretty big cousin?

Juliet:
    If not, we shall proceed to Scene II.

Romeo:
    You are as sweet as the remainder of the quotient between yourself and the sum of the sum of
    a blossoming bottomless golden peaceful noble healthy nose and
    a happy honest sunny green healthy hero and a hard blue fellow.

Juliet:
    YOU are as sweet as the remainder of the quotient between yourself and the sum of the sum of
    a blossoming bottomless golden peaceful noble healthy nose and
    a happy honest sunny green healthy hero and a hard blue fellow.

          Scene II: Tense times.
Juliet:
    Is the quotient between yourself and the sum of a good beautiful delicious grandmother
    and a noble wind as amazing as the quotient between myself and the sum of
    a smooth furry embroidered roman and a honest sister?

Romeo:
    If so, you are as amazing as the remainder of the quotient between
    yourself and the sum of a cute healthy smooth kingdom and a normal mother.

          Scene III: Parting is such sweet sorrow.
Romeo:
    Open your heart! You are as noble as the sum of a honest charming smooth peaceful fine rose and the sum of
    a cute amazing trustworthy summer's day and an angel. Speak your mind!

```

(It's over 6000 bytes long.) There are some tricks in there but I have not tried to golf it much, because: (1) I already contributed my share of golfing on another answer, and (2) changing all characters to "Page" and "Puck", or all phrases to "big big big big big cat", seems to spoil the fun. Instead for the part that deals with Roman numerals I have used characters who are Romans, etc. I did reuse characters and instructions to save some typing. :-)

The program should be mostly straightforward but one wrinkle worth mentioning is that when I wrote this I assumed that reading an integer would work like `scanf`: (1) consume only as many characters from the input as corresponds to an integer, and (2) in case of failure, leave the variable unchanged. (I used this second property to distinguish between Template 1 and 2 in Act II, by reading up to "Line" and attempting to read an integer.) Unfortunately it turns out that there's (what I consider) a bug in the original implementation of the language where reading an integer consumes everything up to the end of the line and throws an error if it fails, so it needs a patch to `libspl.c` to make `int_input` behave more like `scanf`.

And with that, it works:

```
% spl2c < good.spl > good.c
% gcc -lspl -o good good.c
% for f in in-*; do cat $f; echo "->"; ./good < $f; echo "\n"; done
(Act 1, Scene 2, Lines 345-346)
->
(I.ii.345-6)

(Act 3, Scene 4, Lines 34-349)
->
(III.iv.34-349)

(Act 5, Scene 9, Lines 123-234)
->
(V.ix.123-234)

(Act 3, Scene 4, Line 72)
->
(III.iv.72)

(Act 2, Scene 3, Lines 123-133)
->
(II.iii.123-33)

(Act 4, Scene 8, Lines 124-133)
->
(IV.viii.124-33)

```

Slightly higher-level pseudocode that I worked off of, to help anyone trying to understand:

```
Print `(`=40
Read 5 chars
Read Int A
Output A in Roman
Output `.`=46
Read 8 chars
Read Int S
Output S in roman
Output `.`=46
Read 6 chars
Set N to -1
Read Int N
If N ≠ -1 goto finish
Read 2 chars
Read Int M
Output Int M
Output `-`=45
Read 1 char
Read Int N
Reduce N wrt M
finish:
Output N
Print `)`=41

```

Relating the above to the final code is left as an exercise. :-) Note that ShakespearePL has arithmetic and stacks and gotos but no pointers (only labels), so implementing "subroutines" like the conversion to Roman is a bit… interesting.
> 16 votes

# Answer
## LaTeX, ~~513~~ ~~364~~ ~~259~~ ~~226~~ ~~215~~ ~~178~~ 159 Bytes

Good essays should always be written in LaTeX.

```
\documentclass{tui}\makeatletter\input{xstring}\def~#1 #2, #3 #4, #5 #6){(\@Roman#2.\@roman#4.\StrCut{#6}-\A\B\A\if\B\else-\fi\StrCompare\A\B[\P]\StrMid\B\P9)}

```

This uses the xstring package as there isn't exactly a lot of string handling built in. On the plus side the upper limit for the built-in `\Roman` formatting is larger than we'll ever need (even for the sonnets) at `2^31-1`. I've included `\documentclass{ecv}` in the count, but none of the test code:

```
\begin{document}
\t(Act 1, Scene 2, Lines 345-346)

\t(Act 3, Scene 4, Lines 34-349)

\t(Act 5, Scene 9, Lines 123-234)

\t(Act 3, Scene 4, Line 72)

\t(Act 2, Scene 3, Lines 123-133)

\t(Act 4, Scene 8, Lines 124-133)
\end{document}

```

(If you were crazy enough to actually use this, you'd have to ungolf the macro names at least. Overwriting single character macros is bad practice)

Ungolfed and commented:

```
\documentclass{ecv}%We have to have a documentclass
\makeatletter %treat the @ sign as a normal character (it's used in "internal" macro names)
\input{xstring} %use the xstring package
\def\shortref#1 #2, #3 #4, #5 #6){ %macro with 6 positional arguments searated by spaces and commas
    (%print the open bracket
    \@Roman#2 %arg 2 is the Act,  print uppercase Roman
    .%print the full stop
    \roman#4 %arg 4 is the Scene, lowercase roman
    .%print the full stop
    \StrCut{#6}{-}{\A}{\B}%split arg 6 (Lines) at the hyphen, into macros \A and \B
    \A %print the bit before the hyphen
    \ifx\B\empty%if \B has nothing in it do nothing
    \else %otherwise
        - %we need to print a hyphen
    \fi%endif
    \StrCompare{\A}{\B}[\P] %returns (in macro \P) the position at which \A and \B first differ
    \StrMid{\B}{\P}{9}%print \B starting from position \P (9 > the number of remaining characters)
)}%print the closing bracket

```

Note that in this version the comments are *required* otherwise the newline is interpreted as whitespace and expands to a space.
> 11 votes

# Answer
# JavaScript (ES6), ~~210~~ ~~183~~ ~~178~~ ~~177~~ 171 bytes

*Saved 27 bytes by unrolling rest parameters (thanks to ETHproductions)*

*Saved 5 bytes by not matching the opening paren and by tweaking the roman numeral generation*

*Saved 1 byte by adjusting the final ternary expression*

*Saved 6 bytes by combining two matching groups*

```
s=>s.replace(/Act (\d)\D*(\d)\D*(\d*)(\d*-?)\3(\d*)/,(_,a,b,c,d,e)=>'IIIV'.slice(a>3&&a-2,a)+'.'+'iiiviiix'.slice('233336'[b-4],b-(b>4))+'.'+c+d+(d.length>e.length?e:c+e))

```

## Test Cases:

```
let f = s=>s.replace(/Act (\d)\D*(\d)\D*(\d*)(\d*-?)\3(\d*)/,(_,a,b,c,d,e)=>'IIIV'.slice(a>3&&a-2,a)+'.'+'iiiviiix'.slice('233336'[b-4],b-(b>4))+'.'+c+d+(d.length>e.length?e:c+e))

;[
  ["(Act 1, Scene 2, Lines 345-346)", "(I.ii.345-6)"],
  ["(Act 3, Scene 4, Lines 34-349)", "(III.iv.34-349)"],
  ["(Act 5, Scene 9, Lines 123-234)", "(V.ix.123-234)"],
  ["(Act 3, Scene 4, Line 72)", "(III.iv.72)"],
  ["(Act 2, Scene 3, Line 123-133)", "(II.iii.123-33)"],
  ["(Act 4, Scene 8, Line 124-133)", "(IV.viii.124-33)"],
  ["(Act 1, Scene 2, Lines 345-3499)", "(I.ii.345-3499)"]
].map(([a,b]) => console.log(`${a} => ${f(a)} (${f(a) == b ? 'Pass' : 'Fail'})`))
```

```
.as-console-wrapper { min-height: 100% }
```
> 8 votes

# Answer
# Jelly,  ~~87 86~~  85 bytes

```
DµU=/œr1LCṫ@Ṫ
Ṗ,Çj”-µ⁸L’$?W
⁾-,yḲḊm2Ṗ€Vµ“¬Q:’ṃ⁾IV;”X“¤|ʂ’BṚ¤œṗị@µ1,2¦Œl2¦µ;ṪÇ$“(..)”ż

```

**Try it online!** or see a test suite

### How?

```
DµU=/œr1LCṫ@Ṫ - Link 1, toPageShort: list of numbers [fromPage, toPage]  e.g.  [345,365]
D             - cast to decimal lists                                 [[3,4,5],[3,6,5]]
 µ            - monadic chain separation (call that d)
  U           - reverse each                                          [[5,4,3],[5,6,3]]
   =/         - reduce by equality                                              [1,0,1]
     œr1      - strip any 1s from the right                                       [1,0]
        L     - length                                                                2
         C    - complement (1-z)                                                     -1
            Ṫ - tail d                                                          [3,6,5]
          ṫ@  - tail from index (swap @rguments)                                  [6,5]

Ṗ,Çj”-µ⁸L’$?W - Link 2, format page number(s): number or list of two numbers
           ?  - if:
          $   -   last two links as a monad:
        L     -     length
         ’    -     decremented (0 for a number, 1 for a list of two numbers)
      µ       - then:
Ṗ             -   pop (list without the last item, i.e. just the from page)
  Ç           -   call the last link (1) as a monad with the list as its argument
 ,            -   pair
    ”-        -   literal '-'
   j          -   join
              - else:
       ⁸      -   link's left argument (the single page number)
            W - wrap the result in a list (for ease of post-formatting in Main)

⁾-,yḲḊm2Ṗ€Vµ ... µ1,2¦Œl2¦µ;ṪÇ$“(..)”ż - Main link: string s
⁾-,                                    - literal ['-',',']
   y                                   - map (change '-' to ',')
    Ḳ                                  - split at spaces
     Ḋ                                 - dequeue (get all but 1st)
      m2                               - mod-index-2 (1st,3rd,5th)
        Ṗ€                             - pop €ach (ditch last char)
          V                            - evaluate - list of numbers
                                       -   either [act,scene,page] or
                                       -   [act,scene,[from,to]]
           µ     µ   ¦                 - apply to indexes:
                  1,2                  - [1,2]
             ...                       -   see monadic chain " ... ", below
                        2¦             - apply to index 2:
                      Œl               -   lowercase
                          µ            - monadic chain separation
                              $        - last 2 links as a monad:
                            Ṫ          -   tail (page(s))
                             Ç         -   call last link (2) as a monad
                           ;           - concatenate
                               “(..)”  - literal ['(','.','.',')']
                                     ż - zip together
                                       - implicit print

“¬Q:’ṃ⁾IV;”X“¤|ʂ’BṚ¤œṗị@ - monadic chain " ... " from Main
                         -   Get Roman numeral: number n (n>0, n<10) (act or scene)
“¬Q:’                    - base 250 literal 520559
      ⁾IV                - literal ['I','V']
     ṃ                   - base decompression -> "IIIIIIIVVVIVIIVIIII"
          ”X             - literal 'X'
         ;               - concatenate -> "IIIIIIIVVVIVIIVIIIIX"
                   ¤     - nilad followed by link(s) as a nilad:
            “¤|ʂ’        -   base 250 literal 281418
                 B       -   convert to a binary list
                  Ṛ      -   reverse
                    œṗ   -   split at truthy indexes i.e: I II III IV V VI VII VIII IX
                      ị@ -   index into (swap @arguments) using n

```
> 8 votes

# Answer
# , ~~94~~ ~~126~~ ~~112~~ 166 bytes

And now it's wordier than before :(, back to trying to golf it further. Regex for reducing the page reference shamelessly ~~stolen~~ borrowed from @FryAmTheEggman.

Now I really need to do some work to get back the bytes, but it works for the second case now.

```
R=as.roman;i=sub(',','',scan(,''));sprintf('(%s.%s.%s',R(i[2]),tolower(R(i[4])),`if`(!diff(c(nchar(el(strsplit(i[6],'-'))),0))-1,sub('((.+).*-)\\2','\\1',i[6]),i[6]))

```

Try it online! \- Note that `el` doesn't work on TIO and has been replaced with `unlist`

```
R=as.roman;                              # Used to convert to roman numeral class
i=sub(',','',scan(,''));                 # Get input, splits on spaces, remove ,'s
sprintf('(%s.%s.%s',                     # Use sprintf to format the output.
    R(i[2]),                             # Convert to roman numeral
    tolower(R(i[4])),                    # Convert to roman numeral and lowercase
    `if`(                                #
       !diff(                            # Test if the lengths of the last string
       c(nchar(el(strsplit(i[6],'-'))),0)# split on the hyphen are different (extra 0 to appease diff)
       )-1,                              # taking into account the trailing )
       sub('((.+).*-)\\2','\\1',i[6]),   # on true use regex to reduce range
       i[6]                              # else output as is
    )
)

```
> 6 votes

# Answer
# Retina, ~~89~~ 88 bytes

```
T`, lL`._
2`(\d+)
$*i
i{5}
v
i{4}
iv
viv
ix
1T`l`L`\w+
(\b(.+)(.)*-)\2((?<-3>.)*)\b
$1$4

```

Try it online!

Saved 3 bytes thanks to Neil.

Strips away the unnecessary characters before replacing the first two numbers with blocks of `i` characters. Then it matches chunks of these `i`s to form the appropriate roman numerals. Then we capitalise the first roman numeral. Finally we match as many numbers as we can before the hyphen and after the hyphen such that the number of digits in the number is the same. We then remove that prefix from the second number.
> 4 votes

# Answer
# PHP\>=7.1, 195 Bytes

```
preg_match_all("#\d+#",$argn,$t);[[$a,$s,$b,$e]]=$t;for(;$e&&~$c=$e[$k-=1];$p="-".substr($e,$i))$c>$b[$k]&&$i=$k;echo"(",strtoupper(($r=[_,i,ii,iii,iv,v,vi,vii,viii,ix])[$a]),".$r[$s].$b",$p,")";

```

Testcases

Expanded

```
preg_match_all("#\d+#",$argn,$t); # match for all groups of digits
[[$a,$s,$b,$e]]=$t; # shorter variables names for these groups
for(;$e&&~$c=$e[$k-=1];$p="-".substr($e,$i)) # prepare the seceond line if exists
  $c>$b[$k]&&$i=$k;
echo"(" # print the char (
,strtoupper(($r=[_,i,ii,iii,iv,v,vi,vii,viii,ix])[$a]) # print the upper roman digit for Act
,".$r[$s].$b" # print the lower roman digit for Scene and the first line with trailing "."
,$p # print shorted second Line
,")"; #Print the closing )

```
> 4 votes

# Answer
# Perl 5, 185 + 1 = 186 bytes

1 byte penalty for the required `-n` flag.

May fail for some test cases where the scene has more than 10^11 lines, but AFAIK no Shakespeare scenes are quite that long ;)

```
y/A-z //d;while($x++<9){s/,(\d+)(\d{$x})-\g1(\d{$x}\))/,$1$2-$3/};@F=split/,/;for($F[0],$F[1]){$_.='i'while(y/2-91/1-8/d);s/i{5}/v/g;s/i{4}/iv/;s/v(i)?v/$1x/;s/$/,/};$F[0]=uc$F[0];say@F

```

In readable form:

```
y/A-z //d; #Delete all characters besides numbers, parenthesis, and comma
while($x++<9){s/,(\d+)(\d{$x})-\g1(\d{$x}\))/,$1$2-$3/}; #Shortens the line numbers. Super ugly, but my simpler code broke on test case 2- that fix added 26 bytes :( I'll revisit this later, perhaps...
@F=split/,/; #Splits the input into an array so we can mess with the act and scene without messing with the lines
for($F[0],$F[1]){ #For loop over the act and scene
    $_.='i'while(y/2-91/1-8/d); #Recursively turn numbers into naive Roman numerals (i.e. 9 would be iiiiiiiii)
    s/i{5}/v/g;s/i{4}/iv/;s/v(i)?v/$1x/;s/$/,/ #Substitution rules to convert naive Roman numerals into real Roman numerals and add a comma to the end
}
$F[0]=uc$F[0]; #Convert act to uppercase
say@F #Output

```
> 3 votes

# Answer
# Python 2, ~~301~~ ~~259~~ ~~252~~ 221 bytes

*A whopping -31 bytes thanks to Chas Brown.*

So, uh, this is... extremely long... I think I can golf this but I've been wracking my brain for a while.

```
import re
def f(s):s,r=re.match(r'.*?(\d),.*?(\d), .*? (\d*)(\d*-?)\3(\d*)',s),'0 i ii iii iv v vi vii viii ix'.split();b,c,d,e,f=s.groups();print'(%s.%s.%s)'%(r[int(b)].upper(),r[int(c)],d+e+(f if len(e)>len(f)else d+f))

```

Try it online!

## Breakdown

```
import re                     # re module for regex stuff

def f(s):                     # function that accepts one argument

    s, r = (re.match(r'.*?(\d),.*?(\d), .*? (\d*)(\d*-?)\3(\d*)', s),
           # match the string and capture the important parts using regex

           '0 i ii iii iv v vi vii viii ix'.split()
           # array that stores roman numerals

    b, c, d, e, f = s.groups()
                    # all the numbers from the match to variables

    print '(%s.%s.%s)' % (
                              r[int(b)].upper(),
                              # get the respective roman numeral and make it uppercase

                              r[int(c)],
                              # get the respective roman numeral

                              d + e + (f if len(e) > len(f) else d + f)
                              # shorten the second number if it's shorter than the first number
                         )

```
> 2 votes

# Answer
# Ruby, 204+1 = 205 bytes

Uses the `-p` flag.

```
d=[r=%w"i ii iii iv v vi vii viii ix",r.map(&:upcase)]
i=-1
gsub(/\w+ ([\d-]+)/){(a=d.pop)?a[$1.hex]:(a,b=$1.split ?-;b ?(a="%0#{b.size}d"%a;b[0]=""while b[0]==a[i+=1];a.sub(/^0*/){}+?-+b):a)}
gsub", ",?.

```

Try it online!
> 2 votes

# Answer
# Python 2.7 298 bytes

```
import re
r=lambda n:'iiiviiix'[2*(n>3)+(n>4)+3*(n>8):n-(n>4)]
o=lambda x,y,n=0:n*(len(x)==len(y))if not x or x[0]!=y[0]else o(x[1:],y[1:],n+1)
q=lambda a,s,g,h:(r(int(a)).upper(),r(int(s)),g+'-'+h[o(g,h):]if h else g)
f=lambda p:'(%s.%s.%s)'%q(*re.match('\D*(\d)\D*(\d)\D*(\d+).(\d*)',p).groups())

```
> 2 votes

# Answer
## Perl, 99 bytes

```
/(.+)(-\1|.(?2).)\b/;@r=(s/-$1/-/,I,II,III,IV,V,VI,VII,VIII,IX);s/Act(.+)(.,).+ /$r[$1].\L$r[$2]./

```

Run with `perl -pe`. 98 bytes (source) + 1 byte (`p` flag) = 99.
> 2 votes

# Answer
# q/kdb+, ~~200~~ 187 bytes

**Solution:**

```
f:{R:(($:)N:(!)11)!($:)``i`ii`iii`iv`v`vi`vii`viii`ix`x;S:","vs x inter .Q.n,",-";L:"-"vs P:S 2;"(",("."sv(upper R S 0;R S 1;$[{x[y]=x z}[#:;F:L 0;T:L 1];F,"-",((*:)N(&:)F<>T)_T;P])),")"}

```

**Examples:**

```
q)f "(Act 1, Scene 2, Lines 345-346)"
"(I.ii.345-6)"
q)f "(Act 3, Scene 4, Lines 34-349)"
"(III.iv.34-349)"
q)f "(Act 5, Scene 9, Lines 123-234)"
"(V.ix.123-234)"
q)f "(Act 3, Scene 4, Line 72)"
"(III.iv.72)"
q)f "(Act 2, Scene 3, Lines 123-133)"
"(II.iii.123-33)"
q)f "(Act 4, Scene 8, Lines 124-133)"
"(IV.viii.124-33)"

```

**Explanation:** (slightly ungolfed)

```
f:{
  // create map of 0->10 to roman numerals, e.g. "5" -> "v"
  R:(($:)N:(!)11)!($:)``i`ii`iii`iv`v`vi`vii`viii`ix`x;
  // remove everything from the input string except -, then split on ,
  S:","vs x inter .Q.n,",-";
  // split the final field on '-', also save final field in variable P
  L:"-"vs P:S 2;
  // if the length of from/to lines are the same then find the first character
  // where they differ, and cut this many characters from the 'to' string
  M:$[{x[y]=x z}[#:;F:L 0;T:L 1];F,"-",((*:)N(&:)F<>T)_T;P];
  // join everything together, use act/scene to index into
  // the roman numeral map, uppercase the act
  "(",("."sv(upper R S 0;R S 1;M)),")"
  }

```

**Notes:**

Technically it can be 2 bytes shorter (no need for the `f:`) but makes it easier to show examples this way.

**Edits:**

* -13 bytes; replaced `string` with `$:`, `count` with `#:`, `til` with `(!)` and `first` with `(*:)`, cast the indices of R to strings so we dont have to cast act/scene into ints
> 2 votes

---
Tags: code-golf, string, parsing
---


title: Build a staircase for my kid

text:
# Question
Title: Build a staircase for my kid
The other day, my son asked me to build him a staircase using Lego-ish blocks. And I came up with something like this:

Then my kid asked me for a program using the least number of bytes that generated a similar staircase in a computer screen. I am not that good at , so I need your help. I need a program that:

* Receives a positive integer with the number of levels the staircase needs to have.
* Outputs a drawing of a staircase, with the pattern you see in the image.

The output will be in text format but the bricks can be distinguished one from another. For instance, you may use the '█' character as half a block and paint it in any color you want, or just choose any character of your choice.

Restrictions:

* Blocks need to be of three different colors, which will be used as long as possible (if input is 1 or 2 there are not enough blocks to use all three colors). If you want, you may use the '░▒▓' characters, for instance, or just select three different characters.
* No two blocks of the same color or pattern can be side to side in a single row.

My son does not really care about trailing spaces or new lines as long as a staircase is drawn.

Examples (sorry for the bad choice of characters):

```
Input: 1
Output:
██

Input: 2
Output:
██
 ▓▓

Input: 3
Output:
██
 ▓▓
██░░

Input: 5
Output:
██
 ██
██░░
 ██░░
██░░▓▓

```

# Answer
# Jelly,  ~~21 19~~  16 bytes

```
d2SR+%3x2⁶;ṙḂµ€Y

```

A full program printing the result.

Uses `00`, `11`, and `22` as the blocks.

**Try it online!**

### How?

```
d2SR+%3x2⁶;ṙḂµ€Y - Main link: number n
             µ€  - for €ach "row" in n (i.e. for row, r = 1 to n inclusive):
d2               -   divmod 2   -> [integer-divide by 2, remainder] i.e. [r/2, r%2]
  S              -   sum        -> r/2 + r%2
   R             -   range      -> [1, 2, 3, ..., r/2 + r%2]
    +            -   add r      -> [r+1, r+2, r+3, ..., r + r/2 + r%2]
     %3          -   modulo 3   -> [r%3+1, r%3+2, r%3+0, ..., (r + r/2 + r%2)%3]
                 -   e.g.: r: 1  , 2  , 3    , 4    , 5      , 6      , 7       , ...
                             [2], [0], [1,2], [2,0], [0,1,2], [1,2,0], [2,0,1,2], ...
       x2        -   times 2 - repeat each twice (e.g. [2,0,1,2] -> [2,2,0,0,1,1,2,2]
         ⁶       -   literal space character
          ;      -   concatenate (add a space character to the left)
            Ḃ    -   r mod 2 (1 if the row is odd, 0 if it is even (1 at the top))
           ṙ     -   rotate (the list) left by (r mod 2)
               Y - join with newlines
                 - implicit print (no brackets printed due to the presence of characters)

```
> 5 votes

# Answer
# Python 2, 55 bytes

```
i=2
exec"print(i%2*' '+`2%i*1122`*i)[:i];i+=1;"*input()

```

Try it online!

Cycles between blocks of `22, 44`, except the top row is `00`. For example, on input 10, prints

```
00
 22
2244
 2244
224422
 224422
22442244
 22442244
2244224422
 2244224422

```

Prints rows of increasing length `i=2,3,..` by creating a space for odd lengths, repeating the pattern `i` times, and trunctating to length `i`. The pattern is `2244` for all rows except the first one `i=2` for which it's `0`. This is achieved with the arithmetic expression `2%i*1122`.
> 11 votes

# Answer
# JavaScript (ES6), 80 bytes

```
n=>eval(`for(s=11,i=1;i++<n;)s+='\\n'+(' '+'2233'.repeat(n)).substr(i%2,i+1);s`)

```

```
f=
n=>eval(`for(s=11,i=1;i++<n;)s+='\\n'+(' '+'2233'.repeat(n)).substr(i%2,i+1);s`)
console.log(f(+prompt()))
```

---

# JavaScript (ES6), 87 bytes

Previous solution.

```
n=>[11,...Array(n).fill(' '+'2233'.repeat(n)).map((r,n)=>r.slice(n%2,n+3+n%2))].join`
`

```
> 4 votes

# Answer
# SOGL, ~~31~~ ~~28~~ ~~27~~ 25 bytes

```
∫³2\@*O"²b“2⁵I%*r*;I»«nKp

```

Explanation:

```
∫                          iterate input times, pushing 1-indexed counter
 ³                         get 3 total copies of it on stack
  2\                       1 if divides by 2, else 0
    @*                     get that many spaces
      O                    output in a new line
       "²b“                push 1122
           2⁵I%*           multiply 1122 by 2%(iteration+1)
                r          convert to string
                 *         multiply by iteration
                  ;I»«     get one iteration variable ontop of stack
                      n    increase, floor divide by 2, multiply by 2 (gets the amount of bricks in a line)
                       Kp  split that multiplied string in pieces of that length

```

using this technique
Example output for 9:

```
00
 22
2244
 2244
224422
 224422
22442244
 22442244
2244224422

```

### 22 bytes

```
∫³2\@*O"²b“2⁵I%*;I»«mp

```

The command `m` has been documentated on the 1st SOGL commit, just not implemented.
> 3 votes

# Answer
# 05AB1E, ~~22~~ ~~21~~ ~~20~~ ~~18~~ 17 bytes

Uses the interesting fact that `4^(N+2)/5 = [3,12,51,204,...] = b[11,1100,110011,11001100,...]`

```
F4NÌm5÷bDðì}r·IF,

```

Try it online!

**Explanation**

```
F                     # for N in 0...input-1 do
 4                    # push 4
  NÌ                  # push N+2
    m                 # push 4^(N+2)
     5÷               # integer division by 5
       b              # convert to binary
        D             # duplicate
         ðì           # prepend a space to the copy
           }          # end loop
            r         # reverse stack
             ·        # multiply top of stack by 2
              IF      # input times do
                ,     # print with newline

```
> 3 votes

# Answer
## PHP, ~~61~~ 59

```
aa<?for(;++$i<$argn;)echo"
",str_pad(" "[~$i&1],2+$i,bbcc);

```

works pretty much like the python versions but uses all three colors if possible. No trailing new line.

```
-2 bytes by @user63956. Thanks !

```
> 2 votes

# Answer
# Pyth, 29 bytes

```
VQI!%hN2pd)Vh/N2p*2@G%+NH3)pb

```

Test it online!

**Explanations**

```
VQI!%hN2pd)Vh/N2p*2@G%+NH3)pb

VQ                               For N in range(0, input)
  I!%hN2pd)                      If N is odd, print a leading space
           Vh/N2          )      For H in range(0, N / 2 + 1)
                   @G%+NH3       Select the letter at position (N + H) % 3 in the alphabet
                 *2              Then make it a two letters string ("aa" or "bb" or "cc")
                p                Print it
                           pb    End the line by printing a new line

```

I am sure there are a lot of ways to shorten that code, but I am king of tired right now... Will try later.
> 1 votes

# Answer
## Batch, 125 bytes

```
@set s=█
@for /l %%i in (2,1,%1)do @call:c
:c
@set s= %s:█= %
@set s=%s:▓=█%
@set s=%s:░=▓%
@set s=%s:  =░░%
@echo %s%

```

Note: Save this in CP437 or CP850 or some such. Works by rotating the colours each time. Since I can't map over the string to perform the rotation, I use four replacements, using spaces as a temporary stage. This then also allows me to prefix a space every line, so that two spaces turn into a new block. Sample output:

```
░░
 ▓▓
░░██
 ▓▓░░
░░██▓▓

```
> 0 votes

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


title: A+B using C++ language

text:
# Question
Title: A+B using C++ language
I'm golfing a program to sum two numbers in C++.

Example:

```
10 3
13

```

I found out that this problem can be solved in 54 symbols (without spaces and so on) using C++. My code (63 symbols):

```
#include <iostream>
main() {
    int a, b;
    std::cin >> a >> b;
    std::cout << a + b;
}

```

I have no idea how to make my program shorter. Can you help me, please?

# Answer
# 48 bytes

How about...

```
#include<cstdlib>
main(){system("tr \\  +|bc");}

```

...not using C++?

---

* The call to `system` runs commands on your shell (`<cstdlib>` declares `system`).
* `tr \\ +` executes the command `tr`, translating spaces to `+` (so the input`34 45` becomes `34+45`).
* `|` pipes `tr`'s STDOUT into `bc`'s STDIN.
* `bc` performs equations in STDIN and prints the result to STDOUT.
> 5 votes

---
Tags: code-golf, arithmetic, tips, c++
---


title: Verbose IP Range Generator

text:
# Question
Title: Verbose IP Range Generator
The task is simple, given two IP adresses `a` and `b`, output all addresses within that range.

---

# Examples

Example #1:

```
f(a = 192.168.0.1, b = 192.168.0.4)
    192.168.0.1
    192.168.0.2
    192.168.0.3
    192.168.0.4

```

Example #2 (TIO will truncate this, use a smaller range when testing):

```
f (a = 123.0.200.0, b = 124.0.0.0)
    123.0.200.0
    123.0.200.1
    ...            # Omitted pattern
    123.0.200.255
    123.0.201.0
    ...            # Omitted pattern
    123.0.201.255
    ...            # Omitted pattern
    123.0.255.255
    123.1.0.0
    ...            # Omitted pattern
    123.255.255.255
    124.0.0.0

```

# Input and Output

* `a < b` in other words:
    + **Defined Programatically**: `a[0] < b[0] || (a[0] == b[0] && a[1] < b[1]) || (a[0:1] == b[0:1] && a[2] < b[2]) || (a[0:2] == b[0:2] && a[3] < b[3])`
    + **Defined in Words:** `a` will always be lower than `b` (so you will have to increment the subnet to reach `b`).
    + No, you ***do not*** have to handle `a == b` (if you do, kudos).
* Output should be in order from "lowest" to "highest" (see examples).
* For this challenge, the valid syntax for an IP is: `\d{1-3}\.\d{1-3}\.\d{1-3}\.\d{1-3}`.
* You do not have to handle non-IP address input, if it's unexpected input you may error.
* Output may be as an array or as a delimited string (using any whitespace character).

# Winning

# Answer
# Pyth, 22

```
mj\.jd256}FmivMcd\.256

```

Try it online.

```
               cd\.       # split string by "."
             vM           # eval list (convert strings to integers)
            i      256    # convert list of base256 digits to integer
           m          Q   # map the above over implicit input list
         }F               # inclusive range
    jd256                 # convert to list of base256 digits
 j\.                      # join by "."
m                         # map over inclusive range

```
> 3 votes

# Answer
## Batch, 623 bytes

```
@echo off
set s=%1.%2
call:c %s:.= %
exit/b
:c
if %1==%5 goto d
call:d %1 %2 %3 %4 %1 255 255 255
set/al=%1+1,u=%5-1
for /l %%i in (%l%,1,%u%)do call:d %%i 0 0 0 %%i 255 255 255
call:d %5 0 0 0 %5 %6 %7 %8
exit/b
:d
if %2==%6 goto e
call:e %1 %2 %3 %4 %1 %2 255 255
set/al=%2+1,u=%6-1
for /l %%j in (%l%,1,%u%)do call:e %1 %%j 0 0 %5 %%j 255 255
call:e %5 %6 0 0 %5 %6 %7 %8
exit/b
:e
if %3==%7 goto f
call:f %1 %2 %3 %4 %1 %2 %3 255
set/al=%3+1,u=%7-1
for /l %%k in (%l%,1,%u%)do call:e %1 %2 %%k 0 %5 %6 %%k 255
call:e %5 %6 %7 0 %5 %6 %7 %8
exit/b
:f
for /l %%l in (%4,1,%8)do echo %1.%2.%3.%%l

```

Unfortunately Batch's 32-bit arithmetic can't print all IP addresses, so I have to split it up into octets.
> 3 votes

# Answer
# Python 2, 128 bytes

```
a,b=[reduce(lambda a,b:a<<8|int(b),x.split('.'),0)for x in input()]
while a<=b:print'.'.join(`a>>i&255`for i in[24,16,8,0]);a+=1

```

Try it online!
> 2 votes

# Answer
# PHP, 71 Bytes

Output as string

```
for($s=ip2long($argv[1]);$s<=ip2long($argv[2]);)echo long2ip($s++)," ";

```

Try it online! or Output as array

```
print_r(array_map(long2ip,range(ip2long($argv[1]),ip2long($argv[2]))));

```

Try it online!
> 2 votes

# Answer
# Jelly, 18 bytes

```
ṣ”.V€ḅ⁹µ€r/b⁹j”.$€

```

Try it online!

The output appears to by a mush of digits and decimals, but is stored internally as a list of strings. Append a `Y` to the end (+1 byte) to join the strings by newlines.

**How it Works**

```
ṣ”.V€ḅ⁹µ€r/b⁹j”.$€ - main link, input is a list of addresses which are strings
       µ€          - for each address string,
ṣ”.                  - split on periods
   V€                - eval each element in the list (convert strings to numbers)
     ḅ⁹              - transform from base 256 to integer (⁹ is 256)
         r/        - take the inclusive range
           b⁹      - convert each element in the range from integer to base 256
             j”.$€ - join each address with periods.

```
> 2 votes

# Answer
# JavaScript (ES6), 104 bytes

```
g=s=>s.replace(/(\d+)\.256/,(_,n)=>++n+'.0')
f=(a,b)=>a==b?a:a+`
`+f(g(g(g(g(a+'.256').slice(0,-2)))),b)

```

This solution replaces the pattern **n**.256 with **n+1**.0, and it calls itself recursively until the two parameters are equal.

It appends '.256' to the initial input to get the ball rolling. `slice(0,-2)` is then used to remove the trailing '.0'.

**Examples:**

```
g=s=>s.replace(/(\d+)\.256/,(_,n)=>++n+'.0')
f=(a,b)=>a==b?a:a+`
`+f(g(g(g(g(a+'.256').slice(0,-2)))),b)

console.log('192.168.0.1 ... 192.168.0.4');
console.log(f('192.168.0.1', '192.168.0.4'));

console.log('123.255.255.0 ... 124.0.3.0');
console.log(f('123.255.255.0', '124.0.3.0'));

console.log('192.1.1.1 ... 192.1.1.1 ... kudos');
console.log(f('192.1.1.1', '192.1.1.1'));
```
> 2 votes

# Answer
# Java (OpenJDK 8), ~~339~~ ~~314~~ 282 bytes

Golfed:

```
long f(String i)throws Exception{return java.nio.ByteBuffer.wrap(java.net.InetAddress.getByName(i).getAddress()).getInt()&(1L<<32)-1;}void g(String[] a)throws Exception{for(long l=f(a[0]),m=255;l<=f(a[1]);)System.out.println(((l>>24)&m)+"."+((l>>16)&m)+"."+((l>>8)&m)+"."+(l++&m));}

```

Ungolfed:

```
long ipToLong(String ip) throws Exception {
    return java.nio.ByteBuffer.wrap(java.net.InetAddress.getByName(ip).getAddress()).getInt() & (1L << 32) - 1;
}

void printRange(String[] ips) throws Exception {
    for (long ip = ipToLong(ips[0]), m = 255; ip <= ipToLong(ips[1]);)
        System.out.println(((ip >> 24) & m) + "." + ((ip >> 16) & m) + "." + ((ip >> 8) & m) + "." + (ip++ & m));
}

```

Try it online!
> 1 votes

---
Tags: code-golf, networking
---


# Question
Title: Most optimized algorithm for incrementing squares
Write the "fastest" program to print an incrementing series of squares from a given input to a given input.

Example input:

```
-2
7

```

Example output:

```
4, 1, 0, 1, 4, 9, 16, 25, 36, 49

```

When using a "cryptic" language, please post the pseudocode, in addition to your program.

The entries will be judged on the most efficient algorithm.

# Answer
> 9 votes
The tag says "code-challenge", but I don't see any challenge. Just some mathematics we studied when I was about 12.

```
import java.util.*;

public class IncSquares
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int min = in.nextInt();
        int max = in.nextInt();

        int sq = min * min;
        System.out.print(sq);
        while (min < max) {
            sq += (min << 1) + 1;
            min++;
            System.out.print(", " + sq);
        }
        System.out.println();
    }
}

```

# Answer
> 1 votes
**Python**

```
print ", ".join(`x*x` for x in range(int(raw_input()), int(raw_input())+1))

```

# Answer
> 1 votes
## C

Since my usual language interpreter has a one-second startup time already, I chose not to use it here.

```
#include <stdio.h>

int main(void) {
    int start, end, i;
    scanf("%d\n%d", &start, &end);
    for (i = start; i <= end; i++) {
        printf("%d", i*i);
        if (i != end)
            printf(", ");
    }
    return 0;
}

```

# Answer
> 1 votes
## Ruby

```
a,b=*$<.map(&:to_i)
p (a+1..b).reduce([a**2]){|m,x|m<<m[-1]+x+x-1;m}*?,

```

# Answer
> 0 votes
# Jelly 12 bytes

```
+³’µ²
_N‘RÇ€

```

---

**Explanation**

```
+³’µ²
 ³’    -Decrement the first argument
+      -Sum it
   µ   -Groups the functions prior to this
    ²  -Square the result

_N‘RÇ€
_      -Subtract the two arguments
 N     -Negate the difference
  ‘    -Increment the difference
   R   -Generate Range from Difference
    Ç€ -Map range with above function

```

Try it online!

# Answer
> -1 votes
```
(z + 1)^2 = z^2 + (2z + 1)

```

We already know `z^2`, and 2z is simply `z<<1`.

```
(z + 1)^2 = (z^2) + (z << 2 + 1)

```

---

Now just memorize this trick if you want to list squares in your head.

If you've got an arbitrary \[two-digit\] square (to do in your head), `z^2`, do this:

```
z^2 = (z-n)*(z+n) + n^2

```

Or:

```
23^2 = (23-3)*(23+3) + 3^2
23^2 = 20*26 + 9
23^2 = 520 + 9
23^2 = 529

```

Works even "faster" with larger numbers, relative to you doing `97*97` in your head. Have fun showing off.

---
Tags: code-challenge
---


title: Expand that Australian state

text:
# Question
Title: Expand that Australian state
There are 8 Australian states and territories, each with a 2 or 3 letter abbreviation:

* ACT: Australian Capital Territory
* NSW: New South Wales
* NT: Northern Territory
* QLD: Queensland
* SA: South Australia
* TAS: Tasmania
* VIC: Victoria
* WA: Western Australia

> Your task is to write a function/program which takes a valid Australian state abbreviation in upper case, and returns the correct full name (case-sensitive as above).

No extra whitespace permitted, other than a single trailing newline where this is an unavoidable side-effect of every program in that language.

For example:

`f("TAS") => "Tasmania"`

Standard rules (shortest code in bytes wins!) and loopholes apply.

# Answer
# Retina, ~~135~~ 121 bytes

*13 bytes golfed thanks to @Neil by using clever space insertion tactics, which inspired one more byte being golfed*

```
AS
asmania
^W
Western
NT
NorthernT
T$
 Territory
A
Australia
aC
an Capital
IC
ictoria
LD
ueensland
SW
ew SWales
S
South

```

Try it online!

Note the trailing spaces on the fourth and the last lines.
> 9 votes

# Answer
# Jelly, 56 bytes

```
OS%15ị“ÞÑṿ“ıÐṁṾṗ“¡ʋẹḢ⁾ḅ“¢T¡ż¶““msẒw²ẉṪP“ØÑĊ“©$Ḅ3ẊḳƓ“ÇH°»

```

A monadic link taking and returning lists of characters.

See all cases at **Try it online!**

*Note:* Reusing the words "Australia" and "Territory" does not help reduce the byte count.

### How?

Taking the sum of the ordinals of the eight state abbreviations modulo 15 gives 8 unique values. Taking the results of those modulo 9 maintains uniqueness.

```
OS%15ị“ ... » - Main link: list of characters a
O             - cast to ordinals
 S            - sum
  %15         - modulo 15
      “ ... » - list of compressed strings:
              -   "Victoria"
              -   "Western Australia"
              -   "Northern Territory"
              -   "South Australia"
              -   ""
              -   "Australian Capital Territory"
              -   "Tasmania"
              -   "New South Wales"
              -   "Queensland"
     ị        - index into (1-indexed and modular - hence the single empty entry)

```
> 5 votes

# Answer
## Haskell, ~~193~~ 192 bytes

```
f"NSW"="New South Wales"
f"QLD"="Queensland"
f"ACT"=a++"n Capital"++t
f"VIC"="Victoria"
f"TAS"="Tasmania"
f"SA"="South "++a
f"NT"="Northern"++t
f"WA"="Western "++a
a="Australia"
t=" Territory"

```

Somewhat naive solution, but I wanted to go for a fairly simple challange for my first. I'm not even sure if better is possible in Haskell.

Saved a byte by moving the space into t
> 5 votes

# Answer
## Mathematica, 177 bytes

Obvious solution: (199 bytes)

```
<|"ACT"->"Australian Capital Territory","NSW"->"New South Wales","NT"->"Northern Territory","QLD"->"Queensland","SA"->"South Australia","TAS"->"Tasmania","VIC"->"Victoria","WA"->"Western Australia"|>

```

Improved solution: (182 bytes, only runnable on my Wolfram Mathematica 10.2 computer)

```
{,"Northern Territory","Queensland",,,,,"Australian Capital Territory","New South Wales",,,"Tasmania",,,"Western Australia","Victoria",,,,,,,,,,,,"South Australia"}[[Hash@#~Mod~29]]&

```

Best solution:

```
{,"Northern Territory","Queensland",a="Australia",,,,a<>"n Capital Territory","New South Wales",,,"Tasmania",,,"Western "<>a,"Victoria",,,,,,,,,,,,"South "<>a}[[Hash@#~Mod~29]]&

```

Unfortunately repeat `" Territory"` can save only 0 bytes.

It seems that the default Hash function of Mathematica change over versions. But adding a method will make code longer. Using the default Hash function of Mathematica sandbox now can make code shorter by about 9 bytes.

## Mathematica (sandbox - now - version 11), 168 bytes

```
{a="Australia","Western "<>a,,,,"South "<>a,,a<>"n Capital Territory",,,,"Tasmania","Northern Territory",,,,"New South Wales","Victoria","Queensland"}[[Hash@#~Mod~20]]&

```
> 3 votes

# Answer
# Python, 181 bytes

*1 byte saved thanks to @Jonathan Allan*

```
lambda a,s='Australia',t=' Territory':[s+'n Capital'+t,'New South Wales','Northern'+t,'Queensland','South '+s,'Tasmania','Victoria','Western '+s]['ACNSNTQLSATAVIWA'.index(a[:2])//2]

```

Try it online!
> 2 votes

# Answer
# Sed, ~~167~~ 157 bytes

```
s/T$/ Territory/
s/N /Northern /
s/AS/asmania/
s/IC/ictoria/
s/LD/ueensland/
s/W$/Wales/
s/A/Australia/
s/C/n Capital/
s/NS/New S/
s/^W/Western /
s/S/South /

```
> 2 votes

# Answer
# PHP, 148 143 bytes

```
<?=strtr(["0n Capital 3",Victoria,Queensland,West20,10,Tasmania,North23,"New 1 Wales"][md5(hj.$argn)%8],[Australia,"South ","ern ",Territory]);

```

Saved 5 bytes thanks to Jörg Hülsermann.
> 1 votes

# Answer
## C#, 289 bytes

---

### Data

* **Input** `String` `s` The abbreviation of the state.
* **Output** `String` The expanded state name

---

### Golfed

```
(string s)=>{return new System.Collections.Generic.Dictionary<string,string>(){{"ACT","Australian Capital Territory"},{"NSW","New South Wales"},{"NT","Northern Territory"},{"QLD","Queensland"},{"SA","South Australia"},{"TAS","Tasmania"},{"VIC","Victoria"},{"WA","Western Australia"}}[s];};

```

---

### Ungolfed

```
( string s ) => {
    return new System.Collections.Generic.Dictionary<string, string>() {
        { "ACT", "Australian Capital Territory" },
        { "NSW", "New South Wales" },
        { "QLD", "Queensland" },
        { "TAS", "Tasmania" },
        { "VIC", "Victoria" },
        { "NT", "Northern Territory" },
        { "SA", "South Australia" },
        { "WA", "Western Australia" }
    }[ s ];
};

```

---

### Ungolfed readable

```
// Takes a state name abbreviated
( string s ) => {

    // Creates a dictionary with the state name abbreviated and the full state name and returns the one that match
    return new System.Collections.Generic.Dictionary<string, string>() {
        { "ACT", "Australian Capital Territory" },
        { "NSW", "New South Wales" },
        { "QLD", "Queensland" },
        { "TAS", "Tasmania" },
        { "VIC", "Victoria" },
        { "NT", "Northern Territory" },
        { "SA", "South Australia" },
        { "WA", "Western Australia" }
    }[ s ];
};

```

---

### Full code

```
using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<String, String> f = ( string s ) => {
             return new System.Collections.Generic.Dictionary<string, string>() {
                 { "ACT", "Australian Capital Territory" },
                 { "NSW", "New South Wales" },
                 { "QLD", "Queensland" },
                 { "TAS", "Tasmania" },
                 { "VIC", "Victoria" },
                 { "NT", "Northern Territory" },
                 { "SA", "South Australia" },
                 { "WA", "Western Australia" }
             }[ s ];
         };

         List<String>
             testCases = new List<String>() {
                 "ACT",
                 "NSW",
                 "QLD",
                 "TAS",
                 "VIC",
                 "NT",
                 "SA",
                 "WA",
             };

         foreach( String testCase in testCases ) {
             Console.WriteLine( $"Input: {testCase}\nOutput: {f( testCase )}\n");
         }

         Console.ReadLine();
      }
   }
}

```

---

### Releases

* **v1.0** \- `289 bytes` \- Initial solution.

---

### Notes

* None
> 0 votes

# Answer
# Rexx (Regina), ~~148~~ 147 bytes

```
a=Australia
t=Territory
s=South
ac=a'n' Capital t
ns=New s Wales
nt=Northern t
qs=Queensland
sa=s a
ta=Tasmania
vi=Victoria
wa=Western a
arg x 3
say value(x)

```

Try it online!
> 0 votes

# Answer
# JavaScript (ES6), 167 bytes

```
s=>({A:`${A='Australia'}n Capital ${T='Territory'}`,N:s[2]?'New South Wales':'Northern '+T,T:'Tasmania',Q:'Queensland',S:'South '+A,V:'Victoria',W:'Western '+A}[s[0]])

```

```
f=
s=>({A:`${A='Australia'}n Capital ${T='Territory'}`,N:s[2]?'New South Wales':'Northern '+T,T:'Tasmania',Q:'Queensland',S:'South '+A,V:'Victoria',W:'Western '+A}[s[0]])

console.log('ACT NSW NT QLD SA TAS VIC WA'.split(' ').map(f))
```
> 0 votes

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


# Question
Title: Generate all halting Smallfuck programs of length n
Your task is to write a program that, given a number *n*, returns a list of all valid, halting Smallfuck programs of length *n*, in any order.

Actually, we're using a variation of Smallfuck called F2, which is just Smallfuck with a right-unbounded tape. For the purposes of this challenge, a program that moves left from the start of the tape is considered invalid, as is one with unbalanced brackets.

## Scoring

Since solving this for every *n* is impossible (as it would require you to solve the halting problem), your submission's score will be the lowest *n* for which it returns an incorrect answer.

Each submission must be, at most, 1000 bytes (though you are encouraged to provide an ungolfed version as well). In the event of a tie, the earlier answer wins.

## Test Cases

*n* = 1:

```
+ >

```

*n* = 2:

```
++ +> >+ >< >> []

```

*n* = 3:

```
+++ ++> +>+ +>< +>> >++ >+< >+> ><+ ><> >>+ >>< >>> >[] [+] [<] [>] []+ []>

```

*n* = 4:

```
++++ +++> ++>+ ++>< ++>> +>++ +>+< +>+> +><+ +><> +>>+ +>>< +>>> >+++ >++< >++> >+<+ >+<> >+>+ >+>< >+>> ><++ ><+> ><>+ ><>< ><>> >>++ >>+< >>+> >><+ >><< >><> >>>+ >>>< >>>> [][] ++[] +>[] ><[] >>[] [++] [+<] [+>] [<+] [<<] [<>] [>+] [><] [>>] []++ []+> []>+ []>< []>> +[+] +[>] >[+] >[<] >[>] >[]+ >[]< >[]> [+]+ [+]> [<]+ [<]> [>]+ [>]> [[]]

```

Please inform me if there are any more that I have forgotten to add.

# Answer
> 6 votes
# Java (OpenJDK 8), Score: ???

This clocks in at 980 bytes, since I had so much to work with I decided to make it a little more readable. Basically I'm generating all the possible programs for length n and iterating them n^x times for some x. x is currently 3 but it can be modified arbitrarily to any size, limited only by the limitation of the JVM's precission. This will work for arbitrarily large input values if x is increased, but I have it set to 3 for tio.

```
import java.util.*;
public class Main{
    public static void main(String[] args){
        int i = new Scanner(System.in).nextInt();
        int x = 3;
        l:for(int j=0;j<Math.pow(5, i);j++){
            try {
                String s="";
                for(int k=j;s.length()<i;k/=5)
                    s="+<>][".charAt(k%5)+s;
                Stack<Integer>y=new Stack<Integer>();
                Map<Integer,Integer>f=new HashMap<>(),b=new HashMap<>();
                for(int m=0; m<s.length();m++){
                    char c=s.charAt(m);
                    if(c=='[')y.push(m);
                    if(c==']'){int n=y.pop();f.put(n, m);b.put(m, n);}
                }
                if(y.size()>0)
                    continue;
                boolean[] t= new boolean[s.length()];
                int l=0,n=0;
                for(long m=0;l<s.length()&m<Math.pow(i,x);l++,m++){
                    switch(s.charAt(l)){
                    case'+':t[n]=!t[n];break;
                    case'>':n++;break;
                    case'<':n--; if(n < 0)continue l;break;
                    case'[':if(!t[n])l=f.get(l);break;
                    case']':l=b.get(l)-1;break;
                    }
                }
                if(l>=s.length()){
                    System.out.println(s);
                }
            } catch(Exception e){continue;}
        }
    }
}

```

Try it online!

# Answer
> 2 votes
# Braingolf, Score: 3

```
1-?"++ +> >+ >< >> []":"+ >"|&@

```

Start things off nice and easy, hardcodes the correct answer for 1 and 2, outputs `+ >` if n = 1, and `++ +> >+ >< >> []` otherwise

---
Tags: code-challenge, code-generation, halting-problem
---


title: Charlie and the evil hyphen

text:
# Question
Title: Charlie and the evil hyphen
Here's the phonetic alphabet:

```
Alfa
Bravo
Charlie
Delta
Echo
Foxtrot
Golf
Hotel
India
Juliett
Kilo
Lima
Mike
November
Oscar
Papa
Quebec
Romeo
Sierra
Tango
Uniform
Victor
Whiskey
X-ray
Yankee
Zulu

```

In the fewest bytes possible:

1. Input will be these words in a random order, with the first letters removed.
2. Your goal is to arrange the words back to their original order using *only the letters you now have*. In other words: work out how '\[A\]lfa' comes before '\[B\]ravo', and so on. Your code must not refer the original list, index keys, etc.
3. Restore the original first letters of each word.

# Rules

* The hyphen in *X-ray* is probably evil, but needs to stay, for I am also evil.
* The result can be a string (comma or newline separated, for example), or an array.
* The spellings and letter cases are non-negotiable.
* No need to show example output in answers.

# Answer
> 4 votes
# Jelly, 21 bytes

```
“ṣȤW¶¬þḷẒ⁶4ẹ’Œ?ịṢØA;"

```

Input and output are string arrays.

Try it online!

### Background

While there are **26! = 403291461126605635584000000** different inputs, we can sort the input so we have to deal only with one permutation of this phonetic alphabet. Sorting lexicographically, we get

```
-ray
ango
ankee
apa
cho
elta
harlie
hiskey
ictor
ierra
ike
ilo
ima
lfa
ndia
niform
olf
omeo
otel
ovember
oxtrot
ravo
scar
uebec
uliett
ulu

```

We can simply index into this array to sort it by the removed letters. The (1-based) indices are

```
14 22  7  6  5 21 17 19 15 25 12 13 11 20 23  4 24 18 10  2 16  9  8  1  3 26

```

All that's left to do is to prepend the uppercase letters of the alphabet to the strings in the result.

### How it works

```
“ṣȤW¶¬þḷẒ⁶4ẹ’Œ?ịṢØA;"  Main link. Argument: A (string array)

“ṣȤW¶¬þḷẒ⁶4ẹ’          Replace the characters by their indices in Jelly's code page
                       and convert the result from bijective base 250 to integer.
                       This yields k := 214215675539094608445950965.
             Œ?        Construct the k-th permutation (sorted lexicographically)
                       of [1, ..., n], with minimal n (26 here). This yields
                       [14, 22,  7,  6,  5, 21, 17, 19, 15, 25, 12, 13, 11,
                        20, 23,  4, 24, 18, 10,  2, 16,  9,  8,  1,  3, 26].
                Ṣ      Yield A, sorted.
               ị       For each j in the array to the left, select the j-th string
                       from the array to the right.
                 ØA    Yield "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
                   ;"  Concatenate zipwith; prepend the j-th character from the
                       alphabet to the j-th string of the permuted input.

```

# Answer
> 3 votes
# Python 3, ~~76~~ 71 bytes

```
lambda x,S=sorted:S(map(str.__add__,'XTYPEDCWVSMKLAIUGRHNFBOQJZ',S(x)))

```

Try it online!

# Answer
> 2 votes
# JavaScript, 169/195 bytes

If replacing the first letter can be done prior to sorting **169 bytes**

```
x=>x.map(k=>{for(i=0;i<26;)if(!k.indexOf("l,r,ha,e,c,ox,ol,ot,nd,uli,il,im,ik,ov,s,ap,ue,o,ie,ang,n,i,h,-,a,u".split`,`[i++]))return String.fromCharCode(i+64)+k}).sort()

```

Try it online!

If sorting must be done prior to adding the first letter **195 bytes**

```
x=>x.sort((a,b)=>g(a)-g(b)).map(a=>String.fromCharCode(g(a)+64)+a)
g=k=>{for(i=0;i<26;)if(!k.indexOf("l,r,ha,e,c,ox,ol,ot,nd,uli,il,im,ik,ov,s,ap,ue,o,ie,ang,n,i,h,-,a,u".split`,`[i++]))return i}

```

Try it online!

A full 20 bytes of each of these programs is just String.fromCharCode() to regain the character...

Another 69 bytes is the string which uniquely identifies the start of each of the words in the phonetic alphabet.

## Explanation of first example

`for(i=0;i<26;)if(!k.indexOf("l,r,ha,e,c,ox,ol,ot,nd,uli,il,im,ik,ov,s,ap,ue,o,ie,ang,n,i,h,-,a,u".split`,`[i++]))return i`

The string hardcoded here is separated into a list of the unique identifying characters that start the phonetic alphabet words after the first character is removed.

```
return String.fromCharCode(i+64)+k

```

This information is used to find the index where the string falls in the alphabet in order to put the starting character back on.

```
.sort()

```

JavaScript implicitly sorts as strings by the ASCII values of the characters

## Explanation of the second example

The function g=k=\>... finds the index for which the string should fall in the phonetic alphabet.

```
.sort((a,b)=>g(a)-g(b))

```

Sorts the strings by the numbers returned by performing g(...)

```
.map(a=>String.fromCharCode(g(a)+64)+a)

```

Replaces the first character of each of the phonetic alphabet strings

# Answer
> 2 votes
# PHP, 94 bytes

```
<?for(sort($_GET);$i<26;sort($r))$r[]=XTYPEDCWVSMKLAIUGRHNFBOQJZ[$i].$_GET[+$i++];print_r($r);

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~29~~ 27 bytes

```
.•C5ê™вrΓ˜3åóMîõxÿ•uS|{)øJ{

```

Try it online!

```
.•C5ê™вrΓ˜3åóMîõxÿ•uS       # Push exploded XTYPEDCWVSMKLAIUGRHNFBOQJZ.
                     |{)    # Push input in array, sorted.
                        øJ{ # Zip together, join, resort.

```

-2 thanks to Emigna's magical `.•`.

# Answer
> 0 votes
# Java 7, 169 bytes

```
import java.util.*;List c(List l){Collections.sort(l);int i=0;for(Object s:l)l.set(i,""+"XTYPEDCWVSMKLAIUGRHNFBOQJZ".charAt(i)+l.get(i++));Collections.sort(l);return l;}

```

Try it here.

**Explanation:**

```
import java.util.*;                            // Import used for List and Collections

void c(List l){                                // Method with list parameter and no return-type
  Collections.sort(l);                         //  Sort the given list
  int i=0; for(Object s:l)                     //  Loop over the Strings in the list
    l.set(i,""+                                //   Replace the String-item in the list with:
      +"XTYPEDCWVSMKLAIUGRHNFBOQJZ".charAt(i)  //    The leading capital character
      +l.get(i++);                             //    Followed by itself
                                               //  End of loop (implicit / single-line body)
}                                              // End of method

```

---
Tags: code-golf, data-structures, alphabet
---


title: Display OEIS sequences

text:
# Question
Title: Display OEIS sequences
The On-Line Encyclopedia of Integer Sequences (OEIS) is an online database of integer sequences. It contains nearly 280000 sequences of mathematical interest.

Examples of sequences:

Your task is to write a program or function that displays as many OEIS sequences as you can, with a source code of **100 bytes** maximum. Your program should accept as input the sequence id (without the prepending `A` and the zeroes), and output the 20 first numbers in that sequence.

You are not allowed to fetch the data directly from the OEIS website; all sequences must be computed by your code.

**Scoring**

Score is the number of OEIS sequences the program can display. Answers will have to list the IDs of the sequences recognised by their program.

**Example**

Here's a valid answer in Java 8:

```
(int a) -> {
    for (int i = 0; i < 20; i++) {
        System.out.println(a==27?i+1:i*i);
    }
};

```

This program can display the positive integers (A000027 - input 27) and the squares (A000290 - input 290), thus its score is 2.

**Note**

Please avoid scraping the whole OEIS website :-) you can download the sequence names (about 3 megs) or sequence values (about 9 megs). Note that this download is covered by the OEIS End-User License Agreement.

# Answer
> 25 votes
## CJam (2182 2780 3034 sequences)

```
{:ZA3#:Cb(40-z_!!:B-\+CbB)/)_mqmo:M+:NK{)[N0{N1$_*-@/M@+1$md@M@-}K*]<W%B{X0@{2$*+\}%}*ZB&=}%\C)<f*}

```

This gives correct answers for the inclusive ranges

* `[A040000, A040003]`, `[A040005, A040008]`, `[A040011, A040013]`, `A040015`, `[A040019, A040022]`, `A040024`, `[A040029, A040033]`, `A040035`, `A040037`, `[A040041, A040043]`, `A040048`, `A040052`, `[A040055, A040057]`, `A040059`, `A040063`, `[A040071, A040074]`, `A040077`, `A040080`, `[A040090, A040091]`, `[A040093, A040094]`, `A040097`, `A040099`, `[A040109, A040111]`, `A040118`, `A040120`, `[A040131, A040135]`, `A040137`, `A040139`, `[A040142, A040143]`, `A040151`, `[A040155, A040157]`, `A040166`, `A040168`, `[A040181, A040183]`, `[A040185, A040968]`
* `[A041006, A041011]`, `[A041014, A042937]`
* `A006983`, `[A011734, A011745]`, `[A023975, A023976]`, `[A025438, A025439]`, `[A025443, A025444]`, `A025466`, `A025469`, `[A034422, A034423]`, `A034427`, `A034429`, `A034432`, `A034435`, `[A034437, A034439]`, `A034441`, `A034443`, `A034445`, `A034447`, `[A034449, A034459]`, `[A034461, A034462]`, `[A034464, A034469]`, `A034471`, `A034473`, `[A034475, A034477]`, `[A034479, A034487]`, `[A034489, A034490]`, `[A034492, A034493]`, `A034495`, `[A034497, A034512]`, `[A034514, A034516]`, `[A034518, A034523]`, `[A034525, A034582]`, `A036861`, `A047752`, `A052375`, `A055967`, `A061858`, `A065687`, `A066035`, `A067159`, `A067168`, `A070097`, `A070202`, `A070204`, `[A070205, A070206]`, `A072325`, `A072769`, `A076142`, `A082998`, `A083344`, `A085974`, `A085982`, `A086007`, `A086015`, `A089458`, `A093392`, `A094382`, `A105517`, `A108322`, `A111855`, `A111859`, `[A111898, A111899]`, `A112802`, `A122180`, `A129947`, `A137579`, `A159708`, `[A161277, A161280]`, `A165766`, `A167263`, `A178780`, `A178798`, `A180472`, `A180601`, `A181340`, `A181735`, `A184946`, `A185037`, `A185203`, `[A185237, A185238]`, `[A185245, A185246]`, `A185255`, `A185264`, `A185284`, `A191928`, `A192541`, `A197629`, `A198255`, `A200214`, `A206499`, `A210632`, `A212619`, `[A217148, A217149]`, `A217151`, `[A217155, A217156]`, `A228953`, `A230533`, `A230686`, `A235044`, `A235358`, `A236265`, `A236417`, `A236460`, `A238403`, `[A243831, A243836]`, `A248805`, `A250002`, `A256974`, `A260502`, `A264668`, `A276183`, `A277165`, `A280492`, `A280815`

The `A040???` sequences correspond to the continued fractions of non-rational square roots from `sqrt(2)` to `sqrt(1000)` (with the gaps corresponding to ones which appear earlier in OEIS, but conveniently filled with random sequences). The `A041???` sequences correspond to the numerators and denominators of the continued fraction *convergents* for non-rational square roots from `sqrt(6)` to `sqrt(1000)` (with the gap corresponding to `sqrt(10)`, at `A005667 and A005668`). The other assorted sequences have zeroes for their first twenty values.

The answer ports elements of two earlier answers of mine in GolfScript:

Many thanks to xnor for the short closed form `x -> x + round(sqrt(x))` mapping sequence offsets to the value to sqrt. The savings over my previous calculation (generating the list of non-squares and selecting by index) provided enough to have an all-zero fallback for most out-of-range indices.

# Answer
> 36 votes
## Python 2, 875 sequences

```
print', '.join('%020d'%(10**20/(input()-21004)))

```

Works for 875 of the sequences 21016 (decimal digits of 1/12) through 21999 (decimal digits of 1/995).

I found this chunk with the sophisticated search algorithm of haphazardly typing in sequence id's by hand. Some of the sequences in the range are not of this format and appear elsewhere (thanks to Mitchell Spector for pointing this out). For example, 21021 is not the expansion of 1/17.

Even with the interruptions, the sequences for 1/n appear as id `n+21004`. The remainder is not shifted, but the missing sequences appear elsewhere. For example, 1/17 appears as 7450.

I counted the ones that match using a downloaded copy of the sequence names.

A different block gives **848 sequences** from 16742 to 17664.

```
n=input()-16729
for i in range(20):k=n/12;a=int((8*k+1)**.5/2+.5);print(a*i+k-a*(a-1)/2)**(n%12+1)

```

These all have form `n -> (a*n+b)^c`, where `2≤a≤12, 0≤b<a, 1≤c≤12`. The code extracts the coefficients via inverting triangular numbers and moduli. As before, not all sequences in the range match. If these two expressions could fit in 100 bytes, it would give 1723 sequences.

Promising chunks:

* 1929 matching sequences: 41006 through 42397, numerators and denominators of continued fraction convergents.
* ~3300 matching sequences: 147999 to 151254: counts of walks on Z^3, if you can find how the vector lists are ordered.

Here are categories for other potential chunks, via grouping the OEIS sequence names by removing all numbers (digits, minus sign, decimal point). They are sorted by number of appearances.

```
3010    Number of walks within N^ (the first octant of Z^) starting at (,,) and consisting of n steps taken from {(, , ), (, , ), (, , ), (, , ), (, , )}
2302    Number of reduced words of length n in Coxeter group on  generators S_i with relations (S_i)^ = (S_i S_j)^ = I
979     Primes congruent to  mod
969     Numerators of continued fraction convergents to sqrt()
967     Denominators of continued fraction convergents to sqrt()
966     Continued fraction for sqrt()
932     Decimal expansion of /
894     Duplicate of A
659     Partial sums of A
577     Divisors of
517     Inverse of th cyclotomic polynomial
488     Expansion of /((x)(x)(x)(x))
480     Decimal expansion of th root of
471     Number of nX  arrays with each element x equal to the number its horizontal and vertical neighbors equal to ,,,, for x=,,,,
455     First differences of A
448     Decimal expansion of log_ ()
380     Numbers n such that string , occurs in the base  representation of n but not of n+
378     Erroneous version of A
375     Numbers n such that string , occurs in the base  representation of n but not of n
340     Numbers n with property that in base  representation the numbers of 's and 's are  and , respectively

```

---

**35 sequences:**

```
c=input()
for n in range(20):print[(c-1010)**n,(c-8582)*n][c>2e3]

```

Works from 8585 (multiples of 3) through 8607 (multiples of 25), and 1018 (powers of 8) through 1029 (powers of 19). Conveniently, these are all in one chunk ordered by id.

This uses only 65 of the 100 allowed bytes and isn't fully golfed yet, so I'll look for another nice chunk.

# Answer
> 30 votes
# Bash \+ coreutils, 252 sequences

```
yes 0|head -20

```

Try it online!

Works on 252 OEIS sequences: A000004, A006983, A011734, A011735, A011736, A011737, A011738, A011739, A011740, A011741, A011742, A011743, A011744, A011745, A023975, A023976, A025438, A025439, A025443, A025444, A025466, A025469, A034422, A034423, A034427, A034429, A034432, A034435, A034437, A034438, A034439, A034441, A034443, A034445, A034447, A034449, A034450, A034451, A034452, A034453, A034454, A034455, A034456, A034457, A034458, A034459, A034461, A034462, A034464, A034465, A034466, A034467, A034468, A034469, A034471, A034473, A034475, A034476, A034477, A034479, A034480, A034481, A034482, A034483, A034484, A034485, A034486, A034487, A034489, A034490, A034492, A034493, A034495, A034497, A034498, A034499, A034500, A034501, A034502, A034503, A034504, A034505, A034506, A034507, A034508, A034509, A034510, A034511, A034512, A034514, A034515, A034516, A034518, A034519, A034520, A034521, A034522, A034523, A034525, A034526, A034527, A034528, A034529, A034530, A034531, A034532, A034533, A034534, A034535, A034536, A034537, A034538, A034539, A034540, A034541, A034542, A034543, A034544, A034545, A034546, A034547, A034548, A034549, A034550, A034551, A034552, A034553, A034554, A034555, A034556, A034557, A034558, A034559, A034560, A034561, A034562, A034563, A034564, A034565, A034566, A034567, A034568, A034569, A034570, A034571, A034572, A034573, A034574, A034575, A034576, A034577, A034578, A034579, A034580, A034581, A034582, A036861, A047752, A052375, A055967, A061858, A065687, A066035, A067159, A067168, A070097, A070202, A070204, A070205, A070206, A072325, A072769, A076142, A082998, A083344, A085974, A085982, A086007, A086015, A089458, A093392, A094382, A105517, A108322, A111855, A111859, A111898, A111899, A112802, A122180, A129947, A137579, A159708, A161277, A161278, A161279, A161280, A165766, A167263, A178780, A178798, A180472, A180601, A181340, A181735, A184946, A185037, A185203, A185237, A185238, A185245, A185246, A185255, A185264, A185284, A191928, A192541, A197629, A198255, A200214, A206499, A210632, A212619, A217148, A217149, A217151, A217155, A217156, A228953, A230533, A230686, A235044, A235358, A236265, A236417, A236460, A238403, A243831, A243832, A243833, A243834, A243835, A243836, A248805, A250002, A256974, A260502, A264668, A276183, A277165, A280492, A280815

# Answer
> 12 votes
# Python (with sympy), ~~144~~  146 sequences

```
import sympy
f=lambda a,M=16627:[int(c)for c in str(sympy.log((a<M)*46.5+4+a-M).n(20))if'.'<c][-20:]

```

The function `f` works for the **146** sequences **A016578** through **A016723** inclusive.

All of these are output by the test harness at **repl.it**.

The **49** sequences **A016578** through **A016626** inclusive are the decimal expansions of log(3/2), log(5/2), log(7/2), ..., log(99/2).

The **97** sequences **A016627** through **A016723** inclusive are the decimal expansions of log(4), log(5), log(6), ..., log(100).

The first **two** of the **49** start at the first decimal place since the log values for them are less than **1**, so the `[-20:]` takes the trailing 20 decimal places of the result of the call to `...n(20)` which gets 20 significant figures. The `if'.'<c` filters out the decimal place character, and the `int(c)` casts each remaining digit character to an integer (although maybe not necessary).

# Answer
> 11 votes
# Jelly, ~~1127~~ 1975 sequences

-- this currently combines the findings of xnor and Mitchell Spector, but still has some room for growth at 78 bytes. Go give them some credit!

```
0x20
_21004µȷ20:DU¢oU
20Ḷ×⁸+µ*þ12
11R‘µẋ`€F$ç"Ḷ€F$;/
_108ị¢

“æÑØ‘×ȷ3¤>J×$S‘µĿ

```

**TryItOnline!**

The 1975 sequences are:

* the 252 that start with twenty zeros (the behaviour for input outside of `[16000,21999]`);
* the 848 sequences lying in the range 16742 to 17664 that match the `(a*n+b)**c` formula (the behaviour for input in `[16000,17999]`); and
* the 875 sequences lying in the range 21016 to 21999 that match the decimal expansion of `1/n` (the behaviour for input in `[18000,21999]`).

### How?

```
0x20 - Link 1, TwentyZeros: no arguments
0    - zero
  20 - twenty
 x   - repeat

_21004µȷ20:DU¢oU - Link 2, DecimalExpansionOfReciprocal: oeisIndexNumber
      µ          - monadic chain separation
       ȷ20       - 1e20
_21004           - subtract 21004 from oeisNumber to get the n value
          :      - integer division, i.e. 1e20 // n
           D     - decimal list
            U    - reverse
             ¢   - call last link (1) as a nilad, i.e. get twenty zeros
              o  - logical or, i.e. pad the right of the reversed list to twenty with zeros
               U - reverse again

20Ḷ×⁸+µ*þ12 - Link 3, BlockOf12abcFormulaResults: a, b
20Ḷ         - lowered range of 20 [0,1,...,19] i.e. the values of n in (a*n+b)**c
    ⁸       - left argument, a
   ×        - multiply
     +      - add b
      µ     - monadic chain separation
        þ12 - outer product with [1,2,...,12] of... i.e. the values of c in (a*n+b)**c
       *    -     exponentiation

11R‘µẋ`€F$ç"Ḷ€F$;/ - link 4, AllabcFormulaResults: no aguments
11R                - range of 11 [1,2,...,11]
   ‘               - increment   [2,3,...12] i.e. the values of a in (a*n+b)**c
    µ              - monadic chain separation
         $         - last two links as a monad
     ẋ`€           - repeat list with repeated arguments for €ach [[2,2],[3,3,3],...,[12,12,12,12,12,12,12,12,12,12,12,12]]
        F          - flatten into one list
               $   - last two links as a monad
            Ḷ€     - lowered range of €ach [[0,1],[0,1,2],...,[0,1,2,3,4,5,6,7,8,9,10,11]]
              F    - flatten into one list
          ç"       - zip with (") last link (3) as a dydad (ç) i.e. get all the results
                 / - reduce with
                ;  - concatenation i.e. make the list of lists of lists one list of lists.

_108ị¢ - Link 5, abcFormulaResult: oeisIndexNumber
_108   - subtract 108 from the oeisNumber (indexes in Jelly are modular and there are 924 entries, this is shorter than _16740)
     ¢ - call last link (4) as a nilad
    ị  - index into i.e. get the one relevant result of 20 terms

 - Link 6, an empty link (cheaper in bytes than the %6 alternative in the main link)

“æÑØ‘×ȷ3¤>J×$S‘µĿ - Main link: oeisIndexNumber           e.g. 1-15999; 16000-17999; 18000-21999; 22000+
        ¤         - nilad followed by link(s) as a nilad
“æÑØ‘             - codePage indexes [22,16,18]
      ȷ3          - 1e3
     ×            - multiply [22000,16000,18000]
         >        - greater than (vectorises)            e.g. [1,1,1]; [1,0,1];     [1,0,0];     [0,0,0]
            $     - last two links as a monad
          J       - range(length) [1,2,3]
           ×      - multiply                             e.g. [1,2,3]; [1,0,3];     [1,0,0];     [0,0,0]
             S    - sum                                  e.g. 6;       4;           1;           0
              ‘   - increment                            e.g. 7;       5;           2;           1
               µ  - monadic chain separation
                Ŀ - call link(index) as a monad with the oeisIndexNumber
                        link indexing is 1-based and modular so 7 calls link 1
              ><        hence the empty link 6 replacing a %6 here

```

# Answer
> 8 votes
# Mathematica, ~~39~~ ~~173~~ 189 sequences

```
If[l=0~Range~19;#<4^7,l,If[#<3^9,#&@@RealDigits[Log[j=16627;#-j+If[#<j,49.5,4]],10,20],#-22956-l]]&

```

Inspired by Jonathan Allan's answer.

Works for:

* 1477, 2837, 4830, and 8554 (the first 20 terms of these are `{0, 1, 2, ... , 19}`)
* 16578 to 16626 (decimal expansion of log(3/2), decimal expansion of log(5/2), ... decimal expansion of log(99/2))
* 16627 to 16723 (decimal expansion of log(4), decimal expansion of log(5), ... decimal expansion of log(100))
* 22958 to 22996 (2-n, 3-n, ... 40-n)

# Answer
> 6 votes
## CJam, 1831 sequences

```
{168680-:Zz1320b900b48md:R;H+:QB+2*,:!1_tQWtQ)WtK{[WQW*_(]+1$f=[1R2+R~R4+*2/WR-X$-].*1b+}/J~>ZW>f*}

```

This gives correct output for 199 sequences beginning `0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0` and all sequences in the inclusive ranges `[A168680, A169579]` and `[A170000, A170731]`. The bulk of it deals with those two ranges, with a fallback for all-zeroes before the start of the first range.

The two ranges in question have the form

> Number of reduced words of length \\$n\\$ in Coxeter group on \\$P\\$ generators \\$S\_i\\$ with relations \\$(S\_i)^2 = (S\_i S\_j)^Q = I\\$

for values of \\$P\\$ ranging from \\$3\\$ to \\$50\\$ and values of \\$Q\\$ ranging from \\$17\\$ to \\$50\\$. Their generating functions are given in a thoroughly inefficient manner: I found it useful to multiply numerators and denominators by \\$(t - 1)\\$ to give g.f. $$\frac{t^{Q+1} + t^Q - t - 1}{\frac12(P-2)(P-1) t^{Q+1} - \frac12(P-2)(P+1) t^Q + (P-1)t - 1}$$ although for golfing purposes I'm actually working with \\$R = P + 3\\$.

# Answer
> 1 votes
## Batch, 62 sequences

```
@for /l %%i in (1,1,20)do @set/a"n=(n=22956-%1)*(n>>=16)+%%i*(n|%1-8582)"&call echo %%n%%

```

Just implementing one block of sequences was hard, but I managed two in 89 bytes! Explanation: For a parameter `%1` of 8585-8607, `22956-%1>>16` returns zero, causing the `(22956-%1)` expression to be ignored and we end up multiplying the loop variable by 3-25 respectively, while for a parameter of 22958-22996 it returns minus one causing the expression to be negated, while the `n|` causes the multiplication factor to be replaced with minus one effectively subtracting the loop variable.

# Answer
> 1 votes
# PHP, 28 bytes, 33 Sequences I assume

```
for(;;)print_r(range(0,32));

```

Try it online!

https://oeis.org/A000004 0 https://oeis.org/A007395 2 https://oeis.org/A010701 3 https://oeis.org/A010709 4 https://oeis.org/A010716 5 https://oeis.org/A010722 6 https://oeis.org/A010727 7 https://oeis.org/A010731 8 https://oeis.org/A010734 9 https://oeis.org/A010692 10 https://oeis.org/A010850 11 https://oeis.org/A010851 12 https://oeis.org/A010852 13 https://oeis.org/A010854 15 https://oeis.org/A010855 16 https://oeis.org/A010857 18 https://oeis.org/A010859 20 https://oeis.org/A010861 22 https://oeis.org/A010863 24 https://oeis.org/A010871 32

---
Tags: code-challenge, sequence, restricted-source
---


title: Reverse the file

text:
# Question
Title: Reverse the file
I remember this was exam question long long long time ago.

There is a file say MyFile.txt, it can be any size and contains aphanumeric only

your task is to revese the words example : **"Go beyond the traditional laptop with Surface Laptop. It's backed by the best of Microsoft, including Windows and Office"**

It should be **"Office and Windows including Microsoft, of best the by backed It's Laptop. Surface with laptop traditional the beyond Go"**

The size of the text in the file is unknown.

# Answer
> 5 votes
# Python 3, ~~77~~ ~~71~~ ~~47~~ 43 bytes

```
print(" ".join(open("f").read().split()[::-1]))

```

EDIT: Saved 6 bytes thanks to NoOneIsHere.
EDIT: Saved another 24 thanks to Jonathan Allan.

---
Tags: code-challenge, file-system
---


title: Lights out, 7-segment version

text:
# Question
Title: Lights out, 7-segment version
Given a 7-segment display with some segments switched on and some off, find a sequence of digits (0-9), such that after toggling the corresponding segments for each digit, all segments are switched off.

## Example

```
  _
  _    [3] =>     |   [1] =>    [OFF]
  _               |

```

Numbers and their corresponding segments:

```
 _         _   _         _    _    _    _    _
| |    |   _|  _|  |_|  |_   |_     |  |_|  |_|
|_|    |  |_   _|    |   _|  |_|    |  |_|   _|

```

## Rules

Codegolf ⊨ shortest entry wins.

## Input

A non-empty list of segments which are switched on, given as

1. A sequence of numbers. Segments are numbered from top to bottom, left to right; starting from 0 or 1. Numbers need not be in order.
2. A single 7-bit digit. MSB/LSB not specified (thus you can choose).

Non-numeric characters between numbers are allowed (but not required to be supported).

Eg. for number `7`: `136` or `1010010` or `0100101`

## Output

A sequence of numbers to be "applied" to the display. Not restricted in any way, such as order of the digits. Eg. for initial state corresponding to number `1`, valid outputs would be `1`, `111`, `010`, etc.

An alternative output is a 10-bit digit (again, MSB/LSB is your choice). Eg. for `1` as input, the output would be `1000000000` or `0000000001`.

Some combinations have several non-repetitive solutions, eg. segments corresponding to the uppercase letter `H` can be switched off by `013`, but also `489` and `0258`.

If no solution exists (which I believe is not possible), the output is empty.

# Answer
> 4 votes
# Jelly, ~~26~~ 25 bytes

```
2ṗ⁵’µ×“wØ][:koR¶{‘^/=µÐfḢ

```

Try it online!

Takes input as a 7-bit integer. Returns the binary form of a 10-bit integer.

This just brute forces all possibilities. Remove the  to get all possible outputs or replace it with an `X` to get a random possible output.

Magic Visualization Program!

### How it works

```
2ṗ⁵’µ×“wØ][:koR¶{‘^/=µÐfḢ  - main link, takes one integer
2ṗ⁵’                       - generate all length-10 binary arrays
    µ                µÐf   - now we find those arrays which correspond to digit-
                              sequences which work to switch off all segments:
                              Filter (keep) those arrays which:
     ×                      - multiplied by
      “wØ][:koR¶{‘          - [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
                               (encoding for turned-on segments given number)
                  ^/        - reduced by XOR
                    =      - are equal to (implicit) the program's input
                        Ḣ  - output the first of these valid arrays

```

# Answer
> 2 votes
## JavaScript (ES6), ~~117~~ ~~107~~ ~~101~~ ~~86~~ 84 bytes

*Saved 15 bytes thanks to Neil*

Takes input as a 7-bit integer, where the LSB is the upper segment. Returns a 10-bit integer where the LSB is digit `0`.

```
f=(n,k)=>[83,0,57,73,10,71,87,1,91,75].reduce((n,v,i)=>n^=k>>i&1&&v+36,n)?f(n,-~k):k

```

### Demo

```
f=(n,k)=>[83,0,57,73,10,71,87,1,91,75].reduce((n,v,i)=>n^=k>>i&1&&v+36,n)?f(n,-~k):k

console.log("'1' shape", "-->", f(0b0100100).toString(2))
console.log("'7' shape", "-->", f(0b0100101).toString(2))
console.log("'H' shape", "-->", f(0b0111110).toString(2))
```

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

```
n=>[65,35,55,42,48,54,110].reduce((r,v,i)=>r^=n>>i&1&&v+v,0)

```

This works because:

* Toggling 1 and 7 toggles the top segment only
* Toggling 1, 2 and 6 toggles the top left segment only
* Toggling 1, 2, 3, 5 and 6 toggles the top right segment only
* Toggling 2, 4 and 6 toggles the centre segment only
* Toggling 5 and 6 toggles the bottom left segment only
* Toggling 2, 3, 5 and 6 toggles the bottom right segment only
* Toggling 2, 3, 4, 6 and 7 toggles the bottom segment only

# Answer
> 2 votes
## Mathematica, 40 bytes

```
BitXor@@{260,802,10,514,3,266,293}[[#]]&

```

(It may be golfed more by choosing output for each segment carefully and switch between LSB and MSB.)

Take input as a list of positions for example `{2,4,5,7}` and output a 10-bit number (`384` = `0110000000` in binary) in MSB order (0,...,9).

In the example it correspond to

```
  |_
  |_

```

and the output correspond to `{7,8}`.

Explanation:

The magic numbers (hardcoded list) is the output which is returned for each segment. (encoded in binary) And, if a number appear in the list twice, the effect is the same of it not being appear, so bitwise XOR is used. We just need to XOR the output of possible value of the segments turned on.

# Answer
> 2 votes
# Jelly, 12 bytes

```
ị“A#7*06n‘^/

```

Try it online!

This does not brute force, and it is remarkably shorter than my other solution. Takes input as a list of turned-on segments, and outputs as LSB is top segment.

Output as list of digit moves.

**How it works**

This is going to be quick

```
ị“A#7*06n‘^/ - main link, takes input as a list of turned-on segments (eg. [1,3,6])
 “A#7*06n‘   - list literal [65,35,55,42,48,54,110] where each element is a 7-bit
                 integer, where each integer corresponds to how to turn off
                 a segment (eg. turn off the first segment with 7 and 1 =>2^7+2^1=>64)
ị            - get the elements in the list corresponding to the input indices
          ^/ - XOR reduce these elements to get a single 7-bit integer

```

---
Tags: code-golf, puzzle-solver
---


# Question
Title: Encrypt a string using vigenere techniques
Your task:

Create a program that encrypts a string with another string using a key, using the vigenere cipher.

What a vigenere cipher does

```
Ciphertext:   string
Key:          keya
 |             |
 v             v
string
keyake
 |
 v
(18)(19)(17)(08)(13)(06)
(10)(04)(24)(00)(10)(04)
 |
 v
(28)(23)(41)(08)(23)(10)
 |
 v
cxpixk

```

If it still isn't clear, read here.

Rules: No built-ins, shortest code in bytes wins, input and output will/should always be either completely lowercase, or completely uppercase.

```
string, keya -> cxpixk
aaaaaaaaaaaaaaaaaaaaaaaa,abcdefghijklmnopqrstuvwxyz -> abcdefghijklmnopqrstuvwxyz
vigenere, cipher -> xqvlrvtm
short, longkey -> dvbxd

```

# Answer
# Jelly, 9 bytes

2 bytes thanks to Dennis.

```
ṁ⁹,OS‘ịØA

```

Try it online!

## How it works

```
ṁ⁹,OS‘ịØA            arguments: "KEYA", "STRING"

ṁ⁹         reshape   "KEYAKE"
  ,        pair      ["KEYAKE","STRING"]
   O       codepoint [[75,69,89,65,75,69],[83,84,82,73,78,71]]
    S      sum       [158,153,171,138,153,140]
     ‘     add 1     [159,154,172,139,154,141]
      ịØA  index ØA  "CXPIXK"
           where ØA is "ABCDEFGHIJKLMNOPSRQTUVWXYZ"

```
> 2 votes

# Answer
# Brachylog, 18 bytes

```
ạᵐz{+-₁₂%₂₆;Ạ∋₍}ᵐc

```

Try it online!
> 1 votes

# Answer
# , 114 bytes

```
l=letters
i=match
s=strsplit
function(m,k)cat(l[(i(s(m,'')[[1]],l)+i(s(k,'')[[1]],l)-2)%%26+1][1:nchar(m)],sep='')

```

Returns a function that takes the message and the key and prints the result to stdout. Will explain later (on mobile now) Try it online!
> 0 votes

# Answer
# Pyth, 15 bytes

```
s.e@GsxLG,@QkbE

```

Try it online!
> 0 votes

# Answer
# Python 3, ~~75~~ 73 bytes

*-2 bytes thanks to @LeakyNun*

```
f=lambda a,b:a and chr((ord(a[0])+ord(b[0])+1)%26+64)+f(a[1:],b[1:]+b[0])

```

Try it online!

Takes input in uppercase
> 0 votes

---
Tags: code-golf, cipher
---