title: Abbreviate that US state!

text:
# Question
Title: Abbreviate that US state!
Given one of the 50 U.S. state names on the left as input, output its two-letter postal code as shown to the right:

```
Alabama         AL
Alaska          AK
Arizona         AZ
Arkansas        AR
California      CA
Colorado        CO
Connecticut     CT
Delaware        DE
Florida         FL
Georgia         GA
Hawaii          HI
Idaho           ID
Illinois        IL
Indiana         IN
Iowa            IA
Kansas          KS
Kentucky        KY
Louisiana       LA
Maine           ME
Maryland        MD
Massachusetts   MA
Michigan        MI
Minnesota       MN
Mississippi     MS
Missouri        MO
Montana         MT
Nebraska        NE
Nevada          NV
New Hampshire   NH
New Jersey      NJ
New Mexico      NM
New York        NY
North Carolina  NC
North Dakota    ND
Ohio            OH
Oklahoma        OK
Oregon          OR
Pennsylvania    PA
Rhode Island    RI
South Carolina  SC
South Dakota    SD
Tennessee       TN
Texas           TX
Utah            UT
Vermont         VT
Virginia        VA
Washington      WA
West Virginia   WV
Wisconsin       WI
Wyoming         WY

```

## Rules

* **Input and output are both case sensitive.** You many not output e.g. `Al` for `Alabama`.
* You may assume the input is one of the 50 state names shown above.
* You may not access the internet or use built-in state data (looking at you, Mathematica).

Separate lists of inputs and outputs can be found in this snippet (please don't run it, it's just for compressing the post):

```
Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming

AL
AK
AZ
AR
CA
CO
CT
DE
FL
GA
HI
ID
IL
IN
IA
KS
KY
LA
ME
MD
MA
MI
MN
MS
MO
MT
NE
NV
NH
NJ
NM
NY
NC
ND
OH
OK
OR
PA
RI
SC
SD
TN
TX
UT
VT
VA
WA
WV
WI
WY
```

(Non-scoring) Brownie points if you can also take `District of Columbia` as input and produce `DC`, Virgin Islands, etc etc.

## Scoring

This is , so the **shortest code in bytes in each language wins**.

(Originally proposed by ETHProductions)

# Answer
> 33 votes
## Javascript (2023), 88 bytes

This is originally based on HP Williams solution, with some improvements outside the regex, and a couple of tweaks within it, plus a couple of bytes from Primo and Emanresu.

```
s=>s[0]+s.match`.+ .|.+z|...s.s?|T..|M[i-t]+|[AFINOUW][^o]v?|.+`[0].at(-1).toUpperCase()

```

It matches a chunk at the start of the name, then returns the capitalised last letter of that chunk appended to the first letter of the name.

Commentary for the regex:

```
.+ .           // Two word states (NJ, NM, NH, NY, WV, ND, SD, RI,NC,SC)
.+z            // AriZona
...s.s?        // MissiSsippi, MissOuri, MassAchussetts, AlasKa, and KansaS
M[i-t]+        // MonTana, MinNesota, MIchigan
[AFINOUW][^o]v?  // All the other first-two-letter states, avoiding Iowa/Connecticut/Louisiana, plus NeVada
T..            // TeNnessee, TeXas
.+             // Everything else

```

Alternative regex's (same length):

```
...(a$|z|s.s?|.* .)|M[i-t]+|T..|[AFINOUW].v?|.*
.*( .|z)|...s.s?|Te.|M[i-t]+|[^GHKMPVo]{2}v?|.*
.*( .|z)|...s.s?|M[i-t]+|[^GHKMPVo]{2}[vnx]?|.*
.+ .|...s.s?|[MNTe]+[i-z]+|.+z|[AFINOUWow]+.|.+
.+( .|z)|...s.s?|[MNT]e?[i-x]+|[AFINOUWow]+.|.+

```

## History

With linebreaks for readability:

### 90

```
s=>s[0]+
  /.$/.exec(s.toUpperCase()
    .match`.* .|.*Z|...S.S?|T..|M[I-T]+|[AFINOUW][^O]V?|.*`
  )

```

### 92

```
s=>s[0]+
/.*( .|z)|...s.s?|T..|M[i-t]+|[AFINOUW][^o]v?|.*/
.exec(s)[0].slice(-1).toUpperCase()

```

### 94

```
s=>s[0]+/.*( .|z)|...s.s?|M[io]n?t?|[AFIOUWN][^o]v?|T..|.*/
.exec(s)[0].slice(-1).toUpperCase()

```

### 99

```
s=>s[0]+/.*( .|z|l.*k)|T..|M.ss.s?|M[io]n?t?|[AFIOUWN][^o]v?|.*/
.exec(s)[0].slice(-1).toUpperCase()

```

### 101

```
s=>s[0]+/.+[A-Zz]|Nev?|.*sk|M.ss.s?|M[io]n?t?|[AFIOUW][^o]|Te.|.+/
.exec(s)[0].slice(-1).toUpperCase()

```

### 108

```
 s=>s[0]+/MI(N|SSO|S)|[CDGHKLPV].*|.* .|.*[XZV]|.*?N[NTE]|.*(SK|D$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)

```

### 110

```
s=>s[0]+/MI(N|SSO|S)|[CGHKLPV].*|.* .|.*[XZV]|.*?N[NTE]|.*(SK|[ED]$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)

```

### 113

```
s=>s[0]+/^MI(N|SSO|S)|^[CGHKLPV].*|.*?( .|[XZV])|.*?N[NTE]|.*(SK|[ED]$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)

```

### 132

```
s=>(S=s.toUpperCase(),' ._SSO_^MI[NS]_^[CGHKLPV].*_.V_N[TNE]_SK_[ED]$_WA_Z_X_..'
.split`_`.some(p=>s=S.match(p)),S[0]+s[0].slice(-1))

```

### 134

```
s=>' ._SSO_^MI[NS]_^[CGHKLPV].*_.V_N[TNE]_SK_E$_D$_WA_Z_X_..'.split`_`
.map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s

```

### 135

```
s=>' ._SSO_^MI[NS]_LASK_^[CGHKLPV].*_NT_EN_[DE]$_WA_.[XVZ]_..'.split`_`
.map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s

```

### 137

```
s=>' ._OWA_SSO_ONT_^MI[NS]_LASK_^[CGHKLPV].*_EN_[DE]$_.[XVZ]_..'.split`_`.
map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s

```

# Answer
> 25 votes
## Javascript, ~~124~~ 117 bytes

(saved 7 bytes thanks to hvd)

```
x=>/.+[A-Z]|A..[sz]k?|M.ss.s?|M[io]n?t?|Nev?|[AFIOUW][^o]|T..|.+/.exec(x)[0].replace(/(.).*(.)/,'$1$2').toUpperCase()

```

Explanation:

* The regexp finds a match with the first and last letters the two letters of the abbreviation
* First part matches states with more than two words (including District of Columbia)
* Second part matches Alaska and Arizona
* Third part matches Massachusets, Mississippi and Missouri
* Fourth part matches Michigan, Minnesota and Montana
* Fifth part matches Nebraska and Nevada
* Sixth part matches all remaining states abbreviated to their first two letters, with a special case to exclude Iowa
* Seventh part matches all remaining states abbreviated to their first and third letters
* Eighth part matches everything else, which are abbreviated to their first and last letters
* Then it is just a case of stripping of those letters and capitalising
* Also matches Puerto Rico and American Samoa, but not Guam, Marianas islands or US Virgin Islands

# Answer
> 20 votes
## JavaScript (ES6), ~~156~~ 136 bytes

```
s=>s[0]+'.KT..N.VEA.XVL.H.TZ.AA..I.EADATO.JTISRDIYOI.DALA.Y.KE.C.D.R.YAS.NM...C.L...N'[parseInt(s.split` `.join``,36)%359%248*8%99*3%83]

```

### Demo

```
let f =

s=>s[0]+'.KT..N.VEA.XVL.H.TZ.AA..I.EADATO.JTISRDIYOI.DALA.Y.KE.C.D.R.YAS.NM...C.L...N'[parseInt(s.split` `.join``,36)%359%248*8%99*3%83]

;[
  "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho",
  "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi",
  "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio",
  "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
  "Washington", "West Virginia", "Wisconsin", "Wyoming"
]
.map(s => console.log(s, '-->', f(s)))
```

# Answer
> 17 votes
# Jelly, 75 bytes

```
³Oḅ⁹%⁽qġ%14ị⁽"wB¤Ḥ
“¿ØƈṢḍw÷S=)µZṂ÷ĿæÆɱ»Ḳiµ%2+3¢⁸?
e“\B“½ƈN»ȧ5ȯÇ’
i⁶ȯÇ‘ịṭḢŒu

```

**Try it online!**

...or see a **test suite** \- Note a small change had to be made to run the full program for multiple inputs in one go (I swapped out the program input atom, `³`, for a recall from register, `®`, one and set the register to each state name in turn).

### How?

Calculates the index to use for the second character of the postal code, appends it to the first character and uppercases the result.

First finds the index of a space character (or 0 if not found);

Else checks if it is Alaska or Missouri (yielding 5 for `k` or `o`);

Else finds the index of the input state in the list `Arizona Minnesota Mississippi Nevada Montana Texas Tennessee` (or 0 if not found) - if so it takes that index mod 2 plus 3 (for `z n s v t x n`);

Else converts the string to ordinals, converts that from base 256, finds the remainder of that after dividing by 29487, finds the remainder of that after dividing by 14 and uses that to index into the binary representation of 9620 and doubles the result - yielding 0 for states that use their final letter and 2 for those that use their second letter.

All but the very first case are incremented, and the resulting value is decremented (upping the space index found by one).

```
i⁶ȯÇ‘ịṭḢŒu - Main link: state string
 ⁶         - space character
i          - first index (of a space character in the state) or 0 if not found  (n-1 or 0)
   Ç       - call link 3 as a monad  (get n-1 in other cases)
  ȯ        - logical or  (yielding n-1)
    ‘      - increment   (yielding n)
     ị     - index into the state string (get the nth character)
       Ḣ   - head the state string (get the first character)
      ṭ    - tack
        Œu - convert to uppercase
           - implicit print

e“\B“½ƈN»ȧ5ȯÇ’ - Link 3: n-5 or ... : state string
 “\B“½ƈN»      - ["Alaska","Missouri"]
e              - exists in? (1 if so, 0 if not)
          5    - 5
         ȧ     - logical and
            Ç  - call link 2 as a monad
           ȯ   - logical or
             ’ - decrement

“¿ØƈṢḍw÷S=)µZṂ÷ĿæÆɱ»Ḳiµ%2+3¢⁸? - Link 2: n = 3 or n = 4 or ... : state string
“¿ØƈṢḍw÷S=)µZṂ÷ĿæÆɱ»           - "Arizona Minnesota Mississippi Nevada Montana Texas Tennessee"
                    Ḳ          - split at spaces
                     i         - first index of state string in that list or 0
                      µ        - monadic chain separation (call that i)
                             ? - if:
                            ⁸  -   link's left argument, i
                               - then:
                       %2      -   mod 2
                         +3    -   plus 3  - odd entries to 4: AriZona, MisSissippi, MonTana, TenNessee
                               -            even entries to 3: MiNnesota, NeVada, TeXas
                               - else:
                           ¢   -   call link 1 as a nilad

³Oḅ⁹%⁽qġ%14ị⁽"wB¤Ḥ - Link 1 ...n=2 or n=0: no arguments
³                  - program's 1st input    e.g. Iowa          or Ohio
 O                 - cast to ordinals            [73,111,119,97]  [79, 104, 105, 111]
   ⁹               - 256
  ḅ                - convert from base           1232041825       1332242799
     ⁽qġ           - 29487
    %              - modulo                      15991            20139
        %14        - modulo 14                   3                7
                ¤  - nilad followed by link(s) as a nilad:
            ⁽"w    -   9620                     V       V
               B   -   convert to binary = [1,0,0,1,0,1,1,0,0,1,0,1,0,0]
           ị       - index into                  0                1
                 Ḥ - double                      0                2
                   -   ...0th index of Iowa is 'a', 2nd of Ohio is 'h'

```

# Answer
> 16 votes
# Python 2, ~~94~~ 90 bytes

```
lambda s:s[0]+s[(19**9*0x4710b8f6019c1b61deca10eef13b1>>hash(s)%8199472%52*3&7)+1].upper()

```

Try it online

(Only Python 2 because Python 3 hashes are not stable and also you can't hash a string without turning it into bytes.)

Works with all 50 states, plus as a bonus District of Columbia and Puerto Rico.

It would be possible to save one byte by writing the number in base-36: `int("5clu7x0aixb0pelmpugv5iiibphrpf",36)`. ~~I'm waiting to see if I can think of a more creative solution.~~

### Update:

Since there are 12 unused digit positions in the hash, there are 236 possible numbers which will work. It seemed reasonable to believe that one of them would have a prime factor with a large exponent. For any given prime and exponent, finding a value is quite fast; I managed to find one with a factor of 199, reducing the size of the expression needed to represent the number by four bytes.

This is basically the same procedure as my C answer but using Python. Since the base hash function is different, I had to find a different reduction function, which turns out to be mod 52 instead of mod 54. But the biggest savings over C come from the possibility of using bignums to encode the vector, and of course the fact that the standard for Python seems to be that it's ok to use a lambda literal instead of a complete program.

# Answer
> 10 votes
# Python 2, 191 bytes

```
lambda s:s[0]+("KZD"*5+"HNTD"*5+"AYY"*4+"__L_O_VTA_I__A_T_RS_KA__S_"+"MOO"*5+"I_C_"+"AE"*6+"_I_D__A_"+"EDL"*5+"HV_A"+"IR"*7+"XC"*6+"E____N__YJ_YT___L")[reduce(lambda a,x:a+ord(x)^24,s,0)%174]

```

Try it online!

Uses a simple hash function to find the second character of the abbreviation.

# Answer
> 10 votes
# Retina, ~~113~~ ~~81~~ ~~80~~ ~~77~~ ~~70~~ 68 bytes

```
M1!`.+[A-Zz]|...s.s?|M[io]n?t?|[AFIOUWN][^o]v?|T..|.*
\B.*(?=.)

T`l`L

```

Try it online! Includes all 51 test cases. Saved 32 bytes by appropriating @JörgHülsermann's regex that finds the second letter (with a tweak to support DC; edit: saved 1 byte thanks to @JörgHülsermann). Saved 3 bytes by switching to @SteveBennett's regex from his comment to @HPWilliam's answer. Saved ~~7~~ 9 bytes thanks again to @SteveBennett. The other letters are then deleted and the string uppercased.

# Answer
> 8 votes
# PHP\>=7.1, 113 Bytes

```
<?=($a=$argn)[0],ucfirst(preg_match('#[vxz]| .|owa|lask|[CGHKLPV].*|ssi?.|n(n|t|[de]$)#',$a,$t)?$t[0][-1]:$a[1]);

```

Online Version

The strikes are match through a earlier beginning match before

`([vxz])` matches Arizona, Nevada, ~~New Mexico,~~ ~~Pennsylvania,~~ Texas,

`(.)` (one space before) matches New Hampshire, New Jersey, New Mexico, New York, North Carolina, North Dakota, Rhode Island, South Carolina, South Dakota, West Virginia

`[CGHKLPV].*(.)` matches California, Colorado, Connecticut, Georgia, Hawaii, Kansas, Kentucky, Louisiana, ~~New Hampshire~~, ~~North Carolina,~~ Pennsylvania, ~~South Carolina~~, Vermont, Virginia, ~~West Virginia~~

`ow(a)` match Iowa

`las(k)` match Alaska

`ssi?(.)` matches Massachusetts, Mississippi, Missouri, ~~Tennessee~~

`n(n|t|[de]$)` matches ~~Connecticut,~~ ~~Kentucky,~~ Maine, Maryland, Minnesota, Montana, ~~Pennsylvania,~~ ~~Rhode Island,~~ Tennessee, ~~Vermont~~

No match for these states so we take the first two letters Alabama, Arkansas, Delaware, Florida, Idaho, Illinois, Indiana, Michigan, Nebraska, Ohio, Oklahoma, Oregon, Utah, Washington, Wisconsin, Wyoming

First time that I am use this Regex Subpatter `?|` with allows to store the backreferences in one.

## Support the District of Columbia

Replace `(.)` with `([^o])` +3 Bytes

Try it online!

# PHP, 150 Bytes

```
<?=($t=preg_replace("#.\K\w+ |las|ri|nec|eorgi|awa|ow|[aio]ni?|e(?=n|v|x)|ntuck|ouisi|a?in|arylan|issi?|nnsylv|erm|irg#","",$argn))[0],ucfirst($t[1]);

```

Try it online! Testcases

# Answer
> 8 votes
# C, ~~148~~ 141 bytes

```
main(){char s[99];gets(s);printf("%c%c\n",*s,s["-2-1--561-1-62--642138364---4142--1416--67-7131-111-7-246"[*(int*)(s+1)%663694%57]-48]&95);}

```

`*(int*)(s+1)` considers the second through fifth character of the input to be an integer; that integer is then hashed into 0-56 using the hash `i%663694%57`. The hashed value is then looked up in a vector of offsets which represent the location of the second letter of the abbreviation. I chose those particular four bytes because (1) Missouri and Mississippi first differ in the fifth character and (2) some states have only four characters In C you can use the the NUL terminator byte, but nothing beyond that is reliable. (This hashes both Norths to the same value, as well as both Souths. But that doesn't matter because the associated offset is 6 for all of these.)

As it happens, that particular hash yields the correct position for the second letters of the abbreviations of District of Columbia, Puerto Rico and "Virgin Islands" (typed that way, not as "US Virgin Islands", because the algorithm insists that the first character of the abbreviation be the first character of the name).

The constants 663694 and 57 were found with an automated test; 57 was the smallest hash range I found. (The first version used 380085 and 63, but when I extended the test range I found the new one.) It seems that a slightly smaller hash exists if a code is added for "use the last character in the name"; unfortunately, C syntax for selecting the last character is too wordy to make that helpful.

There are only 8 different offsets, so they could have been stored in a 171-bit (3\*57) lookup table with three bits per entry. But I couldn't think of a way to insert those bits efficiently into the program. Hex-encoding would require about one character per four bits, plus the `0x` prefixes. I couldn't do better than 151 bytes, which is much longer than the string version. If the 171 bits could somehow be inserted as raw octets, they would occupy 22 bytes, so there might be a solution, but reading a file is clunky.

# Answer
> 7 votes
# C, ~~945~~ ~~937~~ ~~718~~ ~~711~~ ~~660~~ 616 bytes

Saved 219 bytes thanks to ASCII-only.

```
struct{int*a,b;}m[]={"laba",76,"lask",75,"rizo",90,"rkan",82,"alif",65,"olor",79,"onne",84,"elaw",69,"lori",76,"eorg",65,"awai",73,"daho",68,"llin",76,"ndia",78,"owa",65,"ansa",83,"entu",89,"ouis",65,"aine",69,"aryl",68,"assa",65,"ichi",73,"inne",78,"issi",83,"isso",79,"onta",84,"ebra",69,"evad",86,"ew H",72,"ew J",74,"ew M",77,"ew Y",89,"orth",67,"orth",68,"hio",72,"klah",75,"rego",82,"enns",65,"hode",73,"outh",67,"outh",68,"enne",78,"exas",88,"tah",84,"ermo",84,"irgi",65,"ashi",65,"est ",86,"isco",73,"yomi",89};
i;char b[99];main(){gets(b);putchar(*b);for(;m[i].a;i++)if(!strncmp(m[i].a,b+1,4))puts(&m[i].b);}

```

Newline unnecessary, only for display purposes. Takes the state as input. Try it online!

How it works:

* `struct{int*a,b;}m[]=...` declares a map `m` with two values - a four-byte string and one character. This is used in the comparison loop, which compares the second through fifth indexes with `char*a` in the map.
* `gets(b)` reads a string `b`. This will be the state to abbreviate.
* `putchar(*b)` prints the first character of that string, since each abbreviation starts with the first letter of the state.
* `for(;m[i].a;i++)` loops through each value of the map. (This might be able to be shortened.)
* `if(!strncmp(m[i].a,b+1,4))` compares the current map value to the second through fifth characters of `b` (the state to abbreviate). This is because the only differences are in the first five characters, but we've already printed the first character.
* `puts(&m[i].b);` prints the second letter of the abbreviation (if the state name matches with the current map value), and a newline.

# Answer
> 7 votes
**PHP, ~~887~~ 854 bytes**

```
<?=array_combine(['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming'],['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'])[$argv[1]];

```

Try it online!

*First timer, hooray!*

# Answer
> 4 votes
# Python 3, 230 bytes

```
lambda s:chr(s[0])+'IA%%L!NOI!M%!E.N!Y.XR.Z$D.I!.D$DA.D%!.HA!LJ%.N%$T.I%!C!T!.HAAT$.A!.VL.V%$CE%%AEK%.T$!.Y.A!.R.Y$O.S%!.K$!.S'.replace('%','$$').replace('$','!!').replace('!','..')[sum(c*5**i for i,c in enumerate(s[::-1]))%236-5]

```

Try it online!

Input is expected as a bytes object (a byte string, rather than a Unicode string).

Thanks to Johnathon Allan for an absurd amount of bytes

## Explanation

Each state name is hashed to an integer `a` by applying the hash `a = sum(o*5**i) % 236` (where `o` is a character's ASCII ordinal and `i` is its index in the string, counting back from the end). The modulus `236` was chosen because it is the smallest modulus that causes all hash values to be distinct for the 50 US state names. These hashes are then mapped to the state abbreviations, and the resulting dictionary (compressed using string substitution) is used to look up the abbreviation given a state name (hashing it to get the appropiate key).

# Answer
> 4 votes
# Actually, 181 bytes

```
2"OHCALAGAMAWVFLNVILMNMOMIRINCDEMTMEINWANYTXORNEOKIDAZNMUTNDMDVAKYSDPAARWYNHIAMSALNJAKTNHIKSVTWICOSCCT"╪"âäà♠îÉæô↨→←∟♣áíå*,▓/12│┤94▼╛?DE╞G╚╠╬ST╒WXßb;Θoq╙|⌂"♂┘Z⌠i≈┐⌡MXO;rR5♀ⁿ*:236@%└

```

This solution expects input as a quoted string.

Try it online!

## Explanation

This solution utilizes the same hashing strategy as my Python 3 solution. For brevity, I am going to omit the explanation of how the hash is computed and why it was chosen (go read the other answer if you want that bit).

Also for brevity, I'm going to be leaving out the contents of the very long strings, since otherwise the explanation would be unreadable.

```
2"..."╪"..."♂┘Z⌠i≈┐⌡MXO;rR5♀ⁿ*:236@%└
2"..."╪                                state abbreviations (push the long string, split into length-2 chunks)
       "..."♂┘                         hash values for the state names (a string of CP437-encoded characters, converted to their CP437 ordinals)
              Z                        zip the two lists
               ⌠i≈┐⌡M                  for each pair:
                i                        flatten the pair
                 ≈                       convert hash value to int
                  ┐                      store abbreviation at the register numbered by the hash value
                     X                 discard the now-empty list
                      O                convert input string to list of ASCII ordinals
                       ;rR             range(len(ordinal_list)), reversed
                          5♀ⁿ          5**i mapped over that range
                             *         dot product of powers of 5 and ordinal list
                              :236@%   mod by 236
                                    └  push value in that register

```

# Answer
> 3 votes
# Python 2, ~~131~~ 125 bytes

```
lambda s:s[0]+'CLLKARADEZVAK.T..DETTH.NSAHY...ID.D..O..Y.IRE.X..NALINC.VJM.SY.T..AAOI'[int(s[0]+s[-2:],36)%386%334%181%98%70]

```

Try it online!

`int(s[0]+s[-2:],36)` generates a unique large number for each state by parsing the first and the two last characters as a base 36 integer.
`%386%334%181%98%70` is a modulo chain generated by a search program that reduces the size of the numbers while not mapping two states with a different second character in the abbreviation to the same number.
These smaller numbers are then used to index into the string `'CL ... OI'` to get the second character of the abbreviation.

# Answer
> 2 votes
# Python 2, 152 bytes

```
lambda s:s[0]+'.NY.SDS...O.DT..RT.AAYJZE.K.I.X.TI.EL.CMI..E.NA..L....TH.......O....DAAC..VNH.YAI.RVDA..L....A'[int(s.replace(' ','')[1:],36)%358%235%95]

```

Try it online!

A port of Arnauld's answer.

# Answer
> 2 votes
# ///, ~~619~~ 608 bytes

```
/2/~M//@/~South //1/~North //!/~New //~/\/\///Alabama/AL~Alaska/AK~Arizona/AZ~Arkansas/AR~California/CA~Connecticut/CT~Delaware/DE~Florida/FL~Georgia/GA~Hawaii/HI~Idaho/ID~Illinois/IL~Indiana/IN~Iowa/IA~Kansas/KS~Kentucky/KY~Louisiana/LA2aine/ME2aryland/MD2assachusetts/MA2ichigan/MI2innesota/MN2ississippi/MS2issouri/MO2ontana/MT~Nebraska/NE~Nevada/NV!Hampshire/NH!Jersey/NJ!Mexico/NM!York/NY1Carolina/NC1Dakota/ND~Ohio/OH~Oklahoma/OK~Oregon/OR~Pennsylvania/PA~Rhode Island/RI@Carolina/SC@Dakota/SD~Tennessee/TN~Texas/TX~Utah/UT~Vermont/VT~Virginia/VA~Washington/WA~West Virginia/WV~Wisconsin/WI~Wyoming/WY/

```

Try it online!

Since there is no other way of taking input in ///, it goes at the end of the program. Just append the desired input to the program.

Saved 11 bytes by making more replacements, as recommended by @SteveBennett

# Answer
> 2 votes
# Ruby, ~~106~~ 103 bytes

```
->s{s[0]+(s=~/ /?$'[0]:s[(j="()6>P_ac;?.O}AFLKMrS".index((s.sum%136%95+32).chr))?j>7?j/4:-1:1]).upcase}

```

If the input contains a space, the second output letter is the one after the space. Else...

Hash the sum of all characters in the input to obtain a character whose index in the magic string indicates the index of the second output letter in the input string, according to the formula `j>8?j/4:-1` (-1 means the end.). If the hash gives a character that is not in the magic string, second letter is second letter of input.

As an explanation of the magic string, the hash characters and the letter indexes they encode are below. Note that Delaware appears even though the second letter would do - this is because its hash code clashes with Kentucky. Fortunately the last letter of Delaware is the same as the second.

```
Letter(index)
Last  (-1)  (-MD    )-VA    6-GA-LA  >-DE-KY    P-PA    _-CT    a-KS    c-VT
3rd    (2)  ;-TN    ?-MN    .-TX     O-NV
4th    (3)  }-MS    A-IA    F-MT     L-AZ
5th    (4)  K-MO    M-AK    r-ME     S-HI

```

**Ungolfed in test program**

```
a="Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming".split($/)

f=->s{                                                            #String argument s.
  s[0]+(                                                          #Return character s[0] +
    s=~/ /?$'[0]:                                                 #if s contains a space, 1st character after space, ELSE
      s[(j="()6>P_ac;?.O}AFLKMrS".index((s.sum%136%95+32).chr))?  #if (sum of ascii codes, mod 136 mod 95 +32).chr in the magic string
        j>7?j/4:-1:                                                 #return s[j/4] if j>7 else return s[-1] ELSE
      1]                                                          #if not in the magic string, return s[1].
  ).upcase                                                        #Convert the second character to uppercase if needed.
}

a.map{|i|p [i,f[i]]}

```

# Answer
> 2 votes
## Mathematica, ~~138~~ ~~140~~ 134 Bytes

+2 bytes - found a mistake (needed array offset of 1 not 0)

-6 bytes - found a better hash

`#~StringTake~1<>"R_ATE__IN_COI_J_I_SLNAT_Y_Y_HKOAE__SAA_DDLM_RVAH_XDTVA__I_N_EA_T_DY_C_KZL"~StringTake~{1+Hash@#~Mod~89866736~Mod~73}&`

Similar to others it takes the name and takes the first letter. Then it applies the default Mathematica hash then applies two modulus to it "`Hash@#~Mod~89866736~Mod~73`" to get a unique number for each state. This value is then looked up in a string to generate the second letter.

Can probably be golfed more but the search space is huge for Mathematica to find. Duplicated second letters weren't considered in the hash search. `_` characters represent wasted values in the string. In theory you could get the string down to only 19 characters but finding the custom hash to produce that would be a nightmare.

# Answer
> 1 votes
# TAESGL, 386 bytes

```
B=«ōďā,AL,ņćđ,AK,ķċđ,AZ,ćōē,AR,ďċđ,CA,ĭāď,CO,ŕĭ,CT,ćđēą,DE,ĕŕ,FL,īĭ,GA,ńāē,HI,ćĉďą,ID,ĭċď,IL,ľđā,ţ,ńĕĕ,IA,ķő,KS,ŏĝ,KY,ŏĕĕ,LA,ŏđć,ME,ņāē,MD,ńđā,MA,īđą,MI,ļēď,MN,ŕğ,MS,ňė,MO,ććĕĉ,MT,ćċćĉ,NE,ŕēď,NV,ň ćŋā,NH,ň ĩēđ,NJ,ň ğĕċ,NM,ň ĉĝ,NY,ćņ ġĉă,NC,ćņ ńċą,ND,ĩēą,OH,ŋĺ,OK,ļķ,OR,ĺđď,PA,ĉĉğ đēā,RI,ōċ ġĉă,SC,ōċ ńċą,SD,ňďą,TN,ċĕď,TX,ōđą,UT,ćđāā,VT,ğğ,VA,ďĉē,WA,ĉĉć ğğ,WV,ľēđ,WI,ĉĩĕ,WY»Ĵ",";B[BĪA)+1

```

**Interpreter**

Very simple compression of the state names, added into an array with the abbreviations.

# Answer
> 1 votes
# Japt, 383 bytes

The compression of the first string may be improvable by experimenting with the order of the letters.

```
g +`lkzÇUaidlnyaÀÍ¥evhjmycdhkÎödnxttaaviy`g`alabaµ
Ã2ka
iza
kÂ6s
Öâfnia
åªv
¬n×©
Ü.Ø
fÓQ»
gegia
°ii
i»
ÅJno
Äa
Å0
kÂ6s
kÀ_cky
lia
Úpe
æ¯À
ÚUaÖ³etts
Úòig
·nÌta
æ«7ppi
æ¬
Úa
ßka
va»
w mp¢i
w jÀ y
w ´xi¬
w yk
Íh ÖÚ¦na
Íh »kota
oo
oklaÊá
eg
pnsylvia
r¸ Ó
Ñh ÖÚ¦na
Ñh »kota
âÊte
x
©ah
vÚ
virgia
Øgn
ØÙ virgia
æÈ;n
wyÇg`·bUv) u

```

Try it online

# Answer
> 1 votes
# Perl 5, ~~150~~ 148 bytes (147 + 1)

This is by no means optimal, but it does its job. Needs `-n` command line flag.

```
s/las//;s/ai?n//;s/[oie]n|ri//;s/e([vx])/$1/;s/issi?//;s/(.).+ /\1/;/(.)(.)/;/^([^W]).*(?:[cogavn][wiku]|[ir][ys][li]|rm)([adyti])$/;print uc"$1$2"

```

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


title: Convert a CSS selector to HTML

text:
# Question
Title: Convert a CSS selector to HTML
A CSS selector is made up of five elements:

1. The element type (tag name)
2. The id of the element
3. The classes of the element
4. The attributes of the element
5. Operators to chain these element selectors

This challenge will only involve the first four--also taking into account operators would make more than one element be generated and that's a bit too complex for this challenge. Maybe a future one. ;)

**Input**: A CSS selector, not including any operators. The element type will always be present, but the rest of the portions may not be.

**Output**: An html element representing the selector.

**Examples**:

```
In: div
Out: <div></div>

In: div[with-data="cool-data"][foo]
Out: <div with-data="cool-data" foo></div>

In: span.nice.tidy.cool
Out: <span class="nice tidy cool"></span>

In: button#great-button.fancy[data-effect="greatness"]
Out: <button id="great-button" class="fancy" data-effect="greatness"></button>

In: custom-element#secret[secret-attribute="secret value!!"]
Out: <custom-element id="secret" secret-attribute="secret value!!"></custom-element>

In: element#id.class1.class2[attribute1][foo="bar"]
Out: <element id="id" class="class1 class2" attribute1 foo="bar"></element>

```
* You may assume that the input selector will always have the different parts in order (element type, id, class, attributes).
* You may assume that the provided attribute selectors will never be an attribute text search (^=, $=, \*=).
* You may assume that the input word characters (element type, attribute names, class names, ids) will always match the regex \[a-z0-9\_-\]
* You may have extra whitespace anywhere *except* for inside strings (attribute values)

This is , so the shortest answer (in bytes) wins. Standard loop-holes apply.

# Answer
# PHP, 125 119 bytes

```
<?=preg_replace(['/#([\w-]+)/','/\.([^[]+)/','/[.[\]]/','/(\S+).*/'],[' id="$1"',' class="$1"',' ','<$1></$1>'],$argn);

```

Just regex replacements.
Saved 6 bytes thanks to Christoph.
> 5 votes

# Answer
# Retina, ~~88~~ ~~76~~ 67 bytes

```
#([\w-]+)
 id="$1"
\.([^[]+)
 class="$1"
T`[].`
^(\w+).*
<$&></$1>

```

Try it online!

*-10 bytes thanks to @Neil*
*-2 bytes thanks to @KritixiLithos*
> 2 votes

# Answer
# JavaScript (ES6), 193 bytes

```
s=>[[/#([\w-]+)/,` id="$1"`],[/((\.[\w-]+)+)/,(_,c)=>` class="${c.split`.`.join` `.trim()}"`],[/(\[.+?\])/g,(_,a)=>" "+a.slice(1,-1)],[/([\S]+)(.*)/,"<$1$2></$1>"]].map(r=>s=s.replace(...r))[3]

```

Longer than most since I preferred to output the HTML with all proper whitespace. Also works with the selector parts out of order (`div[attr].class#id`).

## Test Snippet

```
f=
s=>[[/#([\w-]+)/,` id="$1"`],[/((\.[\w-]+)+)/,(_,c)=>` class="${c.split`.`.join` `.trim()}"`],[/(\[.+?\])/g,(_,a)=>" "+a.slice(1,-1)],[/([\S]+)(.*)/,"<$1$2></$1>"]].map(r=>s=s.replace(...r))[3]

;["","div",'div[with-data="cool-data"][foo]',"span.nice.tidy.cool",'button#great-button.fancy[data-effect="greatness"]','custom-element#secret[secret-attribute="secret value!!"]','element#id.class1.class2[attribute1][foo="bar"]'].forEach(s => S.innerHTML += `<option>${s}</option>`);
```

```
<style>*{font-family:Consolas}</style>
Test Cases: <select id="S" onchange="I.value=this.value,I.oninput()"></select><br><br>
<input id="I" oninput="O.innerText=f(this.value)" size="75">
<pre id="O"></pre>
```
> 2 votes

---
Tags: code-golf
---


title: Generate Tiny Text

text:
# Question
Title: Generate Tiny Text
## Challenge

Your program needs to take an input of a string, where the string has only letters, no special characters, no numbers, and no accents (they look all weird).

Then, your program should output a superscript version.

## Example

**Input:** hello world

**Output:** ʰᵉᶫᶫᵒ ʷᵒʳᶫᵈ

## Test Cases

```
hello - ʰᵉᶫᶫᵒ
code - ᶜᵒᵈᵉ
golf - ᵍᵒᶫᶠ
asdf - ᵃˢᵈᶠ
qwerty - ᑫʷᵉʳᵗʸ
abcdefghijklmnopqrstuvwxyz - ᵃᵇᶜᵈᵉᶠᵍʰᶦʲᵏᶫᵐᶰᵒᵖᑫʳˢᵗᵘᵛʷˣʸᶻ

```

## Help

If you need help understanding check out this website, it's a translator: http://txtn.us/tiny-text

## Code Golf

This is a code golf, so the shortest code wins!

Good luck!

## Edits

**Edit #1:** There will be no caps, since I just realized they look weird.

# Answer
> 5 votes
# JavaScript (ES6), 10 bytes

```
s=>s.sup()

```

> It should be noted that the `sup()` method has been deprecated so this solution may not work in all browsers nor is it guaranteed to continue working in future releases of browsers that do currently support it. Tested and confirmed to work in Chrome v58.

---

## Try it

```
f=
s=>s.sup()
o.innerHTML=(i.value="Hello!")+": "+f(i.value)
oninput=_=>o.innerHTML=i.value+": "+f(i.value)
```

```
*{font-family:arial,sans-serif}
```

```
<input id=i><p id=o>
```

# Answer
> 3 votes
# PHP+HTML, 17 Bytes

```
<sup><?=$_GET[0];

```

# Answer
> 2 votes
# Mathematica, 13 bytes

```
#~Style~Tiny&

```

# Answer
> 2 votes
# Java 8 (AWT / Swing), 79 bytes

```
s->new java.awt.Frame(){{add(new javax.swing.JLabel("<html><sup>"+s));show();}}

```

Unfortunately there is no reliable online compiler available for Java GUI, so no TIO-link.

# Java 8 (Console), ~~123~~ 117 bytes

```
s->{for(int x:s.toCharArray())System.out.print("ᵃᵇᶜᵈᵉᶠᵍʰᶦʲᵏᶫᵐᶰᵒᵖᑫʳˢᵗᵘᵛʷˣʸᶻ".charAt(x-97));}

```

Try it here.

# Answer
> 1 votes
# Pyth, 75 bytes (30 chars)

```
XwG"ᵃᵇᶜᵈᵉᶠᵍʰᶦʲᵏᶫᵐᶰᵒᵖᑫʳˢᵗᵘᵛʷˣʸᶻ

```

Try it!

---
Tags: code-golf, string, unicode
---


title: Floor implementation

text:
# Question
Title: Floor implementation
Target: Write a `floor()` function from scratch.

Manipulating like converting float to string, and cutting all after dot are allowed.

All languages are allowed.

Any usage of built in language functions (like `toInteger()`) or similar is not allowed, casting operators are not allowed.

So, your task is implement floor() function without using casting and built in language functions.

Your function must support at least max 32-bit integer values (you will never receive negative values).

Forced casting (like `somevar as float`) and normal casting - such as`(int) somevar` \- is not allowed, any built in functions, not allowed, all other stuff allowed.

Winner: Shortest implemention.

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

```
i;int f(float n){for(i=-2147483648;i<=n;i++);return i-1;}

```

Try it online! (it takes too long, so I changed it to start from `0`.

# Answer
> 1 votes
# CJam, 6 bytes

```
q'.%0=

```

Try it online!

I found several 6 bytes solution but I can't do less than this.

# Answer
> 1 votes
# Javascript, 6 chars

```
x=>~~x

```

Test:

```
f = x=>~~x

document.addEventListener('input', event => {
  var x = event.target.valueAsNumber
  document.querySelector('output').textContent = x + " => " + f(x)
})
```

```
<input type=number> <output></output>
```

# Answer
> 0 votes
# Python 2, ~~21~~ 13 bytes

```
lambda x:x//1

```

Outputs a float if input is float, outputs an integer if input is integer.

Try it online!

# Answer
> 0 votes
# Japt, 2 bytes

```
|0

```

Try it online

---

## Alternative

```
ÂU

```

Try it online

# Answer
> 0 votes
# Batch, 53 bytes

```
@for /f "tokens=1 delims=." %%a in ("%1")do @echo %%a

```

*Trims everything after `.`*

---
Tags: code-golf, floating-point
---


title: What week is it?

text:
# Question
Title: What week is it?
The day of the week and month of the year seem to get a lot of attention but no one seems to care about the week of the year. I believe it's time to change that, so your job is to write a program or function that when given a date outputs an integer between 1 and 53 corresponding to the current week of the year.

For the purposes of this challenge we will say that the first Sunday of the year marks the beginning of the year so the *only* case when January 1st is considered week 1 is when it falls on a Sunday.

* Input can be any date format which does not explicitly include the week number (just specify the format in your answer) for dates between `1JAN1900` and `31DEC2100`.
* Output is an integer between 1 and 53
* You may use any standard methods of providing input/output.

### Test Cases

```
17MAY2017 -> 20

3JAN2013 -> 53

1JAN2017 -> 1

17MAY1901 -> 19

31DEC2100 -> 52

7JUL2015 -> 27

```
* This is so all standard golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 2 votes
# Ohm, ~~12~~ 33 bytes

**EDIT**: Fixed the edge cases for "%U".

```
IΩDÖ?┼╓y≤s"-12-31"C"%F"╓₧Ω
"%U"╓&

```

Assumes input can be a timestamp. Explanation to come.

Try it online!

# Answer
> 6 votes
# MATL, 50 bytes

*Thanks to @Neil and @NickClifford for pointing out a mistake, now corrected*

```
ZO1)TThXJYOXIGYO&:8XO!s310=sJ4B-YOIq&:8XO!s310=sX\

```

Try it online! Or verify all test cases.

### Explanation

This uses the three date/time conversion functions that there are in MATL:

* `XO`: convert date and time to string format;
* `YO`: convert date and time to serial date number;
* `ZO`: convert date and time to vector of components.

Determining if week "0" should become 52 or 53 was costly, because MATL cannot define callable functions to reuse the `8XO!s310=s` part. Reusing by means of loop with a branch only saves one byte, and complicates the explanation, so probably not worth it.

Also, something could be gained inputting the date as a \[year, month, day\] array; but the I would not use all three date functions :-)

Consider input `'17MAY2017'` as an example.

```
       % Implicit input
       % STACK: '17MAY2017'
ZO     % Convert to date vector
       % STACK: [2017 5 17]
1)     % Get first entry: year
       % STACK: 2017
TTh    % Append [1 1]
       % STACK: [2017 1 1]
XJ     % Copy to clipboard J
YO     % Convert to date number
       % STACK: 736696
XI     % Copy to clipboard I
GYO    % Push input again. Convert to date number
       % STACK: [736696 736832]
&:     % Binary range
       % STACK: [736696 736697 736698 ... 736832]
8XO    % Convert to date string with format 'ddd': day of week
       % STACK: ['Sun'; 'Mon'; 'Tue'; ... ; 'Wed']
!s     % Sum of each row (chars are interpreted as code points)
       % STACK: [310 298 302 ...  288]
310=   % Compare with 310 (sum of 'Sun')
       % STACK: [1 0 0 ... 0]
s      % Sum of array. If is 0, it needs to be transformed into 52 or 53,
       % depending on the number of Sundays the previous year contains.
       % STACK: 20
J      % Paste from clipboard J
       % STACK: 20, [2017 1 1]
4B-    % Push [1 0 0] and subtract element-wise
       % STACK: 20, [2016 1 1]
YO     % COnvert to date number
       % STACK: 20, 736330
I      % Paste from clipboard I
       % STACK: 20, 736330, 736696
q      % Subtract 1
       % STACK: 20, 736330, 736695
&:     % Binary range
       % STACK: 20, [736330 736331 736332 ... 736695]
8XO    % Convert to date string with format 'ddd': day of week
       % STACK: 20, ['Fri'; 'Sat'; 'Sun'; ... ; 'Sat']
!s     % Sum of each row (chars are interpreted as code points)
       % STACK: 20, [289 296 310 ... 296]
310=   % Compare with 310 (sum of 'Sun')
       % STACK: 20, [0 0 1 ... 0]
s      % Sum of array
       % STACK: 20, 52
X\     % 1-based modulo
       % STACK: 20
       % Implicit display

```

# Answer
> 4 votes
## JavaScript (ES6), ~~82~~ 80 bytes

Takes input as `(year,month,day)`.

```
let f =

(y,m,d)=>-~((((x=new Date(y,m-1,d))-new Date(y,0,1))/864e5+372-x.getDay())/7%53)

console.log(f(2017, 5,17)) // 20
console.log(f(2013, 1, 3)) // 53
console.log(f(2017, 1, 1)) // 1
console.log(f(1901, 5,17)) // 19
console.log(f(2100,12,31)) // 52
console.log(f(2015, 7, 7)) // 27
```

# Answer
> 4 votes
## JavaScript (Firefox 34+), 70 bytes

```
with(new Date())y.value=getFullYear(),m.value=getMonth()+1,d.value=getDate()+1
f=
(y,m,d)=>new Date(y,--m,d-new Date(y,m,d).getDay()).toLocaleFormat`%U`
```

```
<div oninput=w.value=f(y.value,m.value,d.value)><input id=y type=number><input id=m type=number min=1 max=12><input id=d type=number min=1 max=31><input id=w readonly placeholder=Output>
```

Works by finding the first day of the week containing the given date, then finding that day's week number (which is never zero).

# Answer
> 2 votes
# JavaScript (Firefox Only), 77 bytes

Takes date as string: i.e. `Jan 1, 2017`

```
s=>+new Date(s)[k='toLocaleFormat']`%U`||new Date(s.slice(-4)-1,11,31)[k]`%U`

```

# Answer
> 2 votes
# Python 2, ~~70~~ 64 bytes

Input =\> `(year,month,day)`

```
from datetime import*;lambda*v:int(date(*v).strftime('%U'))or 53

print(f(2017, 5,17)) #20
print(f(2013, 1, 3)) #53
print(f(2017, 1, 1)) #1
print(f(1901, 5,17)) #19
print(f(2100,12,31)) #52
print(f(2015, 7, 7)) #27

```

-6 bytes, thanks to @ovs

# Answer
> 2 votes
# PHP, 125 Bytes

```
for($w=53,$a=0;($c=date_create)($argn)>=$n=date_modify($c("07JAN1900"),"+$a week");$a++)$w=date_format($n,z)<7?1:$w+1;echo$w;

```

Try it online!

# PHP, 28 Bytes

Version for Monday instead Sunday

```
<?=date(W,strtotime($argn));

```

Try it online!

# Answer
> 2 votes
# C#, ~~138~~ ~~123~~ 121 bytes

```
namespace System.Globalization{d=>CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(d,(CalendarWeekRule)1,(DayOfWeek)0);}

```

Turns out there's a built in for that, although it is rather large...

```
namespace System.Globalization
{
    Func<DateTime, int> f = d =>
        CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(d, (CalendarWeekRule)1, (DayOfWeek)0);
 }

```

# Answer
> 1 votes
# Powershell, 260 + 8 = 268 bytes

+8 bytes because of the `-DateTime` flag

---

Accepts argument as `"day month year"` format.

```
function W([datetime]$DateTime = (Get-Date)) {
$cultureInfo = [System.Globalization.CultureInfo]::CurrentCulture
$cultureInfo.Calendar.GetWeekOfYear($DateTime,$cultureInfo.DateTimeFormat.CalendarWeekRule,$cultureInfo.DateTimeFormat.FirstDayOfWeek)
}

```

*Not Powershell expert, can't golf*

---

# Test case

```
>W -DateTime "11 March 2015"
11

```

---
Tags: code-golf, date
---


title: Digital Hardness of Integers

text:
# Question
Title: Digital Hardness of Integers
> To find the *digital hardness* of an integer, take its binary representation, and count the number of times both a leading *and* trailing `1` can be removed until it either start or ends with a `0`. The total number of bits removed is its digital hardness.

That's quite a wordy explanation - so let's break it down with a worked example.

For this example, we'll use the number 3167. In binary, this is:

```
110001011111

```

*(Note that, during the conversion to binary, you should make sure to strip leading zeroes)*

It doesn't start or end with `0`, so we remove 1 pair of bits:

```
1  1000101111  1

```

And another:

```
11  00010111  11

```

But now there is a 0 at the beginning, so we can't remove anymore `1` pairs. In total, 4 bits we removed, and so **4** is the digital hardness of **3167.**

However, for numbers that can be written as **2n-1** for positive **n** (i.e. contain only `1` in binary representation), 0 will never be reached, and so all the bits can be removed. This means that the hardness is simply the integer's bit length.

---

## The Challenge

You task is to write a program or function which, given a non-negative integer `n >= 0`, determines its digital hardness.

You can submit a full program which performs I/O, or a function which returns the result. Your submission should work for values of `n` within your language's standard integer range.

---

## Test Cases

Please notify me if any of these are incorrect, or if you'd like to suggest any edge cases to add.

```
0     -> 0
1     -> 1
8     -> 0
23    -> 2
31    -> 5
103   -> 4
127   -> 7
1877  -> 2
2015  -> 10

```

Here's the ungolfed Python solution which I used to generate these test cases (not guaranteed to be bug-less):

```
def hardness(num) -> int:
    binary = bin(num)[2:]

    if binary.count('0') == 0:
        return num.bit_length()

    revbin = binary[::-1]

    return min(revbin.find('0'), binary.find('0')) * 2

```

# Answer
> 6 votes
# Jelly, ~~11~~ 10 bytes

```
BµQL××Ṛa\S

```

Try it online!

### How it works

```
BµQL××Ṛa\S  Main link. Argument: n

B           Binary; convert n to base 2.
 µ          Begin a new, monadic chain. Argument: A (array of binary digits)
  Q         Unique; deduplicate the digits.
   L        Length; count the unique digits.
    ×       Multiply each digit by the result.
     ×Ṛ     Multiply the results by reversed A.
       a\   Cumulative reduce by logical AND.
            This zeroes out all elements after the first zero.
         S  Compute the sum of the result.

```

# Answer
> 8 votes
# Python, ~~76~~ ~~69~~ ~~68~~ ~~63~~ ~~62~~ ~~60~~ 57 bytes

```
f=lambda n,k=0:n>>k&(n&n>>k>n>>k+1)and(n&n+1>0)-~f(n,k+1)

```

Try it online!

### How it works

This is a recursive solution that takes an input **n** and keeps incrementing **k** – starting at **0**– while both **LSBk(n)** (bit at index **k** from the right) and **MSBk(n)** (bit at index **k** from the left) are set. Once finished, it returns **k** if all of **n**'s bit are set and **2k** if not.

Let's start by rewriting the lambda **f** as a named function **F**, with an auxiliary variable **t**.

```
def F(n, k = 0):
    t = n >> k
    return t & (n & t > t >> 1) and (n & (n + 1) > 0) + 1 + F(n, k + 1)

```

In each invocation of **F**, we first bit-shift **n** a total of **k** units to the right and store the result in **t**. This way, **LSB0(t) = LSBk(n)**, so **t** is odd if and only if **LSBk(n)** is set.

Determining whether **MSBk(n)** is set is slightly trickier; this is what `n & t > t >> 1` achieves. To illustrate how it works, let's consider an integer **n = 1αβγδεζη2** of bit-length **8** and analyze the function call **F(n, 3)**, i.e., **k = 3**.

We're trying to determine whether **MSB3(n) = γ** is set by examining the truth value of the comparison **(n & t \> t \>\> 1) = (1αβγδεζη2 & 1αβγδ2 \> 1αβγ2)**. Let's examine the involved integers.

```
MSB-index  012k4567

n          1αβγδεζη
t             1αβγδ

t >> 1         1αβγ

```

We claim that **γ = 1** if and only if **n & t \> t \>\> 1**.

* If **γ = 1**, then **n & t** has bit-length **5** while **t \>\> 1** has bit-length **4**, so **n & t \> t \>\> 1**.

This proves that **γ = 1** implies **n & t \> t \>\> 1**.
* If **n & t \> t \>\> 1**, there are two options: either **γ = 1** or **γ = 0**. In the first case, there's nothing left to prove.

In the second case, we have that **αβγδ2 ≥ n & t \> t \>\> 1 = 1αβγ2**.

Since **αβγδ2 \> 1αβγ2**, we must have **MSB0(αβγδ2) ≥ MSB0(1αβγ2)**, meaning that **α = 1**.

This way, **1βγδ2 \> 11βγ2**, so we must have **MSB1(1βγδ2) ≥ MSB1(11βγ2)**, meaning that **β = 1**.

In turn, this implies that **11γδ2 \> 111γ2**. Remembering that **γ = 0** in the second case, we get the inequality **110δ2 \> 11102**, which is false since **MSB2(110δ2) = 0 \< 1 = MSB2(11102)**.

Thus, only the first case is possible and **n & t \> t \>\> 1** implies **γ = 1**.

Summing up, if both **LSBk(n)** and **MSBk(n)** are set, **t** will be odd and **n & t \> t \>\> 1** will be *True*, so **t & (n & t \> t \>\> 1)** will yield **1**. However, if **LSBk(n)** or **MSBk(n)** is unset (or if both are), **t** will be even or **n & t \> t \>\> 1** will be *False*, so **t & (n & t \> t \>\> 1)** will yield **0**.

Calling **F** with a single argument initializes **k = 0**. While the condition we've discussed earlier holds, the code after `and` is executed, which (among other things) recursively calls **F** with incremented **k**.

Once **LSBk(n)** or **MSBk(n)** is unset, the condition fails and **F(n, k)** returns **0**. Each of the preceding **k** function calls adds **(n & (n + 1) \> 0) + 1** to **F(n, k) = 0**, so **F(n)** returns **((n & (n + 1) \> 0) + 1)k**.

Now, if all bits of **n** are equal (i.e., if **n** is either **0** or all of its bits are set), **n + 1** will not have any bits in common with **n**, so **n & (n + 1) = 0** and **F(n)** returns **k**. However, if **n** has both set and unset bits, **n & (n + 1) \> 0** and **F(n)** returns **2k**.

# Answer
> 6 votes
# MATL, ~~13~~ 12 bytes

```
Btv`6L&)}x@q

```

Try it online! Or verify all test cases.

### Explanation

The code repeats each binary digit, and counts how many times it is possible to remove two outer ones.

```
B        % Input number (implicit). Horizontal vector of binary digits
tv       % Duplicate and concatenate vertically
`        % Do...while
  6L&)   %   Flatten the array if needed (in column-major order), and split it
         %   into two subarrays: one with the inner entries, and another
         %   with the two outer entries. The latter will be used for deciding
         %   if the loop continues or is exited
}        % Finally (execute before exiting the loop)
  x      %   Delete last subarray of inner entries
  @q     %   Push last iteration index minus 1
         % End (implicit). The next iterarion is executed if the array at the
         % top of the stack is non-empty and only contains nonzero values.
         % Otherwise the loop is exited, executing the "finally" block first
         % Display (implicit)

```

# Answer
> 6 votes
# Python, 82 bytes

I feel like it can still be golfed, but I spent a while trying different methods and this was the shortest.

```
def f(n):b=bin(n)[2:];x=min(b.find('0'),b[::-1].find('0'));print(x<0)*len(b)or x*2

```

**Try it online**

Though this works similarly to the OP's Python program, I created this before the question was posted, after viewing the question in the Sandbox, which did not contain such a program.

# Answer
> 6 votes
## Python 2, 66 bytes

```
s=bin(input())[2:].split('0')
print len(min(s[-1],s[0]))<<1%len(s)

```

Splits the binary representation of the input into chunks of 1. Counts the number of 1's in the smaller of the first and last chunk, then doubles it, unless there's a single chunk that this would double-count.

# Answer
> 3 votes
# PowerShell, ~~109~~ 106 bytes

```
$a=[convert]::ToString($args[0],2)-split0;(((($b=$a[0].length),$a[-1].length|sort)[0]*2),$b)[$a.count-eq1]

```

Try it online!

Takes input `$args[0]`, uses the .NET call to `convert` it `toString` with base `2` (i.e., make it binary), then `-split`s that string on `0`s, stores that into `$a`. Important to note: the .NET call does not return leading zeros, so the first digit is always a `1`.

There are thus two possibilities -- the binary string is all ones, or there was at least one zero. We differentiate between those with a pseudo-ternary indexed by `$a.count-eq1`. If the binary has at least one zero, the left case, we take the minimum of the length of the first `[0]` string of `1`s and the last `[-1]` string (found by `|sort` and then `[0]`). The shorter of those is the most pairs we could remove, so we multiply that by `2`. Note that if the original binary string ends in a `0`, like for input `8`, then the `[-1].length` will also be `0` (since it's an empty string), which when multiplied by `2` is still `0`.

Otherwise, with the binary string all ones, we take just `$b` (which was previously set to be the length of the first `[0]` string, in this case, the entirety of the binary string).

In either situation, that result is left on the pipeline and output is implicit.

# Answer
> 3 votes
## JavaScript (ES6), 57 bytes

```
f=
n=>n.toString(2).replace(/^(1*)(.*(\1))?$/,'$1$3').length
```

```
<input oninput=o.value=1/this.value?f(+this.value):''><input id=o readonly>
```

Takes the binary and tries to match all `1s` or failing that an equal number of leading and trailing `1s`.

# Answer
> 2 votes
# C, ~~137~~ ~~132~~ ~~122~~ ~~119~~ ~~117~~ ~~114~~ ~~98~~ ~~94~~ ~~92~~ ~~87~~ 85 Bytes

Time to start golfing B-)

```
i,j;f(n){for(i=1<<30;i&~n;i/=2);for(j=0;n&i;n/=2,i/=4)j+=~n&1?i=0:2;return j-=n<1*j;}

```

Here's the proof

```
main()
{
  printf("%d %d\n", 0, f(0));
  printf("%d %d\n", 1, f(1));
  printf("%d %d\n", 8, f(8));
  printf("%d %d\n", 23, f(23));
  printf("%d %d\n", 31, f(31));
  printf("%d %d\n", 103, f(103));
  printf("%d %d\n", 127, f(127));
  printf("%d %d\n", 1877, f(1877));
  printf("%d %d\n", 2015, f(2015));
  printf("%d %d\n", 3167, f(3167));
}

```

and the output;

```
0 0
1 1
8 0
23 2
31 5
103 4
127 7
1877 2
2015 10
3167 4

```

# Answer
> 2 votes
# Retina, 48 bytes

```
.+
$*
+`(1+)\1
$1o
o1
1
m(+`^1(.*)1$
xx¶$1
x|^1$

```

**Try it online**

### Explanation:

```
.+              # Convert to unary
$*
+`(1+)\1        # Convert to binary (but with `o` instead of `0` -- it's shorter)
$1o
o1
1
m(+`^1(.*)1$    # Replace pairs of surrounding ones with `xx`
xx¶$1
x|^1$,          # Count x's, including the possibility of a single remaining `1`

```

# Answer
> 2 votes
## C#, 133 bytes

Function that returns hardness. Takes integer from argument.

```
int h(int b){var n=Convert.ToString(b,2);for(b=0;;){if(n[0]+n[n.Length-1]==98)n=n.Substring(1,n.Length-2);else break;b+=2;}return b;}

```

Well, today I found out `'1' + '1' = 98` in C#.

# Answer
> 2 votes
# C, ~~89~~ ~~88~~ 85 bytes

Saved two bytes due to @FlipTack pointing out a useless declaration.

Call `f()` with the number to test, the output is returned from the function.

```
t,h;f(l){for(t=l;t&&~t&1<<30;t*=2);for(h=0;t&1<<30&&l&1;t*=2,l/=2)++h;return h<<!!l;}

```

Try it on ideone.

# Answer
> 2 votes
# Jelly, 14 bytes

```
Eo2
BµŒg.ịṂS×Ç

```

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), ~~59~~ 58 bytes

```
f=(n,m=1<<30)=>m>n?f(n,m/2):m>1?n&m&&n&1&&2+f(n/2,m/4):n&1

```

### Test cases

```
f=(n,m=1<<30)=>m>n?f(n,m/2):m>1?n&m&&n&1&&2+f(n/2,m/4):n&1

console.log(
  [0, 1, 8, 23, 31, 103, 127, 1877, 2015].map(
    n => n + ' -> ' + f(n)
  ).join('\n')
)
```

# Answer
> 1 votes
# Java (OpenJDK), ~~181~~ ~~156~~ 150 bytes

```
n->{int i=0;String s=n.toString(n,2);if(s.matches("1*"))i=s.length();else for(;!s.matches("(.*0)|(0.*)");s=s.substring(1,s.length()-1))i+=2;return i;}

```

Try it online!

# Answer
> 1 votes
# Mathematica, ~~63~~ 56 bytes

```
(2-Min[l=#~IntegerDigits~2])Min[Tr/@Split[l][[{1,-1}]]]&

```

**Explanation**

```
l=#~IntegerDigits~2

```

Generate the base-2 representation of the input, wrapped with a `List`. Store that in `l`

```
(2-Min[...])

```

If the min element of `l` is 1, output 1. If not, output 2. Multiply this by...

```
Split[l]

```

Split `l` into runs.

```
... [[{1,-1}]]

```

Take the first and the last element.

```
Tr/@ ...

```

Take the total of both.

```
Min[ ... ]

```

Find the smaller between the two.

(Multiply the first result (1 or 2) with this result).

# Answer
> 1 votes
# Pyth, 18 bytes

```
?*FJjQ2lJyhSxR0_BJ

```

A program that takes input of an integer and prints the result.

Test suite (First line for formatting)

**How it works**

```
?*FJjQ2lJyhSxR0_BJ  Program. Input: Q
?                   If
  F                 reducing
    jQ2             the binary representation of Q as a list
   J                (store in J)
 *                  by multiplication is truthy:
       lJ            Yield len(J)
                    Else:
          hS         Yield the minimum
            xR0      of the first index of zero
               _BJ   in J and its reverse
         y           * 2
                    Implicitly print

```

# Answer
> 1 votes
# Octave, ~~56~~ 54 bytes

```
 @(n)cummin(d=dec2bin(n)-48)*cummin(flip(d))'*2^!all(d)

```

Try it Online!

Explanation:

```
d=dec2bin(n)-48

```

binary representation of `n`

```
cumd= cummin(d);
cumfd = cummin(flip(d));

```

Take cumulative min of `d` and cumulative min of flipped `d`

```
res = cumd * cumfd ';

```

do matrix multiplication

```
out = res*2^!all(d)

```

multiply with 2 if all of digits is 1;

# Answer
> 1 votes
# PHP, ~~83~~ 74 bytes

3+6 bytes saved by Jörg

```
<?=(~$s=decbin($argn))[$a=strspn($s,1)]?min($a,strspn(strrev($s),1))*2:$a;

```

takes input from STDIN; run with `-nR`.

**breakdown**

```
<?=                     # print ...
(~
    $s=decbin($argn)        # $s = binary representation of input
)[
    $a=strspn($s,1)         # $a = number of leading `1`s
]                           # if $s has more than $a digits,
?   min($a,                     # 2. minimum of $a and
        strspn(strrev($s),1)    # 1. number of trailing `1`s
    )*2                         # 3. *2
:   $a                      # else $a (==strlen)

```

# Answer
> 1 votes
# APL, 26 bytes

```
+/∘(∧\≢↑(∊⊢(,∧∧)¨⌽))2⊥⍣¯1⊢

```

Test cases:

```
      ( +/∘(∧\≢↑(∊⊢(,∧∧)¨⌽))2⊥⍣¯1⊢ ) ¨ 0 1 8 23 31 103 127 1877 2015
0 1 0 2 5 4 7 2 10

```

Explanation:

```

+/∘(∧\≢↑(∊⊢(,∧∧)¨⌽))2⊥⍣¯1⊢

                         ⊢   input
                    2⊥⍣¯1    convert to binary representation
   (               )
        (  ⊢    ¨⌽)          for each bit and its matching bit on the other side
            (  ∧)               take the logical and of both bits,
             ,                  make a list of both bits,
              ∧                 then take the and of the list and the and
         ∊                   flatten the resulting array
      ≢↑                     take only the first N bits, where N is the
                                length of the original list of bits
    ∧\                       take a running logical and (leaving only the
                                starting ones)
+/∘                          sum those

```

# Answer
> 1 votes
# J, 22 bytes

```
(#<.2*(<.&(#.~)|.))@#:

```

This is based on the neat trick learned from this challenge.

Try it online!

## Explanation

```
(#<.2*(<.&(#.~)|.))@#:  Input: integer n
                    #:  Binary digits of n
(                 )@    Operate on those digits D
               |.         Reverse D
       <.                 Take the minimum of
         &(#.~)           the "trailing truths" of D and reverse(D)
    2*                    Multiply by 2
 #                        The length of D
  <.                      Minimum of length and the previous result

```

# Answer
> 0 votes
# JavaScript (ES6), 83 Bytes

```
f=x=>(y=x.toString(2),y.match(/^1*$/)?y:([s,e]=y.match(/^1*|1*$/g),s<e?s:e)).length

```

Ungolfed:

```
function f(n) {
    var binStr = n.toString(2);
    if(binStr.match(/^1*$/)) {
        // If binary representation is all 1s, return length of binary
        return binStr.length;
    } else {
        // Grab the starting and ending 1s in the binary representation
        var [start1s, end1s] = binStr.match(/^1*|1*$/g);
        var startHardness = start1s.length;
        var endHardness = end1s.length;
        return Math.min(startHardness, endHardness);
    }
}

```

# Answer
> 0 votes
# Haskell, ~~94~~ 92 bytes

```
b 0=[]
b n=mod n 2:b(div n 2)
h n|(c,_:_)<-span(>0)$zipWith(*)n$reverse n=c++c|1<3=n
sum.h.b

```

Try it online! Usage:

```
Prelude> sum.h.b $ 3167
4

```

**Explanation:**
`b` converts a number to binary and returns a list of zero and ones with the least significant bit first. In `h`, this list is reversed and element-wise multiplied with the original list, then `span(>0)` splits after the initial `1`s:

```
       b 3167 = [1,1,1,1,1,0,1,0,0,0,1,1] = n
    reverse n = [1,1,0,0,0,1,0,1,1,1,1,1] = m
zipWith(*)n m = [1,1,0,0,0,0,0,0,0,0,1,1] = z
   span(>0) z = ([1,1],[0,0,0,0,0,0,0,0,1,1])

```

The resulting tuple is pattern matched with `(c,_:_)` where `_:_` matches any non-empty list, so `c = [1,1]`. Because the bytes are removed at front and back, `c++c = [1,1,1,1]` is returned and finally summed up to yield the *digital hardness*.

If the second list of the tuple is empty, then the binary representation contains ones only, and the number of ones is the digital hardness. With the pattern matching failed `h` returns just `n`, which is again summed up.

# Answer
> 0 votes
## Mathematica, 62 bytes

```
(h=0;#~IntegerDigits~2//.{{1,m___,1}:>(h+=2;{m}),{1}:>h++};h)&

```

Pure function where `#` represents the first argument.

`(h=0;...;h)&` sets `h=0`, does a bunch of stuff `...`, then returns `h` (the hardness). Let's look at the bunch of stuff:

```
#~IntegerDigits~2                                     Binary representation of the input
                 //.                                  Apply the following list of rules repeatedly until there is no change
                    {                                 Start of the list of rules
                     {1,m___,1}                       If you see a list starting and ending with 1 with the sequence m (possibly empty) in between
                               :>(h+=2;{m}),            replace it with just {m} after incrementing h twice.
                                            {1}       If you see the singleton list {1}
                                               :>h++    replace it with h, then increment h.
                                                    } End of the list of rules

```

Thanks to Greg Martin for introducing me to this trick.

# Answer
> 0 votes
# Perl, 61 bytes

```
sub f{$_=sprintf('%b',pop);length(/0/?/^(1+).*\1$/&&$1x2:$_)}

```

The heart of this is the regex `/^(1+).*\1$/` where 2 times the length of `$1` is the answer. Rest of the code is overhead and dealing with the all 1's special case.

# Answer
> 0 votes
# PHP, 65 Bytes

```
<?=strlen(preg_filter('#^(1*)(.*(\1))?$#',"$1$3",decbin($argn)));

```

Online Version

# Answer
> 0 votes
## CJam, 14 bytes

```
ri2b_0#\W%0#e<

```

Explanation:

```
ri e# Read integer:      | 3167
2b e# Convert to binary: | [1 1 0 0 0 1 0 1 1 1 1 1]
_  e# Duplicate:         | [1 1 0 0 0 1 0 1 1 1 1 1] [1 1 0 0 0 1 0 1 1 1 1 1]
0# e# Index of first 0:  | [1 1 0 0 0 1 0 1 1 1 1 1] 2
\  e# Swap:              | 2 [1 1 0 0 0 1 0 1 1 1 1 1]
W% e# Reverse:           | 2 [1 1 1 1 1 0 1 0 0 0 1 1]
0# e# Index of first 0:  | 2 5
e< e# Minimum:           | 2

```

---
Tags: code-golf, number, binary, integer, bitwise
---


title: Print your system's logo

text:
# Question
Title: Print your system's logo
This is a throwback challenge. You will choose an old computer system and an old language created for that system.

# The challenge

Pick an old computer system that was made before the year 2000. In a programming language that was created to run on that system, print said system's logo.

Example systems, their languages, and their logos:

# The rules

* You may not download the logo/icon from the internet or read it from the filesystem.
* You must use graphics to print the logo - no ASCII art.
* The icon's size must be at least 20 pixels by 20 pixels.
* Your program will not take any input and will clear the screen, print the logo, and exit normally.
* If the logo includes colors, your program must print the logo in the same colors, unless your system does not have a color display.
* The computer must not shut down.
* Your system must have a logo.
* If the logo includes text (e.g. the `Apple ][` in the Apple logo), you only need to print the image part (e.g. the actual colored Apple).

# The winner

As with , the submission with the least bytes wins!

# Answer
> 9 votes
## GFA BASIC on Atari ST, 27 bytes

This is a manually edited source code in .LST format. It contains unprintable characters: `[SO]` and `[SI]` stand for ASCII characters #14 and #15 respectively. Both lines ends with `CR`.

```
DEFTEXT,,,32
TEXT0,28,"[SO][SI]"

```

This will draw a 28x26 Atari logo, which is part of the Atari ST system font.

# Answer
> 3 votes
# Applesoft BASIC on the Apple \]\[, ~~365~~ 361 bytes

```
1GR:POKE-16302,0:I=0:O=15:P=1:Q=1:FORY=7TO47:I=I-1:IF(I<=0)THENI=7:READC:COLOR=C
2IF(Y<21)THENO=O-((21-Y)/12):GOTO4
3O=O+P-1:P=P*Q:Q=Q+0.002
4HLINO,39-O ATY:NEXT:DATA12,13,9,1,3,6:COLOR=0:HLIN16,22 AT7:HLIN18,20 AT8:HLIN16,22 AT47:HLIN18,20 AT46:VLIN14,34 AT32:VLIN15,33AT 31:VLIN16,32 AT30:VLIN18,30 AT29:VLIN22,26 AT28:COLOR=12:FORA=0TO3:VLINA,A+4 AT22-A:NEXT

```

Output and actual logo:

---
Tags: code-golf, graphical-output
---


title: Find Diffy Games

text:
# Question
Title: Find Diffy Games
A fun game to play if you are bored is the Diffy Game. It is a one player game that is pretty simple and can consume a good deal of your time.

The Diffy game works like as follows: You start with a list of non-negative integers, in this example we will use

```
3 4 5 8

```

Then you take the absolute difference between adjacent numbers

```
 (8)  3   4   5   8
    5   1   1   3

```

Then you repeat. You repeat until you realize you have entered a loop. And then generally the game starts from the beginning again.

```
3 4 5 8
5 1 1 3
2 4 0 2
0 2 4 2
2 2 2 2
0 0 0 0
0 0 0 0

```

Often the game has no goal, you are just biding time by doing arithmetic in your head. However when I have the pleasure of playing this game my goal is always to try and pick a period and try to construct a game that loops with that particular period.

Not all games are periodic, the example above is not periodic for example because it eventually reaches a game with all zeros and thus can never make it back to its starting position. In fact it seems that the vast majority of games are not periodic making the few games that are a rare gem.

---

Given a game that loops with a particular period it is trivial to make another game that loops with the same period by just doubling the sequence. For example the game:

```
1 0 1

```

Plays out exactly the same as the game:

```
1 0 1 1 0 1

```

In fact, we can consider that both are really the infinitely repeating game:

```
... 1 0 1 ...

```

We will consider them one game for the sake of this challenge.

In a similar fashion multiplying the entire sequence by a constant will also trivially preserve the period so we once again are going to count any two games that differ by a constant factor to be the same game.

---

The infinite strings `... 1 0 1 ...` and `... 0 1 1 ...` are obviously the same string shifted by one character. We will not count these as different games, but when one reaches the other it will not be considered the end of the cycle when determining the period of a game. For example:

The two games

```
... 0 0 0 1 0 1 ...  = A
... 0 0 1 1 1 1 ...  = B
... 0 1 0 0 0 1 ...  = A << 4
... 1 1 0 0 1 1 ...  = B << 4
... 0 1 0 1 0 0 ...  = A << 2
... 1 1 1 1 0 0 ...  = B << 2

```

and

```
... 0 0 1 0 1 0 ...  = A << 1
... 0 1 1 1 1 0 ...  = B << 1
... 1 0 0 0 1 0 ...  = A << 5
... 1 0 0 1 1 1 ...  = B << 5
... 1 0 1 0 0 0 ...  = A << 3
... 1 1 1 0 0 1 ...  = B << 3

```

are both games with period 6. They share no term with each other at any point in their loops (unlike `... 1 1 0 ...` and `... 1 0 1 ...` which reach each other) but because they are shifted versions of each other they are considered the same game when counting.

---

Reflecting (or reversing) an infinite string gives essentially the same behavior, but does not necessarily give the same period. Consider, for example,

```
... 0 0 0 1 0 0 1 1 0 1 0 1 1 1 1 ...

```

and its reflection

```
... 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 ...

```

If we considered the next generation to be produced at a half-way point between the characters:

```
... 0 0 0 1 0 0 1 1 0 1 0 1 1 1 1 ...
 ... 0 0 1 1 0 1 0 1 1 1 1 0 0 0 1 ...

... 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 ...
 ... 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 ...

```

then both would have shifted position by 3.5 elements. However, we don't consider the next generation to be produced with that half-element offset, so one rounds up to a 4-element shift giving a period of 15, and the other rounds down to a 3-element shift giving a period of 5.

For this reason we consider an asymmetric string and its reflection to be distinct, even though the cycles are in some sense isomorphic. Of course, if they form part of the same cycle then it only counts as one cycle.

---

With these restrictions a little mathematics can show that there are in fact a finite number of Diffy cycles with any given finite period. Moreover, every infinite string with a finite period is an infinite repetition of a finite string.

Note that the strings can be larger or shorter than the periods. For example, there is a string of length 5 with period 15, and a string of length 15 with period 5. All of the strings with period 19 are of length 9709.

# Task

Given a number `n` such that n is larger than 1 via standard input methods determine the number of distinct Diffy cycles with a period of exactly `n`.

*(It seems that, in the literature, `0` is often not considered a periodic Diffy game. Since this is a gray area I will not ask you to solve for `n = 1`)*

This is , so the goal is to minimize the number of bytes in your source code.

# Test Cases

```
2  ->   0
3  ->   1
4  ->   0
5  ->   1
6  ->   1
7  ->   3
8  ->   0
9  ->   4
10 ->   4
11 ->   3
12 ->   5
13 ->   5
14 ->  24
15 ->  77
16 ->   0
17 -> 259
18 -> 259
19 ->  27
20 -> 272
21 -> 811
22 -> 768
23 ->  91
24 -> 340
25 -> 656

```

### Hints

All Periodic diffy games will contain only zero and a single constant, this means every periodic game will be isomorphic to some diffy game consisting only of zeros and ones.

# Answer
# Python 2, 181 bytes

```
n=input()
m=2**n
a=[m]*m
r=lambda i:[i*-~m>>k&m-1 for k in range(n)]
def s(i):
 if a[i]&m:a[i]=i;a[i]=s(min(r(i^i*2)))
 return a[i]
print sum(min(r(i)[1:])>i==s(i)for i in range(m))

```

Try it online!

## How it works

The rules that transform each row of a binary diffy game into the next row are the same as the rules that transform each column into the next column. Therefore, it suffices to find all distinct cycles within the graph of all canonical length-*n* columns, where a column is “canonical” if it is lexicographically smaller than all of its rotations (this automatically excludes columns with period smaller than *n*).

With columns represented as binary numbers 0 ≤ *i* \< 2<sup>*n*</sup>, the rule sends *i* to the smallest rotation of *i* XOR (*i*⋅2). (If *i* is canonical, its high bit is zero and we do not need to worry about wraparound here.)

So we loop through all possible columns *i*, check for canonicity, then repeatedly apply the rule until we find a column we’ve visited before, memoizing the first such revisited column. Exactly one column in each cycle will be its own first revisited column.
> 6 votes

---
Tags: code-golf, sequence, arithmetic, game, combinatorics
---


title: CCC 2016: Circle of Life

text:
# Question
Title: CCC 2016: Circle of Life
# Before I begin, this challenge was not mine originally

Credits to The University of Waterloo. This came from the Canadian Computing Competition 2016, Senior Problem 5. Here is a clickable link to the contest PDF:

`http://cemc.uwaterloo.ca/contests/computing/2016/stage%201/seniorEn.pdf`

Here is a link to the site:

`http://cemc.uwaterloo.ca/contests/past_contests.html`

# Challenge

Given a wrapping array of two constant values, determine the configuration after `n` evolutions for positive integer input `n`. These two values represent a living cell and a dead cell. Evolutions work like this:

# Evolution!

After each iteration, a cell is alive if it had exactly one living neighbor in the previous iteration. Any less and it dies of loneliness; any more and it dies of overcrowding. The neighbourhood is exclusive: i.e. each cell has two neighbours, not three.

For example, let's see how `1001011010` would evolve, where `1` is a living cell and `0` is a dead cell.

```
(0) 1 0 0 1 0 1 1 0 1 0 (1)
    *   $         %

```

The cell at the `*` has a dead cell on both sides of it so it dies of lonliness.
The cell at the `$` has a living cell on one side of it and a dead cell on the other. It becomes alive.
The cel at the `%` has a living cell on both sides of it so it stays dead from overcrowding.

# Winning Criteria

Shortest code wins.

# I/O

Input will be a list of the cell states as two consistent values, and an integer representing the number of inputs, in some reasonable format. Output is to be a list of the cell states after the specified number of iterations.

# Test Cases

```
start, iterations -> end
1001011010, 1000 -> 1100001100
100101011010000, 100 -> 000110101001010
0000000101011000010000010010001111110100110100000100011111111100111101011010100010110000100111111010, 1000 -> 1001111111100010010100000100100100111010010110001011001101010111011011011100110110100000100011011001

```

Test Case
This test case froze hastebin and exceeded the size limit on pastebin

# Answer
# APL (Dyalog),14 bytes

Prompts for start state as Boolean list and then for number of iterations

```
(1∘⌽≠¯1∘⌽)⍣⎕⊢⎕

```

Try it online!

numeric prompt (for Boolean list of start state)

on that, apply

`(``)⍣⎕` the following tacit function, numeric-prompt times

`¯1∘⌽` the argument rotated one step right

different from (XOR)

`1∘⌽` the argument rotated one step left
> 6 votes

# Answer
# Jelly, 7 bytes

```
ṙ2^ṙ-µ¡

```

Try it online!

Extra Test Case (footer for formatting).

**Explanation**

```
ṙ2^ṙ-µ¡
     µ¡  - repeat a number of times equal to input 2:
ṙ2         - previous iteration rotated 2 to the left
  ^        - XOR-ed with:
           - (implicit) previous iteration
   ṙ-      - rotate back (by negative 1 to the left)

```
> 3 votes

# Answer
# 05AB1E, 6 bytes

```
FDÀÀ^Á

```

Try it online!

**Explanation**

```
F        # input_1 times do
 D       # duplicate last iteration (input_2 the first iteration)
  ÀÀ     # rotate left twice
    ^    # XOR
     Á   # rotate right

```
> 1 votes

---
Tags: code-golf, cellular-automata
---


title: Remove the Salutations

text:
# Question
Title: Remove the Salutations
## Challenge

Hi, given a string as input, remove any salutations found at the start of the string.

The program which performs the most correct substitutions in under 50 bytes wins.

## Salutations

Hey, a salutation is defined as one of the following words:

* hi
* hey
* hello
* dear
* greetings
* hai
* guys
* hii
* howdy
* hiya
* hay
* heya
* hola
* hihi
* salutations

The first letter may be capitalised.

There will always be a comma and/or a single space following the salutation which must also be removed. The comma and the space may be in any order (`,<space>` or `<space>,`) and both should be removed.

The greeting and the following word will only ever be separated by a comma and/or single space.

You must then capitalise the first letter of the word which would have followed the salutation. Even if no replacement has taken place, you should still capitalise the first word of the output.

Capitalisation only applies to lowercase alphabetical characters (`abcdefghijklmnopqrstuvwxyz`). You should leave any other character as it was.

The salutation will always be at the start of the string. You should not replace a salutation which is *not* at the start.

There may not always be a salutation.

Your code must be under 50 bytes.

## Examples

```
Input > Output

Salutations, what's going on? > What's going on?
hello i have quetions how does juice an avocado > I have quetions how does juice an avocado
How d'you do > How d'you do
Hey,You! > You!
hola cows eat hay > Cows eat hay
hey Hi there! > Hi there!
hihi ,guys > Guys

```

## Test battery

Hola, there are 1000 different inputs in total:

A Bash command to retrieve both the above is

```
wget https://raw.githubusercontent.com/beta-decay/Remove-Substitutions-Battery/master/{inputs,replaced}.txt

```

## Winning

Howdy, the program with the most correct substitutions from the 1000 inputs above wins.

You must put the percentage of the inputs your program handles correctly in your header like so:

```
# Language Name, percentage%

```

**I'm not completely sure why Jeff made this a thing, but it makes a nice challenge nevertheless.**

# Answer
# GNU sed, ~~78%~~ 100%

```
/^\w*[wd]\b/!s/^[dghs][eruaio]\w*\W\+//i
s/./\U&/

```

(49 bytes)

The test battery is quite limited: we can count which words appear first on each line:

```
$ sed -e 's/[ ,].*//' inputs.txt | sort | uniq -ic
 40 aight
 33 alright
 33 dear
 33 g'd
 41 good
 36 greetings
 35 guys
 31 hai
 33 hay
 27 hello
 33 hey
 37 heya
 43 hi
 34 hihi
 29 hii
 35 hiya
 45 hola
 79 how
 37 howdy
 33 kowabunga
 39 salutations
 32 speak
 34 sweet
 40 talk
 36 wassup
 34 what's
 38 yo

```

The salutations to be removed begin with `d`, `g`, `h` or `s` (or uppercase versions thereof); the non-salutations beginning with those letters are

```
 33 g'd
 41 good
 79 how
 32 speak
 34 sweet

```

Ignoring lines where they appear alone, that's 220 false-positives. So let's just remove initial words beginning with any of those four letters.

When we see an initial word beginning with any of those (`/ ^[dghs]\w*`), case-insensitively (`/i`), and followed by at least one non-word character (`\W\+`), then replace with an empty string. Then, replace the first character with its uppercase equivalent (`s/./\U&/`).

That gives us

```
s/^[dghs]\w*\W\+//i
s/./\U&/

```

We can now refine this a bit:

* The largest set of false-positives is `how`, so we make the substitution conditional by prefixing with a negative test:

```
 /^[Hh]ow\b/!

```
* We can also filter on the second letter, to eliminate `g'd`, `speak` and `sweet`:

```
s/^[dghs][eruaio]\w*\W\+//i

```
* That leaves only `good` as a false positive. We can adjust the prefix test to eliminate words ending in either `w` or `d`:

```
/^\w*[wd]\b/!

```

## Demonstration

```
$ diff -u <(./123478.sed inputs.txt) replaced.txt | grep ^- | wc -l
0

```
> 8 votes

# Answer
# Retina, ~~68%~~ 72.8% (old) ~~74.8%~~ 77.5% (new test battery)

```
i`^h(a[iy]|eya?|i(h?i|ya|)|ello)[ ,]+

T`l`L`^.

```

Try it online! Edit: Gained 4.8% (old) 2.7% (new) coverage with help from @MartinEnder's tips.
> 10 votes

# Answer
# PHP, 60.6%

50 Bytes

```
<?=ucfirst(preg_replace("#^[dh]\w+.#i","",$argn));

```

Try it online!

# PHP, 59.4%

49 Bytes

```
<?=ucfirst(preg_replace("#^h\w+,? #i","",$argn));

```

Try it online!

# PHP, 58.4%

50 Bytes

```
<?=ucfirst(preg_replace("#^[gh]\w+.#i","",$argn));

```

Try it online!
> 6 votes

# Answer
# Vim, ~~55.4%~~ 44.4%

```
df,<<vgU

```

Explanation:

```
df,    Delete until and including the first comma
<<     Remove leading spaces
vgU    Uppercase first letter

```
> 4 votes

---
Tags: code-challenge, test-battery
---


title: Challenge Similarity Detector

text:
# Question
Title: Challenge Similarity Detector
# Challenge

Given two question IDs, try to figure out how similar they are by looking at the answers.

# Details

You will be given two question IDs for `codegolf.stackexchange.com`; you may assume that there exist questions for both IDs that are not deleted, but are not necessarily open. You must run through all of the answers and determine the minimum Levenshtein distance between the code in the answers to the two questions (not including deleted answers). That is, you should compare every answer in question 1 to every answer in question 2, and determine the minimum Levenshtein distance. To find the code in an answer, assume the following procedure:

### How to find the code snippet

A body of text is the answer's actual code if it is in backticks and is on its own line, or if it is indented with 4 spaces, with an empty line above it, unless there is no text above.

### Examples of valid and not-valid code snippets (with `.` as a space) (separated by a ton of equal signs)

```
This is `not a valid code snippet because it is not on its own line`
========================================
This is:
`A valid code snippet`
========================================
This is
....not a valid code snippet because there's no spacing line above
========================================
This is

....A valid code snippet because there's a spacing line above
========================================
....Valid code snippet because there's no other text
========================================

```

If there are no valid code snippets in the answer, ignore the answer completely. **Note that you should only take the first codeblock.**

# Final Specs

The two question IDs can be inputted in any reasonable format for 2 integers. The output should be the smallest Levenshtein distance between any two valid answers from either challenge. If there are no "valid" answers for one or both of the challenges, output `-1`.

# Test Case

For challenge `115715` (Embedded Hexagons) and `116616` (Embedded Triangles) both by Comrade SparklePony, the two Charcoal answers (both by KritixiLithos) had a Levenshtein distance of 23, which was the smallest. Thus, your output for `115715, 116616` would be `23`.

# Edit

You may assume that the question has at most 100 answers because of an API pagesize restriction. You should not ignore backticks in code blocks, only if the code block itself is created using backticks and not on its own line.

# Edit

I terminated the bounty period early because I made a request to a mod to get a one-week suspension and I didn't want the bounty to be automatically awarded to the highest scoring answer (which happens to be the longest). If a new submission comes in or a submission is golfed enough to become shorter than 532 bytes before the actual end of the bounty period (UTC 00:00 on Jun 1), I will give that a bounty to stay true to my promise, after the suspension expires. If I remember correctly, I need to double the bounty period next time so if you do get an answer in, you might get +200 :)

# Answer
> 1 votes
## PowerShell, 532 Bytes

```
$1,$2=$args
$a={irm "api.stackexchange.com/2.2/questions/$args/answers?pagesize=100&site=codegolf&filter=!9YdnSMKKT"|% i*}
$r={$args.body-replace"(?sm).*?^(<pre.*?>)?<code>(.*?)</code>.*",'$2'}
$1=&$a $1;$2=&$a $2
(0..($1.count-1)|%{
    $c=&$r $1[$_]
    0..($2.count-1)|%{
        &{$c,$d=$args;$e,$f=$c,$d|% le*;$m=[object[,]]::new($f+1,$e+1);0..$e|%{$m[0,$_]=$_};0..$f|%{$m[$_,0]=$_};1..$e|%{$i=$_;1..$f|%{$m[$_,$i]=(($m[($_-1),$i]+1),($m[$_,($i-1)]+1),($m[($_-1),($i-1)]+((1,0)[($c[($i-1)]-eq$d[($_-1)])]))|sort)[0]}};$m[$f,$e]} $c $d
    }
}|sort)[0]

```

I left newlines in there for some readability. The are still reflected in my byte count.

Pretty sure I have a handle on this. The tough part for me was actually getting the Levenshtein distance since PowerShell does not have a builtin for that as far as I know. Because of that I was able to answer the related challenge on Levenshtein distance. When my code refers to an anonymous function for LD you can refer to that answer for a more detailed explanation as to how that works.

### Code with comments and progress indicator

The code can get real slow (because of the LD) so I built in some progress indicators for myself so I could follow the action as it unfolded and not assume it was stuck in a loop somewhere. The code for monitoring progress is not in the top block nor counted in my byte count.

```
# Assign the two integers into two variables.
$1,$2=$args

# Quick function to download up to 100 of the answer object to a given question using the SE API
$a={irm "api.stackexchange.com/2.2/questions/$args/answers?pagesize=100&site=codegolf&filter=!9YdnSMKKT"|% i*}

# Quick function that takes the body (as HTML) of an answer and parses out the likely codeblock from it.
$r={$args.body-replace"(?sm).*?^(<pre.*?>)?<code>(.*?)</code>.*",'$2'}

# Get the array of answers from the two questions linked.
$1=&$a $1;$2=&$a $2

# Hash table of parameters used for Write-Progress
# LD calcuations can be really slow on larger strings so I used this for testing so I knew
# how much longer I needed to wait.
$parentProgressParameters = @{
    ID = 1
    Activity = "Get LD of all questions"
    Status = "Counting poppy seeds on the bagel"
}

$childProgressParameters = @{
    ID = 2
    ParentID = 1
    Status = "Progress"
}

# Cycle each code block from each answer against each answer in the other question.
(0..($1.count-1)|%{
    # Get the code block from this answer
    $c=&$r $1[$_]

    # Next line just for displaying progress. Not part of code.
    Write-Progress @parentProgressParameters -PercentComplete (($_+1) / $1.count * 100) -CurrentOperation "Answer $($_+1) from question 1"

    0..($2.count-1)|%{
        # Get the code block from this answer
        $d=&$r $2[$_]

        # Next two lines are for progress display. Not part of code.
        $childProgressParameters.Activity = "Comparing answer $($_+1) of $($2.count)"
        Write-Progress @childProgressParameters -PercentComplete (($_+1) / $2.count * 100) -CurrentOperation "Answer $($_+1) from question 2"

        # Anonymous function to calculate Levenstien Distance
        # Get a better look at that function here: https://codegolf.stackexchange.com/a/123389/52023
        &{$c,$d=$args;$e,$f=$c,$d|% le*;$m=[object[,]]::new($f+1,$e+1);0..$e|%{$m[0,$_]=$_};0..$f|%{$m[$_,0]=$_};1..$e|%{$i=$_;1..$f|%{$m[$_,$i]=(($m[($_-1),$i]+1),($m[$_,($i-1)]+1),($m[($_-1),($i-1)]+((1,0)[($c[($i-1)]-eq$d[($_-1)])]))|sort)[0]}};$m[$f,$e]} $c $d
    }
# Collect results and sort leaving the smallest number on top.
}|sort)[0]

```

My logic for finding the code blocks is to take answer as HTML and look for a code tag set, optionally surrounded by a pre tag set that starts on its own line. In testing it found all the correct data on 6 different question sets.

I tried to work from the markdown code but it was too difficult to find the right code block.

### Sample runs

```
Challenge-Similarity-Detector 97752 122740
57

Challenge-Similarity-Detector 115715 116616
23

```

# Answer
> 3 votes
# **Java + Jsoup, 1027 bytes**

The first two arguments are the question IDs.

**Golfed:**

```
import org.jsoup.*;import org.jsoup.nodes.*;class M{String a1[]=new String[100],a2[]=new String[100],c[];int i1=0,i2=0;public static void main(String a[])throws Exception{String r="https://codegolf.stackexchange.com/questions/";M m=new M();m.c=m.a1;m.r(Jsoup.connect(r+a[0]).get());m.c=m.a2;m.r(Jsoup.connect(r+a[1]).get());int s=m.ld(m.a1[1],m.a2[1]);for(int i=2;i<m.a1.length;i++)for(int j=2;j<m.a2.length;i++){if(m.a1[i]==null)break;int d=m.ld(m.a1[i],m.a2[j]);if(d<s)s=d;}System.out.print(s);}void r(Document d){a:for(Element e:d.select("td")){for(Element p:e.select("pre")){ a(p.select("code").get(0).html());continue a;}}}void a(String d){c[c==a1?i1++:i2++]=d;}int ld(String a,String b){a=a.toLowerCase();b=b.toLowerCase();int[]costs=new int[b.length()+1];for(int j=0;j<costs.length;j++)costs[j]=j;for(int i=1;i<=a.length();i++){costs[0]=i;int nw=i-1;for(int j=1;j<=b.length();j++){int cj=Math.min(1+Math.min(costs[j],costs[j-1]),a.charAt(i-1)==b.charAt(j-1)?nw:nw+1);nw=costs[j];costs[j]=cj;}}return costs[b.length()];}}

```

**Readable:**

```
import org.jsoup.*;import org.jsoup.nodes.*;

class M {
    String a1[]=new String[100],a2[]=new String[100],c[];
    int i1=0,i2=0;
    public static void main(String a[])throws Exception{
    String r="https://codegolf.stackexchange.com/questions/";
    M m=new M();

    m.c=m.a1;
    m.r(Jsoup.connect(r+a[0]).get());
    m.c=m.a2;
    m.r(Jsoup.connect(r+a[1]).get());

    int s=m.ld(m.a1[1],m.a2[1]);
    for(int i=2;i<m.a1.length;i++)for(int j=2;j<m.a2.length;i++){if(m.a1[i]==null)break;int d=m.ld(m.a1[i],m.a2[j]);if(d<s)s=d;}
    System.out.print(s);
}

void r(Document d) {
    a:for(Element e:d.select("td")) {for(Element p:e.select("pre")) {
        a(p.select("code").get(0).html());
        continue a;
    }}
}

void a(String d){c[c==a1?i1++:i2++]=d;}

int ld(String a, String b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    int [] costs = new int [b.length() + 1];
    for (int j = 0; j < costs.length; j++)costs[j] = j;
    for (int i = 1; i <= a.length(); i++) {
        costs[0] = i;
        int nw = i - 1;
        for (int j = 1; j <= b.length(); j++) {
            int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);
            nw = costs[j];
            costs[j] = cj;
        }
    }
    return costs[b.length()];
}

```

}

# Answer
> 0 votes
# Mathematica, 540 bytes

```
f=Flatten;l=Length;P=StringPosition;(H[r_]:=Block[{s,a,t,k},t={};d=1;k="https://codegolf.stackexchange.com/questions/"<>r;s=First/@P[Import[k,"Text"],"<pre><code>"];a=f[First/@P[Import[k,"Text"],"answerCount"]][[1]];While[d<l@s,If[s[[d]]>a,AppendTo[t,s[[d]]]];d++];Table[StringDelete[StringCases[StringTake[Import[k,"Text"],{t[[i]],t[[i]]+200}],"<pre><code>"~~__~~"</code></pre>"],{"<pre><code>","</code></pre>"}],{i, l@t}]];Min@DeleteCases[f@Table[EditDistance[ToString@Row@H[#1][[i]],ToString@Row@H[#2][[j]]],{i,l@H[#1]},{j,l@H[#1]}],0])&

```

**input**

> \["115715", "116616"\]

**output**

> 23

uses built-in EditDistance which "gives the edit or Levenshtein distance between strings or vectors u and v."

As for the test case mathematica

```
EditDistance["ＦＮ«ＡＸ²ιβ×__β↓↘β←↙β↑←×__β↖β→↗β","ＮαＷα«Ｘ²ι↙ＡＸ²⁻ι¹β↙β↑↖β→Ａ⁻α¹α"]

```

returns 23

I guess I can golf it a bit more
Takes some minutes to run

---
Tags: code-golf, string, stack-exchange-api
---