# Question
Title: Find a binary needle in a decimal haystack
## The challenge

You're given:

* a non-empty, unsorted list **h** of positive integers (the haystack)
* a positive integer **n** (the needle)

Your task is to return the list of all ***unique*** decimal concatenations of permutations of **h** whose binary representation contains the binary representation of **n**.

## Examples

1. **h = \[ 1, 2, 3 \]**
**n = 65**

There's only one matching concatenation, so the expected output is `[321]`.
2. **h = \[ 1, 2, 3 \]**
**n = 7**

This time, there are three concatenations which contain the binary pattern **111**. The expected output is `[123, 231, 312]`.
3. **h = \[ 12, 3 \]**
**n = 7**

Only two permutations are available and both are matching. The expected output is `[123, 312]`.
4. **h = \[ 1, 2, 2 \]**
**n = 15**

The only matching concatenation is **122** (**1111010** in binary, which contains **1111**), so the expected output is `[122]`. Note that two permutations actually lead to **122** but you are *not* allowed to output `[122, 122]`.

## Clarifications and rules

* You may take the needle as an integer (`65`), a string representing a decimal value (`"65"`) or a string representing a binary value (`"1000001"`).
* You may take the haystack as a native array/object/set of integers (`[11,12,13]`), a native array/object/set of strings representing decimal values (`["11","12","13"]`), or a delimited string of decimal values (`"11 12 13"` or `"11,12,13"`). You may also opt for a variant using arrays of digits (like `[[1,1],[1,2],[1,3]]`).
* The output must follow one of the formats described above for the haystack, but not necessarily the same one.
* You're not supposed to handle haystacks whose highest decimal concatenation is greater than the highest representable unsigned integer in your language.
* Apart from that, your code should theoretically support any input -- assuming it's given enough time and memory.
* This is ~~SPARTA!~~ , so the shortest answer in bytes win!

## Test cases

```
Haystack             | Needle   | Output
---------------------+----------+-----------------------------------
[ 1, 2, 3 ]          | 65       | [ 321 ]
[ 1, 2, 3 ]          | 7        | [ 123, 231, 312 ]
[ 12, 3 ]            | 7        | [ 123, 312 ]
[ 1, 2, 2 ]          | 15       | [ 122 ]
[ 1, 2 ]             | 7        | []
[ 12, 34, 56 ]       | 21       | [ 125634, 341256, 345612, 563412 ]
[ 1, 2, 3, 4, 5 ]    | 511      | [ 53241 ]
[ 1, 3, 5, 7, 9 ]    | 593      | [ 37519, 51793, 75913, 75931 ]
[ 11, 12, 13, 14 ]   | 12141311 | [ 12141311 ]
[ 1, 2, 1, 2, 1, 2 ] | 1015     | [ 221112 ]

```

# Answer
> 17 votes
# 05AB1E, ~~10~~ 8 bytes

Takes the needle in binary to save 1 byte.

-2 bytes thanks to Emigna

```
œJÙʒbŒIå

```

Try it online!

```
œJÙʒbŒIå   Arguments: a, n
œJÙ        Get all unique permutations of a
   ʒ       Filter: Keep if following code returns true
    b      Convert to binary
     Œ     Get all substrings
      Iå   Check if substrings contain n
           Implicit output of filtered list

```

# Answer
> 11 votes
## Python 2, 90 bytes

-3 bytes thanks to @Gábor Fekete

Try it online

Takes as input array of strings, representing ints from hay and string, representing needle in binary

```
from itertools import*
lambda H,N:{i for i in permutations(H)if N in bin(int(''.join(i)))}

```

# Answer
> 10 votes
# Java 10, ~~320~~ ~~312~~ ~~305~~ ~~297~~ 292 bytes

```
import java.util.*;Set s=new HashSet();l->n->{Long q=0;p(l,0);for(var x:s)if(q.toString(q.decode(x+""),2).contains(n))System.out.println(x);}void p(List l,int k){int i=k,x=l.size();for(Collections C=null;i<x;p(l,k+1),C.swap(l,k,i++))C.swap(l,i,k);if(k>x-2)s.add((l+"").replaceAll("\\D",""));}

```

Input as List & binary-String, output as Strings on new-lines.

**Explanation:**

Try it here.

```
import java.util.*;           // Required import for Set, HashSet, List, and Collections

Set s=new HashSet();          // Class-level Set

l->n->{                       // Method (1) with List and String parameters and no return-type
  Long q=0;                   //  Number-object is required for two static method-calls below
  p(l,0);                     //  Determine all permutations of given list and put it in the Set
  for(var x:s)                //  Loop over these permutations
    if(q.toString(q.decode(x+""),2)
                              //   If the binary String of the current permutation
        .contains(n))         //   contains the binary String of the input integer
      System.out.println(x);} //    Print this permutation

void p(List l,int k){         // Method (2) with List and integer parameters and no return-type
  int i=k,x=l.size();         //  Two temp integers
  for(Collections C;          //  Collections-object is required for two static method-calls below
      i<x                     //  Loop `i` in the range [`k`, list-size)
      ;                       //    After every iteration:
       p(l,k+1),              //     Do a recursive-call to this method with `k+1`
       Collections.swap(l,k,i++))
                              //     And swap the items at indices `k` and `i` back
    Collections.swap(l,i,k);  //   Swap the items at indices `i` and `k`
  if(k>x-2)                   //  If `k` is now equal to the size of the list - 1
    s.add((l+"").replaceAll("\\D",""));}
                              //   Add this permutation to the Set

```

# Answer
> 9 votes
# Japt, ~~15~~ ~~14~~ ~~13~~ ~~12~~ 10 bytes

Takes the haystack as an array of integers and the needle as a binary string. Outputs an array of integer strings.

```
á m¬f_°¤øV

```

Try it

---

## Explanation

```
á m¬â f_°¤øV
              :Implicit input of array U=haystack and string V=needle
á             :Unique permutations of U
  m           :Map
   ¬          :  Join to a string
    f_        :Filter
      °       :  Postfix increment current element to cast it to an integer
       ¤      :  Convert to base-2 string
        øV    :  Does that contain V?
              :Implicit output of resulting array

```

# Answer
> 4 votes
# Ruby, ~~61~~ 59 bytes

```
->a,n{a.permutation.select{|s|"%b"%s.join=~/#{"%b"%n}/}|[]}

```

Try it online!

Cool feature of the day: I didn't know I could output the binary representation of a string containing a number.

Example:

```
puts "%b"%"123"

-> 1111011

```

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

Takes needle as a binary string.

```
(h,n,S=new Set,p=(a,m='')=>a.length?a.map((_,i)=>p(A=[...a],m+A.splice(i,1))):S.add(+m),_=p(h))=>[...S].filter(d=>~d.toString(2).indexOf(n))

```

```
f=
(h,n,S=new Set,p=(a,m='')=>a.length?a.map((_,i)=>p(A=[...a],m+A.splice(i,1))):S.add(+m),_=p(h))=>[...S].filter(d=>~d.toString(2).indexOf(n))

console.log( f([1, 2, 3], (65).toString(2)) )
console.log( f([12, 34, 56], (21).toString(2)) )
```

# Answer
> 3 votes
# Brachylog, 15 bytes

```
{hpc.ḃs~ḃ~t?∧}ᵘ

```

Try it online!

### Explanation

```
{            }ᵘ    Find all unique outputs, given [h, n], of:
 hpc.                The Output is the concatenation of a permutation of h
    .ḃs              Take a substring of the binary representation of the Output
       ~ḃ            Convert it back to a decimal number
         ~t?∧        This decimal number must me n

```

# Answer
> 2 votes
## Mathematica, ~~170~~ 156 bytes

```
(t={};l=Length;v=IntegerDigits;j=v[#2, 2];s=FromDigits/@Flatten/@v@Permutations@#1;Table[If[l@SequenceCases[v[s[[i]],2],j]>0,t~AppendTo~s[[i]]],{i,l@s}];t)&

```

**input**

> \[{12, 34, 56}, 21\]

**output**

> {125634, 341256, 345612, 563412}

# Answer
> 1 votes
## CJam, ~~23~~ ~~22~~ ~~21~~ 19 bytes

```
{e!{si2b1$2b#)},\;}

```

This is a block that takes inputs `n h` on the stack and leaves the output as an array on the stack.

Explanation:

```
                   e# Stack:                      | 65 [1 2 3]
e!                 e# Unique Permutations:        | 65 [[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 1 2] [3 2 1]]
  {                e# Filter where block is true: | 65 [3 2 1]
   s               e#   Convert to string:        | 65 "321"
    i              e#   Convert to int:           | 65 321
     2b            e#   Convert to binary:        | 65 [1 0 1 0 0 0 0 0 1]
       1$          e#   Copy behind:              | 65 [1 0 1 0 0 0 0 0 1] 65
         2b        e#   Convert to binary:        | 65 [1 0 1 0 0 0 0 0 1] [1 0 0 0 0 0 1]
           #       e#   Find array in another:    | 65 2
            )      e#   Increment:                | 65 3
             },    e# End filter                  | 65 [321]
               \;  e# Delete back:                | [321]

```

# Answer
> 1 votes
# R, 114 bytes

```
pryr::f(plyr::l_ply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste(y,collapse=""))))cat(y,"\n")))

```

Uses a bunch of packages. `pryr::f()` automatically creates a function, taking `p`, a string of the binary pattern to look for, and `x`, a vector with the other input as input. `combinat::permn` creates all permutations of `x`. `R.utils::intToBin` is a nice and wordy version to convert a numeric (or character representation of a numeric) to a binary number, already conveniently stored as a character. So applying this over all the permutations and outputting them if the binary string `p` is contained in the binary version of the concatenation. An explicit newline is printed, because otherwise the output would be `12 56 3456 34 1234 56 1234 12 56`.

`plyr`'s `l_ply` is used to surpress outputting a null list, besides the regular output. If output like this is allowed:

```
3 2 1
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

[[6]]
NULL

```

Then we can save few bytes by using `lapply` instead:

## 108 bytes:

```
pryr::f(lapply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste(y,collapse=""))))cat(y,"\n")))

```

~~If output like this is allowed:~~

~~```
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
[1] 3 2 1

[[5]]
NULL

[[6]]
NULL

```
Then we can do it even shorter:<br>101 bytes:
```
pryr::f(lapply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste0(y,collapse=""))))y))

```~~

Not allowed.

# Answer
> 0 votes
# Perl 6, 69 bytes

```
{set @^a.permutations».join.grep(*.fmt('%b').contains($^b.base(2)))}

```

---
Tags: code-golf, binary, permutations
---


title: Straddling Checkerboard Cipher

text:
# Question
Title: Straddling Checkerboard Cipher
The Straddling Checkerboard is a method for converting letters to numbers and was part of a pencil an paper cipher known as VIC

To convert letters to numbers first you have to make a checkboard like this:

```
    0   1   2   3   4   5   6   7   8   9
   ---------------------------------------
    E   T       A   O   N       R   I   S
2 | B   C   D   F   G   H   J   K   L   M
6 | P   Q   #   U   V   W   X   Y   Z   .

```

Is a 10 x 3 table filled with 28 different simbols and two blanks on the first row.

The labels of second and third row are the position of the blanks on the first one.

To cipher a message you have to replace each letter with the column label. If it is not on the first row, prepend row label:

```
G -> 24
O -> 4
L -> 28
F -> 23

```

The extra simbols `#` and `.` are used to escape numbers and to indicate full-stop.

# Task

## Input:

* 0 to 26 unsorted unique letters (key)
* 4 digits, #1 != #2 and #3 != #4
* Alphanumeric message to be encoded

## Output:

* Digits representing the encoded message

## Implementation:

The table will be filled with the 26 character recived by input. If lengh is less than 26, the remaining spaces will be filled with the missing letters in alphabetical order. The first two integers represent the blank spaces on the first row (and labels for second and third row).Next two integers represent the position of `#` and `.` on the third row.

> ### Example:
>
> **Input:** codeglf , 4 6 8 9 , "programming puzzles are gr8."
>
> Yields this table:
>
> ```
>    0 1 2 3 4 5 6 7 8 9
>    -------------------
>    c o d e   g   l f a
> 4| b h i j k m n p q r
> 6| s t u v w x y z # .
>
> ```
>
> **Output:** 47491549945454246547727777637094935496886869

**Note1:** Spaces are not encoded and not included in the output.

**Note2:** Original message may contain letters, numbers, spaces and . (assume same capitalisation as the key)

**Note3:** If there is a number in the original message you have to output the corresponding code number for `#` followed by the number then another `#` code (68 in the example) and then continue with the letters.

> ### Example2:
>
> **Input:** toearly , 2 8 6 1 , "wake up at 06.am"
>
> ```
>    0 1 2 3 4 5 6 7 8 9
>    -------------------
>    t o   e a r l y   b
> 2| c d f g h i j k m n
> 8| p . q s u v # w x z
>
> w  a  k e  u  p a t  # 0 6  #  . a  m
> 87 4 27 3 84 80 4 0 86 0 6 86 81 4 28
>
> ```
>
> **Output:** 87427384804086068681428

This is the complete VIC cipher question.

# Answer
# PHP\>=7.1, 226 Bytes

```
for([,$c,$a,$b,$d,$e,$t]=$argv,$c.=join(preg_grep("#[^$c]#",range(a,z)));$p<30;)$x[in_array($y=["",$a,$b][$p/10].$p++%10,[$a,$b,$b.$d,$b.$e])?"__#."[$m++]:$c[$i++]]=$y;for(;a&$w=$t[$k++];)echo is_numeric($w)?$x["#"].$w:$x[$w];

```

Online Version

Expanded

```
for([,$c,$a,$b,$d,$e,$t]=$argv #short variables in input array
,$c.=join(preg_grep("#[^$c]#",range(a,z))) # join the rest of alphabet
;$p<30;) # loop 30 times
  $x[in_array($y=["",$a,$b][$p/10].$p++%10 # is actual position reserved?
  ,[$a,$b,$b.$d,$b.$e]) # reserved positions
    ?"__#."[$m++] # set reserved positions with chars underscore instead spaces to avoid encoding
    :$c[$i++]] # set alpabetic characters
  =$y; # make encoding array
for(;a&$w=$t[$k++];) # loop through string which shall be encoded
  echo is_numeric($w)
    ?$x["#"].$w # printing for digits
    :$x[$w]; #printing for the other characters

```
> 2 votes

# Answer
## JavaScript (ES6), 236 bytes

```
(k,s,t,h,d,m)=>m.replace(/./g,c=>1/c?c>' '?''+t+h+c:'':(c=a.indexOf(c))>9?''+(c>19?t:s)+c%10:c,l=[...'zyxwvutsrqponmlkjihgfedcba'].filter(c=>k.search(c)<0),i=0,a=[...Array(30)].map((_,n)=>n-s&&n-t&&n-h-20?n-d-20?k[i++]||l.pop():'.':''))

```

Creates the checkboard `a` (except for the `#`, which is special-cased), then replaces letters and `.` in the message with the appropriately translated index while digits are prefixed with the code for `#`.
> 2 votes

# Answer
# , ~~286 281~~ 261 bytes

Bit horrible looking and I am sure there is room for improvement, but I wanted to make sure I was doing it correctly before really getting into it.

Have changed it a bit to use 2 arrays and handle the numbers differently. Hopefully this makes it easier to golf.

Implemented as an unnamed function that take 4 parameters \- `k` the key for the table \- `x` a vector containing the row name integers \- `y` a vector containing the "#",'.' locations \- `s` the string to encode

```
function(k,x,y,s){W=which
S=strsplit
P=paste0
L=letters
m=rep(NA,40)
m[c(1:10,x+11,y+31)]=c(0:9,'','','#','.')
m[is.na(m)]=c(d<-el(S(k,'')),L[-W(L%in%d)])
i=t(outer(c(P(x[2],y[1]),'',x),0:9,P));cat(sapply(el(S(gsub(' ','',s),'')),function(x)i[W(m==x)]),sep='')}

```

Try it online!

I have loaded the library `methods` in TIO example to get `el()` to work, however this is not required on my version of R.
> 1 votes

---
Tags: code-golf, cryptography, encryption
---


title: Generate chord charts for ukulele

text:
# Question
Title: Generate chord charts for ukulele
Your task is to write a function which outputs a ukulele chord chart in the following format for a given chord symbol. For instance, for input "`G7`", it must output:

```
 G C E A
---------
| | |#| |
---------
| |#| |#|
---------
| | | | |
---------
| | | | |
---------
| | | | |
---------

```

> It must support all chords of these forms: **X Xm X7 Xm7 Xmaj7 Xsus4 Xdim Xdim7**
>
> where X is any of **A A# B C C# D D# E F F# G G#**

(Supporting flats, such as Bb and Eb, is not required.)

The rest of the challenge description (until "Output and scoring") is purely explanatory: if you know ukulele chords already, you don't need it.

There are three steps parts to producing the chart for a chord.

1. First, work out which notes are in the chord.
2. Choose the correct fret for each string to match the notes.
3. Draw the chart.

## Work out which notes are in the chord

There are 12 **notes** in the cyclical music scale, each a **semitone** apart: `A, A#, B, C, C#, D, D#, E, F, F#, G, G#`, then A, A#....

*(If you're not into music, just mentally translate every "`A`" into a `0`, every "`A#`" into a `1`, etc, and everything will work out just fine.)*

A **chord** is a set of 3 or 4 notes, according to a defined pattern of intervals starting from the **base note**:

* `X`: 0 + 4 + 3 ("major"). *Example: C, C+E+G*
* `Xm`: 0 + 3 + 4 ("minor"). *Example: Cm, C+D#+G*
* `X7`: 0 + 4 + 3 + 3 ("seven"). *Example: C7, C+E+G+A#*
* `Xm7`: 0 + 3 + 4 + 3 ("minor seven"). *Example: Cm7, C+D#+G+A#*
* `Xmaj7`: 0 + 4 + 3 + 4 ("major seven") . *Example: Cmaj7, C+E+G+B*
* `Xsus4`: 0 + 5 + 2 ("sus four"): *Example: Csus4, C+F+G*
* `Xdim`: 0 + 3 + 3 ("diminished"). *Example: Cdim, C+D#+F#*
* `Xdim7`: 0 + 3 + 3 + 3 ("diminished seven"). *Example: C+D#+F#+A#. \[You may find it helpful to know that this is the same chord as A#dim7, D#dim7 and F#dim7\].*

(The name in parentheses is just for your music education, it's not relevant to the challenge.)

For instance: "`Am`" is a chord, where "A" is the base note, and "m" is the chord type. Looking up the table ("Xm: 0 + 3 + 4"), we see it has 3 notes:

* the base note (`A`),
* the note 3 semitones above (`C`, counting `A#` and `B`), and
* the note 4 semitones above that (`E`).

(Chords that have 3 notes will by necessity be repeating one of the notes across the 4 strings. That's fine.)

## Choose the correct frets for the notes

Ukulele is an instrument with four **strings**, that play the notes G, C, E and A. Pressing the string against a **fret** makes it sound higher, one semitone per fret. (Pressing fret 1 on the A string turns it to A#, fret 2 turns it to B, etc).

### Chord charts

The chord chart represents the first few frets, played by the left hand, read from top to bottom ("higher" frets are lower down the page). The **strings** are the columns separated by **`|`** symbols. The **frets** are the rows separated by **`-`** symbols. The symbol **`#`** means that the string is pressed against that fret ("is fretted"), while the right hand strums.

So in the chord chart at the start:

* The G string is not fretted (it is "open"), so it sounds like G.
* The C string is fretted on fret 2 (two semitones up), so it sounds like D.
* The E string is on fret 1 (one semitone up), and sounds like F.
* The A string is on fret 2, so sounds like B.

So this chord has notes: G, D, F, B. (It's G7, G+B+D+F - the order of the pitches doesn't matter.)

### Calculating chords

To calculate which fret to play for a given string, for a given chord:

* if the string's base note (G, E, A or C) is not already in the chord, play the lowest fret that belongs to the chord
* repeat for each of the four strings.

### Example #1

For instance, let's play `E7` (consisting of `E` \+ `G#` \+ `B` \+ `D`).

1. The `G` string is not in the chord. Raise it to `G#` (fret 1).
2. The `C` string is not in the chord. Raise it to `D` (fret 2).
3. The `E` string is in the chord. Don't fret it. (Leave the string open.)
4. The `A` string is not in the chord. Raise it to `B` (fret 2).

So we are playing: `G#`, `D`, `E`, `B`.

So we output:

```
 G C E A
---------
|#| | | |
---------
| |#| |#|
---------
| | | | |
---------
| | | | |
---------
| | | | |
---------

```

### Example #2

Another example: `G#` (consisting of `G#` \+ `B#` \+ `D#`):

1. The `G` string is not in the chord, raise it to `G#` (fret 1).
2. The `C` string is in the chord (B#), don't fret it.
3. The `E` string is not in the chord, raise it to `G#` (fret 4).
4. The `A` string is not in the chord, raise it to `B#`(C) (fret 3)

So we are playing `G#`, `C`, `G#`, `C`

```
 G C E A
---------
|#| | | |
---------
| | | | |
---------
| | | |#|
---------
| | |#| |
---------
| | | | |
---------

```

(You may notice that sometimes not every note in the chord ends up getting played. Don't worry about it. "Proper" ukulele chords are slightly more complicated than this basic algorithm.)

## Output and scoring

Your output must closely match the above. (You can use other characters instead of `|`, `-` and `#`, such as em-dashes or ASCII line-drawing characters, if they are visually superior. An unfilled circle character would be better than `#`). Trailing linespace on each line is ok. Whitespace before the first line or after the last line is not ok. Final linefeed is optional.

Normal forms of input and output. You will receive one chord name, guaranteed to be in the table above, in the correct case.

Standard loopholes disallowed. Online services are disallowed. If your language has music functions in its standard library, you may use them (but not if they're plugins, packages, etc.)

This is . Lowest score (in bytes) wins.

## Extra credit

This simple algorithm sometimes produces useless chord fingerings that don't include all the important notes of the chord. (For instance, for `Dm`, it produces `ACFA`, the same as `Fm`.)

For extra credit, modify the algorithm so that:

* For all chords, the root and third (first two notes, usually 0 and 3 or 0 and 4) are played on at least one string each.
* For 4-note chords (X7, Xm7, Xmaj7, Xdim7), the root, third and seventh (first, second and fourth notes) are played on at least one string each.

# Answer
> 5 votes
## Javascript 280 ~~282~~ ~~287~~ bytes

(Non-meaningful linebreaks inserted for readability)

```
f=

a=>' G C E A'+[1,2,3,4,5].map(y=>
(l=`
---------
`)+[-2,3,7,0].map(
x=>(z=a.match(/(.#?)(.*)/),
[...'9'+{'':14,7:147,m:40,m7:740,maj7:148,sus4:24,dim:30,dim7:360}[z[2]]]
.map(i=>(i-x+'D EF G A BC'.search(z[1][0])+!!z[1][1]+8)%12)
.sort((a,b)=>a-b)[0]-y?'| ':'|#'
)).join``+'|').join``+l

document.getElementById("mysubmit").onclick=function() {
  document.getElementById("out").innerHTML=f(document.getElementById("myinput").value)
}
```

```
<input type="text" value="G7" id="myinput">
<input type="submit" id="mysubmit">
<pre id="out"></pre>
```

## Commentary

I've never been so happy at Javascript's weird type conversions. This is probably the first time I've ever wanted 40 + 9 to equal 409 :) It's also really fortunate that integers are acceptable as keys in Objects.

There's nothing too clever going on here. I subtract 3 from each chord note in order to keep the range within 0-9, so that I can temporarily express a chord as a 3-digit number. Luckily, the order of notes isn't important, so we can express 036 as 360.

# Answer
> 3 votes
# Python 2, 518, 448 bytes

Thanks to Wheat Wizard for the coding suggestions!

```
S='GCEA'
N=['A','A#','B','C','C#','D','D#','E','F','F#','G','G#']
C={'':(0,4,7),'m':(0,3,7),'7':(0,4,7,10),'m7':(0,3,7,10),'maj7':(0,4,7,11),'sus4':(0,5,7),'dim':(0,3,6),'dim7':(0,3,6,9)}
x=raw_input()
j=1+('#'in x)
c=[]
for s in S:c.append(min((N.index(i)-N.index(s))%12for i in [N[(a+N.index(x[:j]))%12]for a in C[x[j:]]]))
print' '+''.join(a+' 'for a in S)
for f in range(5):f=['|o'if i==f+1else'| 'for i in c];print'-'*9,'\n',''.join(f)+'|'

```

Try it online!

## Sample Output

```
G
 G C E A
---------
| | | | |
---------
| |o| |o|
---------
| | |o| |
---------
| | | | |
---------
| | | | |

```

## Commentary

Thanks for a fun challenge. My daughter and I are off to buy a uke this weekend. I've never played the uke, but I play mandolin, and the theory is similar.

For this submission (my first), I addressed the original challenge without the extra credit components. I fear addressing the extra credit questions will add a lot of of bytes to the code. I hope to submit again with the extra credit bits, time permitting.

The logic is pretty simple if you trace your way back through the successive functions: 1. Parse the chord description. 2. Identify what notes are in that chord. 3. Figure out what frets on each string would fit 4. Assemble a chord by selecting the lowest fret that works on each string 5. Print out the chart fret by fret.

The core of the golfed code lies in the gnarly mess of nested list comprehensions in the eighth -- now seventh -- line of the code. The best way I can explain what's going on is by presenting the ungolfed version.

(Wheat Wizard suggested a shift from list comprehensions to generators that was not reflected in this ungolfed code)

```
STRINGS = 'GCEA' # Ukelele
#STRINGS = 'GDAE' # Mandolin
NOTES=['A','A#','B','C','C#','D','D#','E','F','F#','G','G#']
TYPES = {'':(0,4,7),
     'm':(0,3,7),
     '7':(0,4,7,10),
     'm7':(0,3,7,10 ),
     'maj7':(0,4,7,11),
     'sus4':(0,5,7),
     'dim':(0,3,6),
     'dim7':(0,3,6,9)}

def parse(x):
    # parses the chord into the root and the chord type
    i=2 if '#' in x else 1
    return x[:i],x[i:]

def strng(string,notes):
    # Return a list of possible fret locations based on notes in a chord
    # This will return all possible fret locations, including those
    # beyond the fifth fret, where this code stops drawing.
    return sorted([(NOTES.index(i)-NOTES.index(string))%12 for i in notes])

def chordnotes(note,typ):
    #return the list of Notes that belong to the chord
    return  [NOTES[(a+NOTES.index(note))%12] for a in TYPES[typ]]

def chord((note,typ)):
    # Returns a list of four fret locations, in order of the strings.
    # This is the heart of the musical logic of the code. Here I use a naive
    # approach, and simply grab the lowest note on each string that fits the
    # chord.  This function needs to be rewritten to address the extra
    # credit parts of the challenge.
    # The extra parentheses in the function declaration allow us to pass in
    # the results of the parse function directly.
    x = []
    for s in STRINGS:
        x.append(min(strng(s,chordnotes(note,typ))))
    return x

def printchart(x):
    # Do the heavy lifting of formatting the output
    # I calculate the layout of each fret, and print them in turn.
    ch = chord(parse(x))
    print  ' '+''.join([a+ ' ' for a in STRINGS])
    fret = '-'*9
    for f in range(5):
        note = ['|o' if i==f+1 else '| ' for i in ch]
        print fret + '\n' + ''.join(note)+'|'

def main():
    x = raw_input('Chord?')
    printchart(x)

if __name__ == '__main__':
    main()

```

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


# Question
Title: General tips for representing large numbers
Sometimes, while golfing, one needs to represent large number(s) in their code. Writing them as is can significantly increase the byte-count.

What *general*1 tips do you have for representing long numbers concisely in code?

Please post one tip per answer.

---

1With *general*, I mean tips that can be applied to more than a single language. For language-specific tips, post in their respective thread.

# Answer
# Look out for special numbers

Some languages have built-in functions for squares, exponentiation with base 2, *n*-th prime, factorial, or other procedures that can generate large numbers. Check if you number *happens to fall* into any of those categories.

And if it doesn't, it may happen that a *larger* number that does will fit for your purposes and can be used instead.
> 15 votes

# Answer
# Use bitwise boolean operators

Some languages have bitwise AND, OR, XOR, and sometimes NOT.

Expressing a specific large number as a bitwise combination of a result of an exponentiation or left shift and another number can get you to precisely the number you need. This is usually only worth it if the numbers get quite big.

For example, `2147483722` is 10 bytes, but `2<<30^74` (2^31 bitwise-XORed with 74) is only 8.
> 13 votes

# Answer
## Use Scientific Notation

Scientific notation can save bytes in case of long numbers. For Example:

```
3564e-8 // returns 0.00003564 (saves 3 bytes!)

```
> 11 votes

# Answer
## Use Strings for repetitive numbers

For numbers that are very repetitive in nature, you can use Strings and cast them to Integer. For Example, in JavaScript

```
+"1".repeat(100) // returns 100 1s (saves 84 bytes!)

```
> 11 votes

# Answer
## Base Compression

Base decompression code can be fairly complex, but if you have a truly enormous number sometimes it can help to compress it in some base higher than 10.

It also helps that in some languages, the base compression code is very simple. For example, PHP has `base64_decode(_)`, Python has `int(_,36)`, JavaScript has `parseInt(_,36)`, and many golfing languages have base decompression builtins. For example, in CJam:

```
"+ÜTbô±"256b

```

This contains an unprintable. Try it online!

This yields:

```
12345678987654321

```
> 10 votes

# Answer
# Look for another number to use instead

This may sound like a non-answer, but it is not always obvious that a larger number can be calculated by shorter code. An example I remember is Output a googol copies of a string, where the obvious answers require computing 10100. As it turns out, computing any multiple of 10100 leads to an equally correct, but in some languages, shorter answer. Dennis's answer there uses 100100, my own uses 250255.
> 10 votes

# Answer
## Use Bitwise Left Shift for 2's exponentiation

Although, there are many languages that support operator for exponentiation, some do not. And those which don't, usually require calling functions (or Class/Object methods), which can cost a few bytes.

But you can save some bytes when you need to raise 2 to the power *n* by using the Bitwise Left Shift operator `<<` as `1<<n`. Note that this will only save you bytes if *n* is greater than or equal to 17. However, this will *always* save you bytes if *n* is dynamic. Few Examples:

```
1<<2 // returns 4 (3 bytes more :( )
1<<3 // returns 8 (3 bytes more :( )
1<<6 // returns 64 (2 bytes more :( )
1<<14 // returns 16384 (no bytes saved)
1<<17 // returns 131072 (saves 1 byte!)
1<<18 // returns 262114 (saves 1 byte!)

```
> 9 votes

# Answer
## Use exponential fractions for large repetitive numbers

Say you wanted to generate the number made of 100 1's. You could use `int("1"*100)`, `+"1".repeat(100)`, etc. but you can also take advantage of the fact that it's very close to

```
1e100/9

```

This works best for very repetitive numbers, such as those made of a single digit. A couple repeated digits also works fairly well:

```
12e100/99  // Generates 121212121212... (100 digits)

```

Occasionally you'll find some other weird pattern which also can be represented fairly tersely in this method. If you happened to need `int("123456790"*11)`, for example:

```
1e100/81

```

Be careful, though: numbers such as `int("1234567890"*10)` don't have such an easy representation.
> 9 votes

# Answer
# Chinese Remainder Theorem

If arbitrary big integers frequently appear, or big integer representation in target programming language costs too many bytes, you can consider using Chinese Remainder Theorem.

Choose some pairwise relatively prime integers mi \>=2, and you can express a big number from 0 to lcm(m1, m2, ... , mi) -1

For example, I choose 2, 3, 5, 11, 79, 83, 89, 97, then I can express number less than 18680171730 uniquely. 10000000000 (1e10) can be expressed as 0,1,0,1,38,59,50,49 (1e10 mod 2, 3 ... , 97) which need not be expressed as special Big Integer class/struct which might save some bytes in some programming language.

Addition and substraction can be done directly using this representation. Example:

```
(0,1,0,1,38,59,50,49)+(0,2,0,6,23,20,16,53) = 1e10 + 5000
                                            = (0+0 mod 2, 1+2 mod 3, 0+0 mod 5, 1+6 mod 11, 38+23 mod 79, 59+20 mod 83, 50+16 mod 89, 49+53 mod 97)

```
> 8 votes

# Answer
# Use String Padding (where possible)

If a large number includes a repeating digit at the beginning or end, you may be able to save bytes by using your one of your language's padding methods to construct a string of the number you're looking for, which you can then convert to an integer.

---

# Example

To generate the number `1111111111111111111111112` (25 bytes) in JavaScript (ES8):

```
+"2".padStart(25,1) // 19 bytes

```
> 6 votes

# Answer
# Use Exponents

If your language has an exponent operator you might be able to use it to generate, if not the number you want, at least a number you can perform a simple calculation or 2 on to arrive at your number. Even without an operator, you may still be able to save bytes with a built-in function or method.

## Example

The maximum safe integer in JavaScript is `9007199254740991`, which is 16 digits long. In ES7, this can be calculated with the following 7 bytes:

```
2**53-1

```

The equivalent in ES6 and earlier, while the same length as the integer itself in this instance, demonstrates that using a more verbose method might not necessarily cost you any bytes.

```
Math.pow(2,53)-1

```

The above, though, may work out *shorter* if, for example, you already have `Math` aliased to a single character elsewhere in your code.
> 3 votes

# Answer
# Use fractions in the place of float

Example: `1./3` in place of `0.333333333`
> 2 votes

---
Tags: code-golf, number, tips
---


title: What is this date format?

text:
# Question
Title: What is this date format?
For Gregorian calendars, the date format varies from a country to another. There are three main formats recognized:

1. `YY-MM-DD` (big-endian)
2. `DD-MM-YY` (little-endian)
3. `MM-DD-YY` (middle-endian)

Your task is to write a program which, given an input string representing a date, output all the possible date formats by which this string can be interpreted as a date.

**Rules**

* The input date is in the format `xx-xx-xx`, where each field is two digits and zero-padded.
* The date is always valid (so you cannot get things like 14-13-17)
* The date is always at least one of the formats above (so you cannot get things like 17-14-11)
* Because we are in fact in a parallel world, **there are 31 days for every month of the year**, and consequently no leap years
* The date is between January 01, 2001 and December 31, 2099
* If there is only one format for the date, the code must print only it (only trailing newlines are allowed)
* If there are several formats for the date, they must be either separated by a comma, a space, a newline, or a combination of those
* You must output the exact name(s) of the format(s). Using distinct arbitrary values is not allowed.
* No leading or trailing characters others than a trailing space are allowed
* The output must be lowercase
* You are not allowed to use any built-in date or calendar functions
* The output formats do not have to be sorted

**Examples**

```
Input      Output
30-05-17   big-endian, little-endian
05-15-11   middle-endian
99-01-02   big-endian
12-11-31   big-endian, little-endian, middle-endian
02-31-33   middle-endian

```

This is so the shortest code in bytes wins. Explanations are encouraged.

# Answer
> 3 votes
# 05AB1E, 40 bytes

```
'-¡©2£13‹`®Á2£32‹*)˜“Œ±„¥„ê“#Ï’-„–ian’«»

```

Try it online!

**Explanation**

```
'-¡©                                      # split on "-" and store a copy in register
    2£13‹                                 # compare the first 2 elements to 13
         `                                # split as separate to stack
                                          # the bottom element is true if it is middle endian
                                          # the top value is true if it can be big/little
          ®Á                              # retrieve the list from register and rotate right
            2£32‹                         # compare the first 2 elements to 32
                 *                        # multiply with the result of the comparison to 13
                  )˜                      # wrap in a flattened list
                    “Œ±„¥„ê“#             # push the list ['middle', 'big', 'little']
                             Ï            # index into this with the flattened list
                                          # this leaves the types the date could be
                              ’-„–ian’«   # append "-endian" to each
                                       »  # join on newlines

```

# Answer
> 4 votes
# Python 2, 123 bytes

```
a,b,c=map(int,input().split('-'))
for a,b,c in[[b,c,'big'],[b,a,'little'],[a,b,'middle']]:print(c+'-endian')*(a<13)*(b<32),

```

Try it online!

---

## Python 2, less input parsing, 123 bytes

```
d=input()
for a,b,c in[[3,6,'big'],[3,0,'little'],[0,3,'middle']]:print(c+'-endian')*(int(d[a:a+2])<13)*(int(d[b:b+2])<32),

```

Try it online!

# Answer
> 4 votes
## JavaScript (ES6), ~~121~~ ~~119~~ ~~118~~ 112 bytes

Returns a space-delimited string with a trailing space.

```
s=>['big','little','middle'].map((v,i)=>[b<13&c<32,b<13&a<32,a<13][i]?v+'-endian ':'',[a,b,c]=s.split`-`).join``

```

### How?

We split the input into **a**, **b** and **c**. Because the date is guaranteed to be valid, we know for sure that **b** is less than 32. Therefore, it's enough to test whether **a** is less than 13 to validate the middle-endian format. Little-endian and big-endian formats require **b** to be less than 13 and another test on **a** and **c** respectively to validate the day.

Hence the 3 tests:

* Big-endian: **b \< 13 & c \< 32**
* Little-endian: **b \< 13 & a \< 32**
* Middle-endian: **a \< 13**

### Test cases

```
let f =

s=>['big','little','middle'].map((v,i)=>[b<13&c<32,b<13&a<32,a<13][i]?v+'-endian ':'',[a,b,c]=s.split`-`).join``

console.log(f("30-05-17")) // big-endian, little-endian
console.log(f("05-15-11")) // middle-endian
console.log(f("99-01-02")) // big-endian
console.log(f("12-11-31")) // big-endian, little-endian, middle-endian
console.log(f("02-31-33")) // middle-endian
```

# Answer
> 3 votes
# Bash, ~~240~~ ~~125~~ ~~116~~ 112 bytes

```
IFS=- read a b c<<<$1
d=-endian
((b<13))&&(((a<32))&&echo little$d;((c<32))&&echo big$d);((a<13))&&echo middle$d

```

Golfed.

Thanks to manatwork for some tips

Saved 9 bytes removing the verification for less than 32 in the middle-endian follwing Arnauld answer

Saved 4 bytes by using different variables instead of an array

Test it!

# Answer
> 1 votes
# C#, 180 bytes

```
t=(n,m)=>int.Parse(n)<13&int.Parse(m)<32;s=>{var a=s.Split('-');return$"{(t(a[1],a[2])?"big-endian":"")} {(t(a[1],a[0])?"little-endian":"")} {(t(a[0],a[1])?"middle-endian":"")}";};

```

Outputs with only space separated values, can also have leading and trailing spaces. Will update when the OP has clarified on that point if needed.

Full/Formatted version:

```
Func<string, string, bool> t = (n, m) => int.Parse(n) < 13 & int.Parse(m) < 32;

Func<string, string> f = s =>
{
    var a = s.Split('-');

    return $"{(t(a[1], a[2]) ? "big-endian" : "")} {(t(a[1], a[0]) ? "little-endian" : "")} {(t(a[0], a[1]) ? "middle-endian" : "")}";
};

```

# Answer
> 1 votes
# Java 232 bytes

```
(String s)=>{String[]i=s.split("-");String e="-endian",b="big"+e,m="middle"+e,l="little"+e;int p=Integer.valueOf(i[0]);System.out.print(p<13?Integer.valueOf(i[1])<13?Integer.valueOf(i[2])<32?b+","+m+","+l:m+","+l:m:p<32?b+","+l:b);}

```

**Here's a nicer version**

```
String[] i = s.split("-");

String e = "-endian",
       b = "big" + e,
       m = "middle" + e,
       l = "little" + e;

int p = Integer.valueOf(i[0]);

```

I didn't really know how to format this part...

```
System.out.print(
        p < 13 ? Integer.valueOf(I[1]) < 13 ? Integer.valueOf(I[2]) < 32 ? b + "," + m + "," + l
                                                                         : m + "," + l
                                            : m

               : p < 32 ? b + "," + l
                        : b
);

```

# Answer
> 1 votes
# PHP, 151 Bytes

```
[$a,$b,$c]=sscanf($argn,"%d-%d-%d");$z="-endian ";echo($m=$b&&$b<13)&&$c&&$c<32?big.$z:"",$m&&$a&&$a<32?little.$z:"",$a&&$a<13&&$b&&$b<32?middle.$z:"";

```

Testcases

# Answer
> 1 votes
## Batch, 138 bytes

```
@echo off
set/ps=
call:l little %s:-= %
exit/b
:l
call:e big %4 %3
call:e middle %3 %2
:e
if %2 leq 31 if %3 leq 12 echo %1-endian

```

Vaguely based on @ovs's answer.

# Answer
> 1 votes
# PHP, 131 bytes

```
[$a,$b,$c]=explode('-',$argn);foreach([[big,b,c],[little,b,a],[middle,a,b]]as[$t,$x,$y])echo$$x*$$y&&$$x<13&$$y<32?"$t-endian ":"";

```

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


title: Prime of my Life

text:
# Question
Title: Prime of my Life
This year my age is a prime number, and so is this year. This conjunction will repeat in 10 years and again in 12. If I live to 100, I will lived exactly 11 years in which my age and the year are both prime. My condolences to those of you born in odd-numbered years, who will experience this phenomenon at most once if at all.

As it turns out, if I tell you that the consecutive gaps between years in which my age and the year were, are, or will be both primes are 4, 2, 4, 14, 10, 2, 10, 14, 16, and 14, then that is enough information for you to tell me exactly which year I was born.

# The Challenge

This challenge is to write a program or function that, given a list of even numbers, each representing gaps between consecutive prime-age prime-year conjunctions, print or return all years between 1AD and 2100AD inclusive such that a person born in that year (and living no longer than 100 years) would have exactly that sequence of gaps between prime-year prime-age conjuctions (i.e. *no* other such conjunctions)

Or, in more mathematical terms, given a list \\$a\\$, print or return all \\$x\\$ between 1 and 2100 such that there exists a \\$0\<b\le100\\$ such that \\$x+b\\$ is prime, \\$b\\$ is prime, and \\$x+b+\sum^n\_{i=1}a\_i\\$ and \\$b+\sum^n\_{i=1}a\_i\\$ are both prime for all \\$n\\$ up to the length of \\$a\\$ (where the latter sum is guaranteed to be less than 100).

If there are no such years in that range, you may print or return anything falsy or nothing at all.

I/O is flexible: just be able to take a list of numbers as input and produce a list of numbers as output.

# Examples

```
[4,2,4,14,10,2,10,14,16,14]          =>     [1986]
(6,4,2,4)                            =>     ()
6,4,2,4,8,6,10,12,14,10,6            =>     1980
4;4                                  =>     (No output)
[]...................................=>     (A list containing every odd number between 1 and 2099, plus the numbers 1136, 1732, and 1762)

```

# Scoring

Shortest program, in bytes, wins.

Bonus: I will create a bounty to reward the shortest answer that produces the correct output using an algorithm which has an asymptotic worst case running time strictly better than \\$O(YA+A^2)\\$ where Y is the maximum birth year and A is the maximum age. (Y and A are not inputs to your program or function, but pretend they are for the purposes of determining if your algorithm qualifies.) If you wish to compete in the bonus challenge, it is up to you to convince me your program or function meets the requirements. You may assume that all built-ins use the asymptotically fastest known classical algorithm to achieve their results (e.g. generates primes with a Sieve of Atkin rather than a Sieve of Eratosthenes). Yes, it is possible to receive this bounty even if you win the regular challenge.

# Answer
> 4 votes
# 05AB1E, 18 bytes

```
2101GтLDpÏN+DpÏ¥Q–

```

Try it online!

**Explanation**

```
2101G               # for each N in [1 ... 2100]
     тL             # push the range [1 ... 100]
       DpÏ          # keep only numbers that are prime
          N+        # add N to each
            DpÏ     # keep only numbers that are prime
               ¥    # calculate delta's
                Q–  # print N if the resulting list is equal to input

```

# Answer
> 2 votes
# Jelly, 19 bytes

```
97ÆR+⁸ÆPÐfI⁼
⁽¥cçÐf

```

Try it online!

### How it works

```
⁽¥cçÐf        Main link. Argument: A (array of integers)

⁽¥c           Yield 2100.
   çÐf        Apply the helper link to each n in [1, ..., 2100], with right
              argument A. Yield all values of n that return 1.

97ÆR+⁸ÆPÐfI⁼  Helper link. Left argument: n. Right argument: A

97ÆR          Prime range; yield all prime numbers in [1, ..., 97].
    +⁸        Add n to each of these primes.
      ÆPDf    Filter by primality, keeping only prime sums.
          I   Increments; compute all forward differences.
           ⁼  Return 1 if the result and A are equal, 0 if not.

```

# Answer
> 0 votes
# Pyth, 24 bytes

```
fq.+f&P_+TYP_YU100QU2100

```

Try it online!

I feel like this can be golfed down quite a bit, but here it is for now.

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


title: Err, Where am I?

text:
# Question
Title: Err, Where am I?
Oh no! I'm trapped in a big forest (Okay, not really, but just assume it) and I don't know where I am!

Thankfully, I brought my laptop. But when I searched 'Maps', It said 'No results', and I'm asking this as a last resort.

Please make a program which outputs my location's longitude and latitude in any two number format. `any two number format` includes:

* A tuple.
* A string including the longitude and the latitude.
* A JSON Object.
* etc..

Any API or Libraries may be used. That is, You can query Google Maps, etc. (I guess, They didn't trash their APIs :\\)

# Answer
## Mathematica, 4 bytes

> Err, where am I?

```
Here

```

Evaluates to `GeoPosition[{latitude, longitude}]`.
> 74 votes

# Answer
# JavaScript (ES6), ~~89~~ 82 bytes

```
navigator.geolocation.watchPosition(x=>alert([(y=x.coords).latitude,y.longitude]))

```

Try it online! (For some reason, this was not working in the snippet).

## Explanation

`navigator` object is a part of BOM. `geolocation` is a property of its and is also an object, which contains geolocational data of the user. `watchPosition()` is a method of `geolocation` object. It takes in a callback function which is executed after the geolocational data has been retrieved. The callback function `x=>alert((y=x.coords).latitude+","+y.longitude)` is an anonymous (lambda) function that takes in an object `x` and `alert()`s the `latitude` and `longitude` properties of `x.coords` separated by a comma. Note that the object `x` is passed to the callback function by `watchPosition()` when the callback function is called (i.e. after the retrieval of the geolocational data).

---

**Note:** The geolocational data is GPS-based if GPS is available, otherwise it's based on IP.
> 12 votes

# Answer
# PowerShell, 130 Bytes

```
Add-Type -A System.Device;($a=[Device.Location.GeoCoordinateWatcher]::new()).Start();for(;($b=$a|% Po*n|% L*)|% I*){}$b|select L*e

```

Ungolfed:

```
Add-Type -AssemblyName System.Device #Required to access System.Device.Location namespace
$GeoWatcher = New-Object System.Device.Location.GeoCoordinateWatcher #Create the required object
$GeoWatcher.Start() #Begin resolving current locaton
whille ($GeoWatcher.Status -ne "Ready") do { sleep -Milliseconds 100 } #Wait for discovery.
$GeoWatcher.Position.Location | Select Latitude,Longitude #Select the relevent results.

```

Returns as:

```
PS C:\users\sweeneyc\Desktop> Add-Type -A System.Device;($a=[Device.Location.GeoCoordinateWatcher]::new()).Start();for(;($b=$a|% Po*n|% L*)|% I*){}$b|select L*e

        Latitude         Longitude
        --------         ---------
53.4064177191653 -6.36202495701332

```

Turns out there is a way to do this, but it's not so pretty.

bonus: opens google maps on your current location.

```
Add-Type -A System.Device;($a=[Device.Location.GeoCoordinateWatcher]::new()).Start();for(;($b=$a|% Po*n|% L*)|% I*){};saps "https://www.google.ie/maps/@$($b.Latitude),$($b.Longitude)z"

```

could save 3 bytes using `TryStart` but it outputs a `true` to the pipeline and costs more to suppress that.

```
Add-Type -A System.Device;($a=[Device.Location.GeoCoordinateWatcher]::new()).TryStart($true,[int]9e8);$a|% Po*n|% L*|select L*e

```

---

# PowerShell (non-competing), 44 Bytes

```
(irm freegeoip.net/xml).Response|select *ude

```

Uses an external service since PowerShell has no internal builtins for 'current location' - this is IP-based Geolocation, so almost definitely won't return your actual location, it will return a 'default' location for your ISP, and if you run this over a VPN will present wherever the exit point is.

I've tried (not as a golf exercise) to get google maps API to work with the wireless-mac-address geolocation method, but it's far from accurate or golfable.

marked as non-competing due to the inaccuracy of the results.

```
PS C:\Users\sweeneyc> (irm freegeoip.net/xml).Response|select *ude
Latitude Longitude
-------- ---------
53.3472  -6.2439

```

this displays `Central Dublin, Ireland` when searched up, however i'm a bit outside the city center currently, about 8 miles from the returned point.
> 8 votes

# Answer
# Python with requests, ~~101~~ ~~100~~ 75 bytes

*4 bytes saved thanks to @КириллМалышев*

*21 bytes saved thanks to @Rod*

```
from requests import*;print(get('http://su0.ru/auls').text.split(',')[5:7])

```
> 8 votes

# Answer
# Angolf, 110 107 bytes

```
❦™navigator.geolocation.getCurrentPosition#x=>™alert##y=x.coords▷.latitude+","+y.longitude▷▷●
    ❦                                   Define an IIFE
       ™                                Get the scope
         navigator                      Get JavaScript's navigator object from the scope
             geolocation                Get the geolocation property of the navigator object
                 getCurrentPosition     Get the current position and execute a function
                     x=>                Define a function with x as a parameter
                         ™              Get the scope
                            alert       Call alert and alert the following string:
                         #y=x.coords▷ Define y with the value of the coordinates of x
                         latitude       Get y's latitude
                         +","           Append "," to the string
                         +y.longitude   Append the longitude to the string
    ●                                   Close the IIFE and call it with the scope

```
> 2 votes

# Answer
# C#, 132 bytes

```
_=>{var w=new System.Device.Location.GeoCoordinateWatcher();w.Start();var c=w.Position.Location;return c.Longitude+","+c.Latitude;};

```
> 0 votes

# Answer
# Swift 4, ~~125 117~~ 96 bytes

This can only be tested locally, unfortunately.

```
import CoreLocation;var c=CLLocationManager().location!.coordinate;print(c.longitude,c.latitude)

```
> 0 votes

# Answer
# Excel VBA (Windows, Office 2016+ Only), ~~278~~ 272 Bytes

> Restricted to Windows, Office 2016+ for the use of the `Microsoft.Mashup.OleDb.1` provider

Full `sub`routine that takes no input and outputs your current location as a `Excel.ListObject` typed table, including extra information.

```
Sub a
ThisWorkbook.Queries.Add"x","let S=Json.Document(Web.Contents(""su0.ru/auls""))in S
With Sheet1.ListObjects.Add(0,"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=x",,,[A1]).QueryTable
.CommandText="SELECT * FROM [x]
.Refresh
End With
End Sub

```

Example output excluded for obvious reasons.

-2 Bytes for use of `[Sheet1]` over  `Sheets(1)`
> 0 votes

---
Tags: code-golf
---


title: Adding, the old-fashioned way

text:
# Question
Title: Adding, the old-fashioned way
**Overview**
The ancient Romans devised a number system using Latin letters, which served them well, and which is still used by modern civilization, though to a much smaller degree. In the time of its use, Romans would have had to learn to use and manipulate these numbers in order to be of much use for many applications. For example, if a man owned 35 oxen, and he procured 27 more, how would he know the new total other than counting them all? (*Ok, that and using an abacus...*) If the Romans could do it, surely we can figure it out as well.

**Objective**
Write the shortest algorithm/function/program that will **add** two Roman numerals together and output the result **without** converting the string representation of either input into a number.

**Rules/Constraints**
Because of historical/pre-medieval inconsistencies in formatting, I'm going to outline some non-standard (per modern usage) rules for orthography. See the value guide below as an example.

* The letters I, X, C, and M can be repeated up to four times in succession, but no more. D, L, and V can never be repeated.
* The letter immediately to the right of another letter in the Roman representation will be of the same or lesser value than that to its left.
    + In other words, `VIIII == 9` but `IX != 9` and is invalid/not allowed.
* All input values will be 2,000 (MM) or less; no representation for numbers greater than M is necessary.
* All input values will be a valid Roman numeral, pursuant to the rules above.
* You may not convert any numbers to decimal, binary, or any other number system as part of your solution (you are welcome to use such a method to *VERIFY* your results).
* This is code golf, so shortest code wins.

**Value Guide**

```
Symbol        Value
I             1
II            2
III           3
IIII          4
V             5
VIIII         9
X             10
XIIII         14
XXXXIIII      44
L             50
LXXXXVIIII    99
C             100
D             500
M             1,000

```

**Examples**

```
XII + VIII = XX (12 + 8 = 20)
MCCXXII + MCCXXII = MMCCCCXXXXIIII (1,222 + 1,222 = 2,444)
XXIIII + XXXXII = LXVI (24 + 42 = 66)

```

If any further clarification is needed, please ask.

# Answer
## APL (~~59~~ 56)

```
,/N⍴⍨¨{∨/K←⍵≥D←7⍴5 2:∇⍵+(1⌽K)-K×D⋄⍵}⊃+/(N←'MDCLXVI')∘=¨⍞

```

Input on one line (i.e. `XII + XII`, though the `+` is not necessary).

Edit: changed shift to rotate to save three characters - it only matters when the answer ≥ 5000, which should never happen as the question says the input values will always be ≤ 2000. The only effect is it now "overflows" at 5000, giving 5000=1, 5001=2, etc.

(I don't really think the Romans did it this way... APL is more something for Ancient Egyptians I think :) )

Explanation:

* : get user input
* `(N←'MDCLXVI')∘=¨`: store 'MDCLXVI' in N. Return, for each character of the input string, a vector with a 1 in the place where the character corresponds to one of 'MDCLXVI', and 0 otherwise.
* `⊃+/`: Sum the vectors and de-encapsulate. We now have a vector with information about how many of each Roman numeral we have. I.e, if the input was `XXII XIIII`, we now have:

```
     M D C L X V I
     0 0 0 0 3 0 6

```
* Note that this is not converting the values.
* `{`...`:`......`}` is a function with an if-else construct.
* `D←7⍴5 2`: `D` is the vector `5 2 5 2 5 2 5`. This is how many of a Roman numeral are *not* allowed. I.e. if you have 5 `I`s, that's too many, and if you have 2 `V`s that's also too many. This vector also happens to be the multiplication factor for each Roman numeral, i.e. a `V` is worth 5 `I`s and an `X` is worth 2 `V`s.
* `∨/K←⍵≥D`: `K` is the vector where there's a 1 if we have too many Roman numerals of a certain kind. `∨/` ORs this vector together.
* If this vector is not all zeroes:
* `K×D`: Multiply K by D. This vector has zeroes where we don't have too many Roman numerals, and the amount of Roman numerals where we do.
* `⍵+(1⌽K)`: Rotate K to the left by 1, and add it to the input. For each Roman numeral we have too many, this will add one of the next-higher one.
* `⍵+(1⌽K)-K×D`: Subtract this from the other vector. The effect is, for example if you have 6 `I`s, it will add one `V` and remove 4 `I`s.
* : Recurse.
* `⋄⍵`: But if `K` was all zeroes, then ⍵ represents a valid Roman numeral, so return ⍵.
* `N⍴⍨¨`: For each element of the resulting vector, create that many of the corresponding Roman numeral.
* `,/`: Join these vectors together to get rid of the ugly spaces in the output.
> 5 votes

# Answer
## Python, 100

```
s="IVXLCDM"
r=raw_input()
a=""
i=2
u=0
for c in s:r+=u/i*c;i=7-i;u=r.count(c);a+=u%i*c
print a[::-1]

```

Takes one string from input (e.g. `VIII + XII` or `VIII + XII =`).
> 5 votes

# Answer
### Ruby, 85 82 characters

```
gets;r=0;v=5;puts"IVXLCDM".gsub(/./){|g|r+=$_.count g;t=r%v;r/=v;v^=7;g*t}.reverse

```

This version takes input on STDIN as a single string (e.g. `XXIIII + XXXXII`) and prints output to STDOUT.

```
f=->*a{r=0;v=5;"IVXLCDM".gsub(/./){|g|r+=(a*'').count g;t=r%v;r/=v;v^=7;g*t}.reverse}

```

The second one is an implementation as a function. Takes two (or more) strings and returns the summed values. Usage:

```
puts f["XXIIII", "XXXXII"]     # -> LXVI

```
> 3 votes

# Answer
## Perl, 132 chars

```
sub s{@a=VXLCDM=~/./g;@z=(IIIII,VV,XXXXX,LL,CCCCC,DD);$r=join"",@_;
$r=~s/$a[-$_]/$z[-$_]/gfor-5..0;$r=~s/$z[$_]/$a[$_]/gfor 0..5;$r}

```

Declares function `s` which takes any number of arguments and sums them. Pretty straightforward: it appends the input, reduces everything to `I`s and then immediately restores the Roman numerals. (Hopefully this doesn't count as using the unary number system!)
> 3 votes

# Answer
## GNU Sed, 131 chars

```
:;s/M/DD/;s/D/CCCCC/;s/C/LL/;s/L/XXXXX/;s/X/VV/;s/V/IIIII/;t;s/\W//g;:b;s/IIIII/V/;s/VV/X/;s/XXXXX/L/;s/LL/C/;s/CCCCC/D/;s/DD/M/;tb

```
> 3 votes

# Answer
## Python, 174 chars

A very simple algorithm - count each digit, loop to handle overflow to the next, print.
Reads from standard input. Something like `XVI + CXX` would work (ignores anything except numerals, so the `+` isn't really needed).

```
x="IVXLCDM"
i=raw_input()
d=dict((c,i.count(c))for c in x)
for c in x:
    n=2+3*(c in x[::2])
    if d[c]>=n:d[c]-=n;d[x[x.find(c)+1]]+=1
print"".join(c*d[c]for c in reversed(x))

```
> 1 votes

# Answer
### Scala 150

```
val c="IVXLCDM"
def a(t:String,u:String)=((t+u).sortBy(7-c.indexOf(_))/:c.init)((s,z)=>{val i=c.indexOf(z)+1
s.replaceAll((""+z)*(2+i%2*3),""+c(i))})

```

invocation:

```
a("MDCCCCLXXXXVIIII", "MDCCCCLXXXXVIIII")

```

ungolfed Version:

```
val c = "IVXLCDM"
def add (t:String, u:String) = (
  (t+u).  // "MDCCCCLXXXXVIIIIMDCCCCLXXXXVIIII"
  sortBy(7-c.indexOf(_)) // MMDDCCCCCCCCLLXXXXXXXXVVIIIIIIII
  /: // left-fold operator to be used: (start /: rest) ((a,b)=> f (a,b))
  c.init) /* init is everything except the rest, so c.init = "IVXLCD"
    (because M has no follower to be replaced with */
  ((s, z) => { /* the left fold produces 2 elements in each step,
    and the result is repeatedly s, on initialisation
    MMDDCCCCCCCCLLXXXXXXXXVVIIIIIIII
    and z is the iterated element from c.init, namely I, V, X, L, C, D
    in sequence */
    val i = c.indexOf (z) + 1 // 1, 2, ..., 7
    /* i % 2 produces 1 0 1 0 1 0
       *3 => 3 0 3 0
       +2 => 5 2 5 2
       (""+ 'I') * 5 is "IIIII", ("" + 'V') * 2 is "VV", ...
       ""+c(i) is "V", "X", ...
    */
    s.replaceAll (("" + z) * (2+i%2*3), "" + c (i))
    }
  )

```
> 1 votes

# Answer
# VBA, 187 chars

```
Function c(f,s)
a=Split("I,V,X,L,C,D,M",",")
z=f & s
For i=0 To 6
x=Replace(z,a(i),"")
n=Len(z)-Len(x)+m
r=IIf(i Mod 2,2,5)
o=n Mod r
m=Int(n/r)
c=String(o,a(i)) & c
z=x
Next
End Function

```
> 1 votes

# Answer
# JavaScript 195 179

My system is fairly rudimentary, reduce all Roman numerals to a series of `I` for both numbers, join them up and then reverse the process turning certain blocks of `I` into their respective larger versions...

Iteration 1  `a="IIIII0VV0XXXXX0LL0CCCCC0DD0M".split(0);d=b=>x.replace(g=RegExp((c=z)>b?a[c][0]:a[c],"g"),c>b?a[b]:a[b][0]);x=prompt().replace("+","");for(z=6;0<z;z--)x=d(z-1);for(z=0;6>z;z++)x=d(z+1);alert(x)`

Iteration 2 `a="IIIII0VV0XXXXX0LL0CCCCC0DD0M".split(0);x=prompt().replace("+","");for(z=-6;6>z;z++)b=0>z?-z:z,c=0>z?~z:z+1,x=x.replace(g=RegExp(b>c?a[b][0]:a[b],"g"),b>c?a[c]:a[c][0]);alert(x)`

Features:

* Zero delimited array string, quicker than setting up a string array.
* Reduced the two recursions to the one, and recalculating the parameters for the specific regex.
* More ternary operators than you can poke a stick at!

Input is entered via prompt in the form of `<first roman number>+<second roman number>` (no spaces), output in the form of an alert.

e.g.

```
XVI+VII // alert shows XXIII, correct!
MCCXXXIIII+DCCLXVI // alert shows MM, also correct!

```
> 1 votes

# Answer
# JavaScript, 190

```
x=prompt(r=[]);p=RegExp;s="MDCLXVI";for(i=-1;++i<7;){u=x.match(new p(s[i],'g'));if(u)r=r.concat(u)};for(r=r.join("");--i>0;){r=r.replace(new p(s[i]+'{'+(i%2==0?5:2)+'}','g'),s[i-1])}alert(r)

```

Putting some instruction inside the third slot of the `for` operator let me save some semicolons!

When the input prompts, you insert the two numbers (the `+` and spaces are not necessary, but if you put them you don't get an error). Then the alert show you the sum.
> 1 votes

# Answer
## C++, 319 chars

```
#define A for(j=0;j<
#define B .length();j++){
#define C [j]==a[i]?1:0);}
#include <iostream>
int main(){std::string x,y,s,a="IVXLCDM";int i,j,k,l,m=0,n;std::cin>>x>>y;for(i=0;i<7;i++){k=0;l=0;A x B k+=(x C A y B l+=(y C n=k+l+m;m=(n)%(i%2?2:5);for(j=0;j<m;j++){s=a[i]+s;}m=(n)/(i%2?2:5);}std::cout<<s<<"\n";return 0;}

```
> 0 votes

# Answer
# PHP, 136 Bytes

```
for($r=join($argv);$c=($n=IVXLCDM)[$i];$r.=$p($n[++$i],$z/$d))$t=($p=str_repeat)($c,($z=substr_count($r,$c))%($d="52"[$i&1])).$t;echo$t;

```

Try it online!
> 0 votes

---
Tags: code-golf, math, roman-numerals
---


title: Find the rectangle

text:
# Question
Title: Find the rectangle
## Overview

Given a 2 dimensional array of values with a filled in rectangle, find the position and size of the rectangle. Do it in the fewest array accesses as possible.

## Requirements

* The `x` and `y` values in the output must be 0-indexed. The top left corner is `(0, 0)`.
* The output should be the 4-tuple `(x, y, width, height)`.
* This is a challenge, so do it in as few array accesses as possible. An "array access" is the use of `abc[x][y]`, `.indexOf`, or `.contains`. Getting the bounds of the array is free.
* You may not copy the array to another format.
* You may not store any information about the inputs into your program ahead of time. That's cheating. It should be completely general. The inputs are fixed so everyone is on an equal playing field, and so your program isn't given a bad score from simple bad luck.
* While not strictly a requirement, to keep track of "array accesses", you can have a counter that is incremented after every access.

## Example Inputs and Outputs

Given the following 2D array

```
((0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 1, 1, 1, 1, 1, 0, 0),
 (0, 0, 0, 1, 1, 1, 1, 1, 0, 0),
 (0, 0, 0, 1, 1, 1, 1, 1, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0))

```

Your program should return `(3, 2, 5, 3)`, specifying that the rectangle starts at x=3 and y=2 and is 5 units wide and 3 units tall.

Input:

```
((1, 1, 1, 0, 0, 0, 0, 0, 0, 0),
 (1, 1, 1, 0, 0, 0, 0, 0, 0, 0),
 (1, 1, 1, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0))

```

Output: `(0, 0, 3, 3)`

Input:

```
((0, 0, 0, 0, 0, 1, 1, 1, 1),
 (0, 0, 0, 0, 0, 1, 1, 1, 1),
 (0, 0, 0, 0, 0, 1, 1, 1, 1),
 (0, 0, 0, 0, 0, 1, 1, 1, 1),
 (0, 0, 0, 0, 0, 1, 1, 1, 1))

```

Output: `(5, 0, 4, 5)`

Input:

```
((0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 1, 1, 0, 0),
 (0, 0, 0, 0, 0, 0, 1, 1, 0, 0),
 (0, 0, 0, 0, 0, 0, 1, 1, 0, 0),
 (0, 0, 0, 0, 0, 0, 1, 1, 0, 0))

```

Output: `(6, 2, 2, 4)`

Input:

```
((0, 0, 0, 0, 0, 0),
 (0, 1, 1, 1, 1, 0),
 (0, 1, 1, 1, 1, 0),
 (0, 1, 1, 1, 1, 0),
 (0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0))

```

Output: `(1, 1, 4, 3)`

Input:

```
((0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 1, 0, 0, 0, 0))

```

Output: `(3, 7, 1, 1)`

## Scoring

Your program's score is determined by the sum of the number of array accesses it takes to solve all 6 of those examples. For example, if it takes 20 accesses to solve the first 5, and 15 for the last, your program's score will be 115. Lower score is better.

# Answer
# JavaScript, 40 operations

```
function findRect(arr) {
  var found = false;
  var c = 0;
  for (i = 0; i < arr.length; i++) {
    if (!found) {
      first = arr[i].indexOf(1);
      c++;
      if (~first) {
        found = true;
        x = first;
        y = i;
      }
    }
    if (found) {
      last = arr[i].lastIndexOf(1);
      c++;
      if (~last) {
        width = last - x + 1;
        height = i - y + 1;
      } else {
        console.log(c);
        return [x,y,width,height];
      }
    }
  }
  console.log(c);
  return [x,y,width,height];
}

```

```
var globalC = 0;

function findRect(arr) {
  var found = false;
  var c = 0;
  for (i = 0; i < arr.length; i++) {
    if (!found) {
      first = arr[i].indexOf(1);
      c++;
      if (~first) {
       found = true;
        x = first;
        y = i;
      }
    }
    if (found) {
      last = arr[i].lastIndexOf(1);
      c++;
      if (~last) {
       width = last - x + 1;
        height = i - y + 1;
      } else {
       console.log(c);
        globalC += c;
        return [x,y,width,height];
      }
    }
  }
  console.log(c);
  globalC += c;
  return [x,y,width,height];
}

console.log(findRect([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 1, 1, 1, 1, 1, 0, 0],
 [0, 0, 0, 1, 1, 1, 1, 1, 0, 0],
 [0, 0, 0, 1, 1, 1, 1, 1, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]));

 console.log(findRect([[1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
 [1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
 [1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]));

 console.log(findRect([[0, 0, 0, 0, 0, 1, 1, 1, 1],
 [0, 0, 0, 0, 0, 1, 1, 1, 1],
 [0, 0, 0, 0, 0, 1, 1, 1, 1],
 [0, 0, 0, 0, 0, 1, 1, 1, 1],
 [0, 0, 0, 0, 0, 1, 1, 1, 1]]));

 console.log(findRect([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
 [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
 [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
 [0, 0, 0, 0, 0, 0, 1, 1, 0, 0]]));

 console.log(findRect([[0, 0, 0, 0, 0, 0],
 [0, 1, 1, 1, 1, 0],
 [0, 1, 1, 1, 1, 0],
 [0, 1, 1, 1, 1, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0]]));

 console.log(findRect([[0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 1, 0, 0, 0, 0]]));

 console.log(globalC);
```
> 2 votes

# Answer
## PowerShell, ~~34~~ 50 Operations

I was doing some string manipulation earlier. I removed any string manipulation, as it was clarified as forbidden, at the cost of some extra operations.

```
function Get-SquareCoordinates{
    param(
        [array]$array
    )

    $count = 0             # Record the count
    $flag = $false         # Loop exit flag
    $rowIndex = -1         # Row location in array

    # Find the top left corner
    do{

        $rowIndex++
        # Check if this row contains 1
        $result = $array[$rowIndex].IndexOf(1)

        # If there is no 1 then -1 would be in $result
        if($result -ge 0){$x,$y=$result,$rowIndex;$flag=$true}

        # Increase the counter
        $count++
    } while(!$flag)

    # Start from the back of the array and find the last index of 1
    $w,$h = 0,0              # To store the width and height of the rectangle
    $flag = $false         # Loop exit flag
    $rowIndex = $array.Count          # Row location in array

    # Find the bottom right corner
    # Start checking the rows backwards
    do{
        $rowIndex--
        # Check if this row contains 1 and add the count of all the ones to the index of the first one found
        $result = $array[$rowIndex].IndexOf(1) + ($array[$rowIndex]-match1).Count - 1

        # If there is no 1 then -1 would be in $result
        if($result -ge 0){
            $w,$h= ($result-$x+1),($rowIndex-$y+1)
            $flag=$true
        }

        # Increase the counter by 2. First to find the one and the second to count the 1's on the line
        $count=$count+2
    } while(!$flag)

    Write-Host "Determined using $count array operations" -ForegroundColor Green
    $x,$y,$w,$h
}

```

Using the inputs exactly as in the questions, where each is saved as a variable it would net me the answers as an array of integers and spit out a console line containing the amount of operations it took to find the dimensions.

```
$array1, $array2, $array3,$array4,$array5,$array6 | ForEach-Object{
    (Get-SquareCoordinates $_) -join ", "
}

Determined using 9 array operations
3, 2, 5, 3
Determined using 11 array operations
0, 0, 3, 3
Determined using 3 array operations
5, 0, 4, 5
Determined using 5 array operations
6, 2, 2, 4
Determined using 12 array operations
1, 1, 4, 3
Determined using 10 array operations
3, 7, 1, 1

```
> 1 votes

---
Tags: fastest-algorithm
---


title: Separate the psychopaths!

text:
# Question
Title: Separate the psychopaths!
Dr. Trump is the head psychiatrist at a mental hospital, which is populated by murdering psychopaths. If 2 psychopaths are left together, they will end up brutally injuring or even killing each other, so Dr. Trump needs to build walls to separate these psychopaths, but owing to the limited amount of funds he has left, he has to minimise the number of walls he builds. Walls of a room can either be horizontal or vertical in nature and of any length.

Help Dr. Trump minimise the number of walls he builds to separate all the psychopaths in a 2\*n psych ward.

Also, do keep in mind that the shortest code wins.

## Input

The first 2 lines contains the position of psychopaths (denoted by '#') and empty spaces (denoted by '-').

## Output

An integer which is equal to the minimum number of walls to build to separate all the psychopaths from each other.

## Input Constraints

1 \<= n \<= 1000000

# Sample Test Cases

## Test Case 1

Sample Input

```
##########
##########

```

Sample Output

```
10

```

## Test Case 2

Sample Input

```
#-#-#
-#-#-

```

Sample Output

```
3

```

## Test Case 3

Sample Input

```
#-----
------

```

Sample Output

```
0

```

# Answer
## Python, 270 228 166 156 bytes

```
a=input();b=input();m=lambda s:[c=="#"for c in s];f=m(a);g=m(b);s=p=0
for i in range(len(a)):q=2*f[i]+g[i];r=p&q;s+=r!=0;p=r or p|q
print(s+(any(f)&any(g)))

```

PEP8-ified:

```
a = input()
b = input()
m = lambda s: [c == "#"for c in s]
f = m(a)
g = m(b)
s = p = 0
for i in range(len(a)):
    q = 2*f[i]+g[i]
    r = p & q
    s += r != 0
    p = r or p | q
print(s+(any(f) & any(g)))

```

Try it online!

This is my first time here, be gentle please ;)

There is always a horizontal wall in the middle, except when prisoners are only on one side -- the addition in `print()` takes this into account. Strategy here is to break horizontal bar into sections such that there is no more than one prisoner on each side, for each section.

The `for` loop uses an int, p, to hold two bit flags, indicating whether the current top/bottom section already contains a psychopath. We `&` this with the flags from the new gridsquare to check whether we are going to overflow, and need to place a wall; if so, we increment s. We also use `p&q` to decide how to update the state: if we overflow, we hold onto just the overflowed prisoner (`p&q`). Otherwise, we `|` the new prisoners onto our current prisoner state. Using `and` and `or` as a ternary operator again here.

There are some helper functions at the top, as well as throwaway variable names for values used more than once.

Edit: It seems like this got simpler as it got shorter. It used to use all kinds of wacky behaviour
> 6 votes

---
Tags: code-golf
---


title: The most unreliable gun ever

text:
# Question
Title: The most unreliable gun ever
You are given a very special gun with a full magazine.

Let `n` be the initial number of bullets in the magazine and `i` the number of bullets left.

That gun is really unreliable, hence each time you shoot, you have a `i/n` chance to successfully shoot. The fewer bullets you have left, the more tries it requires to shoot.

The goal is to find the average number of attempts to shoot before running out of ammo.

### Example

You start with 3 bullets (`n=3`). Your first shot is always successful. You have now 2 bullets left. You will shoot first with a probability of `2/3` and misfire with `1/3`. The probability of emptying your magazine in just 3 tries (no misfires) is `(3/3) * (2/3) * (1/3)`.

The average number of tries before emptying your magazine for this example is `5.5`.

### Test Cases

```
f(2) = 3.000
f(3) = 5.500
f(4) = 8.330
f(10) ~= 29.290

```

# Answer
# 05AB1E, 3 bytes

```
L/O

```

Try it online! or as a Test suite

**Explanation**

```
L     # range [1 ... n]
 /    # divide n by each in above list
  O   # sum

```
> 5 votes

# Answer
# Haskell, ~~22~~ 21 bytes

```
f n=sum$(n/)<$>[1..n]

```

**Try it online (TIO)!**

---

Previous, more self-explanatory version:

```
f n=sum[n/i|i<-[1..n]]

```
> 1 votes

# Answer
# Japt, ~~6~~ 4+1= 5 bytes

Inspired by Emigna's 05AB1E solution.

+1 byte for the `-x` flag.

```
õ@/X

```

Try it online
> 1 votes

# Answer
# Ohm, 4 bytes

```
D@/Σ

```

Try it online!

Inspired by Emigna's answer
> 1 votes

# Answer
# Aceto, ~~41~~ 34 bytes

Based on Emigna's insight

Could almost definitely be golfed more.

```
  9jpX
 {:s_=1(
 &_L+&l@
iM!l
rLz@

```

### Rough explanation

Part 1: Making a range and dividing by each of the numbers:

```
 {:s
 &_L
iM!l
rLz@

```

Part 2: Summing them up

```
    _=1(
    +&l@

```

Part 3: Printing, exiting, and making sure we don't visit this earlier

```
  9jpX

```
> 0 votes

# Answer
# PHP, 37 Bytes

```
for(;$i++<$argn;)$s+=$argn/$i;echo$s;

```

Try it online!
> 0 votes

# Answer
# JavaScript (ES6), ~~44~~ ~~34~~ ~~27~~ 26 bytes

Also inspired by Emigna's 05AB1E solution.

```
f=(n,i=n)=>i&&n/i+f(n,--i)

```

<sub>(Look at me , going for recursion over array mapping for once!)</sub>

---

## Try it

```
f=(n,i=n)=>i&&n/i+f(n,--i)
oninput=_=>o.innerText=f(+i.value)
o.innerText=f(i.value=1)
```

```
<input id=i type=number><pre id=o>
```
> 0 votes

# Answer
# CJam, 11 bytes

```
rid_,:)f/:+

```

Try it online!

Inspired by Emigna's answer
> 0 votes

# Answer
# jq, 30 characters

```
. as$n|[range(1;.+1)|$n/.]|add

```

Sample run:

```
bash-4.4$ jq '. as$n|[range(1;.+1)|$n/.]|add' <<< 10
29.289682539682538

```

Try in jq‣play
> 0 votes

---
Tags: code-golf, probability-theory
---


title: Is it Covfefey?

text:
# Question
Title: Is it Covfefey?
Based on this challenge, you must determine if a string is covfefey, that is, could it have been produced as output from a covfefifier?

The string will be composed of only alphabet chars (`^[a-z]\*$`, `^[A-Z]\*$` are possible schemes for input. change the regexs appropriately if using caps)

To do this, there are a few checks you must do:

Do the last four characters follow this scheme:

```
([^aeiouy][aeiouy])\1

```

example:

```
fefe

```

follows this scheme.

is this consonant at the start of the ending the voiced or voiceless version of a consonant immediately before it?

consonant pairings follow this key. find the consonant occuring before the end part consonant we had, and check whether the end part consonant is there

```
b: p
c: g
d: t
f: v
g: k
h: h
j: j
k: g
l: l
m: m
n: n
p: b
q: q
r: r
s: z
t: d
v: f
w: w
x: x
z: s

```

does the first part of the word, the part that does not include the `([^aeiouy][aeiouy])\1`, follow this regex:

```
[^aeiouy]*[aeiouy]+[^aeiouy]

```

That is, does it contain one group of vowels, and exactly one consonant after that vowel?

If it fulfills all these criteria, it is covfefey.

Output a truthy value if covfefey, otherwise falsy

Test cases

```
covfefe -> truthy
barber  -> falsy
covefefe -> falsy
pressisi -> falsy
preszizi -> truthy
prezsisi -> truthy
president covfefe -> You don't need to handle this input as it contains a space.
cofvyvy -> truthy
businnene -> falsy (the first part does not follow the regex)

```

# Answer
# Jelly, 56 bytes

```
5ịØYiị“ßȷ%Hẹrȧq’œ?ØY¤⁾cgy
Ṛµ4,2ị=ÇȦ
Çȧe€ØyµḄ%⁴⁼5ȧŒgLe5,6

```

A monadic link taking a list of lowercase characters and returning `1` for truthy and `0` for falsey.

**Try it online!** or see the test suite.

### How?

```
5ịØYiị“ßȷ%Hẹrȧq’œ?ØY¤⁾cgy - Link 1, convert 5th character: list of characters, r
5ị                        - index into r at 5
  ØYi                     - first index of that in "BCDF...XZbcdfghjklmnpqrstvwxz"
                    ¤     - nilad followed by link(s) as a nilad:
      “ßȷ%Hẹrȧq’          -   base 250 number = 1349402632272870364
                  ØY      -   yield consonants-y = "BCDF...XZbcdfghjklmnpqrstvwxz"
                œ?        -   nth permutation    = "BCDF...XZpctvkhjglmnbqrzdfwxs"
     ị                    - index into that (converts a 'b' to a 'p' etc..)
                     ⁾cg  - literal ['c','g']
                        y - translate (convert a 'c' to a 'g' - a special case)

Ṛµ4,2ị=ÇȦ - Link 2, check the 3 consonants at the end: list of characters, w
Ṛ         - reverse w
 µ        - monadic chain separation, call that r
  4,2     - 4 paired with 2 = [4,2]
     ị    - index into r
       Ç  - call the last link (1) as a monad (get 5th char converted)
      =   - equal? (vectorises)
        Ȧ - any and all (0 if empty or contains a falsey value, else 1)

Çȧe€ØyµḄ%⁴⁼5ȧŒgLe5,6 - Main link: list of characters, w
Ç                    - call last link as a monad (1 if the 3 consonants are good; else 0)
    Øy               - vowel+y yield = "AEIOUYaeiouy"
  e€                 - exists in? for €ach c in r
 ȧ                   - logical and (list of isVowels; or 0 if link 2 returned 0)
      µ              - monadic chain separation, call that v
       Ḅ             - convert from binary (0 yields 0)
         ⁴           - literal 16
        %            - modulo (0 yields 0)
          ⁼5         - equals 5? (1 if ending is consonant,vowel,consonant,vowel; else 0)
             Œg      - group runs of v (e.g. [0,0,0,1,1,0,1,0,1]->[[0,0,0],[1,1],[0],[1],[0],[1]])
            ȧ        - logical and (the grouped runs if AOK so far, else 0)
               L     - length (number of runs)
                 5,6 - 5 paired with 6 = [5,6]
                e    - exists in (the number of runs must be 5 or 6 to comply)

```
> 5 votes

# Answer
## JavaScript (ES6), ~~109~~ 108 bytes

Returns `true` for covfefey / `null` or `false` otherwise.

```
s=>(m=s.match`^[^aeiouy]*[aeiouy]+(.)((.)[aeiouy])\\2$`)&&((a="bcdfgszkvtgp")[11-a.search(b=m[1])]||b)==m[3]

```

### Test cases

```
let f =

s=>(m=s.match`^[^aeiouy]*[aeiouy]+(.)((.)[aeiouy])\\2$`)&&((a="bcdfgszkvtgp")[11-a.search(b=m[1])]||b)==m[3]

;[
  "covfefe",
  "barber",
  "covefefe",
  "pressisi",
  "preszizi",
  "prezsisi",
  "cofvyvy",
  "exxaxa"
]
.map(s => console.log(s, '-->', f(s)))
```
> 5 votes

# Answer
# Java 8, ~~211~~ ~~210~~ ~~166~~ ~~163~~ ~~161~~ 156 bytes

```
s->{int l=s.length()-5;return"bpbdtdfvfgkgszshhjjllmmnnqqrrwwxxcg".contains(s.substring(l,l+2))&s.matches("[^x]*[x]+(.)((.)[x])\\2".replace("x","aeiouy"));}

```

-2 bytes by replacing the regex `[^x]*[x]+[^x]([^x][x])\\1` with `[^x]*[x]+(.)((.)[x])\\2` thanks to *@Arnauld*'s JavaScript answer.

**Explanation:**

Try it here.

```
s->{                   // Method with String parameter and boolean return-type
  int l=s.length()-5;  //  Temp integer value with the length of the input-String - 5
  return"bpbdtdfvfgkgszshhjjllmmnnqqrrwwxxcg".contains(s.substring(l,l+2))
                       //   Return if the correct pair is present at the correct location
                       //    (i.e. `vf` at index l-5 + l-6 in the String `convfefe`
   &s.matches("[^x]*[x]+(.)((.)[x])\\2".replace("x","aeiouy"));
                       //    and if the String matches the regex-pattern
}                      // End of method

```
> 5 votes

# Answer
## Perl, 80 bytes

```
$_=/[aeiouy]+(*COMMIT)(.)((.)[aeiouy])\2$/&&$3eq$1=~y/bcdfgkpstvz/pgtvkgbzdfs/r

```

Run with `perl -pe`.

Due to their length, it’s not often that I get to use the exotic regex verbs in golf, but this challenge is a perfect fit!

Whenever the engine backtracks to `(*COMMIT)`, the entire match fails. This guarantees that the part that comes before it, `[aeiouy]+`, can only ever match the first thing it tries to match, namely the first continuous stretch of vowels. Thus, `[aeiouy]+(*COMMIT)(.)` is equivalent to `^[^aeiouy]*[aeiouy]+([^aeiouy])` (equivalent in terms of which strings match, but matches are on different positions).
> 4 votes

# Answer
# PHP , 121 Bytes

```
$v=aeiouy;echo preg_match("#^[^$v]*[$v]+([^$v])(([^$v])[$v])\\2$#",$argn,$t)&$t[3]==strtr($t[1],bcdfgkpstvz,pgtvkgbzdfs);

```

Try it online!
> 4 votes

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


# Question
Title: How many goals has Steven Gerrard scored?
Steven Gerrard was born on 30th of May 1980. He is now 37 years old. Happy birthday, Steven!

To celebrate his anniversary, your goal is to remind him the number of goals he has scored each year in premiere league for Liverpool.

He doesn't want to remember the goals scored before or after playing for Liverpool. It is like scoring `0` goals.

**Input**

The starting year of football season.

**Output**

The number of goals scored by Steven during this season for Liverpool.

**List of seasons and goals**

```
1998–99     0
1999–2000   1
2000–01     7
2001–02     3
2002–03     5
2003–04     4
2004–05     7
2005–06     10
2006–07     7
2007–08     11
2008–09     16
2009–10     9
2010–11     4
2011–12     5
2012–13     9
2013–14     13
2014–15     9

```

**Example**

```
Input    Output
2002     5
2017     0
1990     0
2014     9

```

This is so the shortest submission in bytes in each language wins. Explanations are encouraged.

# Answer
> 3 votes
# 05AB1E, ~~25~~ 24 bytes

```
•3ßÎó‚4Ëǝï•17в15ÝƵÊØ+Ikè

```

Try it online! or as a Test suite

**Explanation**

```
•3ßÎó‚4Ëǝï•                 # push the number 69255401071877657848
           17в              # convert to list of base-17 digits
                            # produces the list [1,7,3,5,4,7,10,7,11,16,9,4,5,9,13,9,0]

              15Ý           # push the range [0 ... 15]
                 ƵÊØ+       # add the 303rd prime (1999) to each
                     Ik     # get the index of the input in this list
                            # or -1 if outside the range
                       è    # get the element at that index in first list

```

# Answer
> 21 votes
## JavaScript (ES6), ~~47~~ ~~43~~ ~~42~~ 39 bytes

```
y=>+'0723135148933694'[y-1999]+y%20%9|0

```

### How?

We compute an approximation ***x*** of the number of goals for a given year ***y*** with the formula:

```
x = y % 20 % 9

```

This is actually a very bad approximation, but it's always less than or equal to the expected value ***v*** and never less than ***v - 9***, which allows to encode the difference with a single decimal digit.

```
y    | y % 20 | x = y % 20 % 9 | v  | v - x
-----+--------+----------------+----+------
1999 |     19 |              1 |  1 |     0
2000 |      0 |              0 |  7 |     7
2001 |      1 |              1 |  3 |     2
2002 |      2 |              2 |  5 |     3
2003 |      3 |              3 |  4 |     1
2004 |      4 |              4 |  7 |     3
2005 |      5 |              5 | 10 |     5
2006 |      6 |              6 |  7 |     1
2007 |      7 |              7 | 11 |     4
2008 |      8 |              8 | 16 |     8
2009 |      9 |              0 |  9 |     9
2010 |     10 |              1 |  4 |     3
2011 |     11 |              2 |  5 |     3
2012 |     12 |              3 |  9 |     6
2013 |     13 |              4 | 13 |     9
2014 |     14 |              5 |  9 |     4

```

### Demo

```
let f =

y=>+'0723135148933694'[y-1999]+y%20%9|0

for(y = 1997; y <= 2017; y++) {
  console.log(y, f(y))
}
```

# Answer
> 3 votes
# JavaScript, 44 Bytes

```
y=>parseInt("173547a7bg9459d9"[y-1999],17)|0

```

# Answer
> 2 votes
# PHP, 44 Bytes

```
<?=intval(_173547a7bg9459d9[$argn-1998],17);

```

Try it online!

# Answer
> 1 votes
# PowerShell, 65 Bytes

```
(($g=(1,7,3,5,4,7,10,7,11,16,9,4,5,9,13,9)["$args"-1999]),0)[!$g]

```

uses a ternary/array format to return 0 if the year isn't in the array.

This is so long because powershell doesn't have any `else return 0` format, and the full array is required, if he scored 9 or less goals in each year we could shave a lot off this by indexing into a string instead.

# Answer
> 1 votes
# Bash, ~~97~~ 93 Bytes

```
a=(1 7 3 5 4 7 10 7 11 16 9 4 5 9 13 9)
((2014<$1||$1<1999))&&(echo 0)||(echo $[a[$1-1999]])

```

# Answer
> 0 votes
# JavaScript (ES6), ~~50~~ 41 bytes

```
y=>+`0x${"06243696af8348c8"[y-1999]}`+1|0

```

---

## Try it

```
f=
y=>+`0x${"06243696af8348c8"[y-1999]}`+1|0
oninput=_=>o.innerText=f(+i.value)
o.innerText=f(i.value=1998)
```

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

# Answer
> 0 votes
# C#, ~~79~~ 72 bytes

```
y=>new[]{0,1,7,3,5,4,7,10,7,11,16,9,4,5,9,13,9}[y>2014|y<1999?0:y-1998];

```

# Answer
> 0 votes
# Braingolf v0.6, 48 bytes

```
#ߎ-V173547#
792+82*945994+9&,0R!?1-[v>R]v_:0_|;

```

This is a weird one.

The character `ߎ` has the ordinal 1998, making  the Braingolf literal for 1998, which is then subtracted from the input.

### Explanation:

```
#ߎ-V173547#
792+82*945994+9&,0R!?1-[v>R]v_:0_|;  Implicit input of n
#ߎ-                                  Subtract 1998 from n
   V                                 Create a new stack and switch to it
    173547                           Digit literals 1, 7, 3, 5, 4 and 7
          #<newline>                 Integer literal 10
792                                  Digit literals 7, 9 and 2
   +                                 Sum the last 2 items (9 and 2) to make 11
    82*                              Digit literals 8 and 2 multiplied to make 16
       9459                          Digit literals 9, 4, 5 and 9
           94+                       Digit literals 9 and 4 summed to make 13
              9                      Digit literal 9
               &,                    Reverse stack
                 0                   Digit literal 0
                  R                  Return to main stack
                   !?                If n != 0
                     1-              Decrement n
                       [...]         Loop, repeat n+1 times
                        v>           Move to next stack and rotate to the right
                          R          Return to main stack
                            v_       Move to next stack and output last item
                              :      Else
                               0_    Push zero and output
                                 |   Endif
                                  ;  Suppress implicit output

```

# Answer
> 0 votes
# Python 2, ~~59~~ 58 bytes

Inspired by this answer.

```
lambda x:1997<x<2015and int('173547a7bg9459d9'[x-1999],17)

```

Try it online!

---
Tags: code-golf
---


title: Write your own Death Note

text:
# Question
Title: Write your own Death Note
### Kira needs your help!

---

## Input format:

```
Date [and/or Time]
Name
Gender
Reason

```

## Output format:

```
<Last Name, First Name> <will die/died> on the <DD><st/nd/rd/th> of <MMM, YYYY> [at <hh:mm:ss TT>].
<He/She> <will die/died> of <Reason>.

```

---

---

# Details, Details:

---

Your program should account for at least the following date input formats:

```
9 November 2003
9/11/2003
November 9, 2003

```

---

Time formats:

```
hh tt
hh TT
hh:mm tt
hh:mm TT
hh:mm:ss tt
hh:mm:ss TT
HH
HH:mm
HH:mm:ss

```

---

The following name input formats:

```
first        // Stephen
last         // Harper
first last   // Stephen Harper
last, first  // Harper, Stephen

```

---

---

# Test cases:

---

## Input:

```
2 September 1973
J.R.R. Tolkien
Male
pneumonia

```

## Output:

> Tolkien, J.R.R. died on the 2nd of September, 1973.
>
> He died of pneumonia.

---

**DISCLAIMER:** If he actually dies on this date, it's *Kira's* fault, not mine.

**UPDATE:** Stephen Harper did not die on the listed date

## Input:

```
21/12/12 23:59:59             // DD/MM/YY HH:mm:ss
Harper, Stephen               // Last, First
Unknown                       // Gender
a heart attack for no reason  // Reason

```

## Output:

> Harper, Stephen will die on the 21st of December, 2012 at 11:59:59 PM.
>
> Harper, Stephen will die of a heart attack for no reason.

---

---

## Bonus:

```
July 21, 1969 02:56:15 GMT
Armstrong, Neil
Male
poisoned moon cheese

--

January 19, 2038 03:14:08 GMT
Everyone
Unknown
Y2K38

```

Add `<st/nd/rd/th>` at the end of `DD` for input.

# Answer
## Javascript (561)

This can probably be reduced significantly, but here goes:

```
i=i.split("\n");d=new Date(i[0]);t=d.getDate();z=t%10;t+=z==1?"st":z==2?"nd":z==3?"rd":"th";m=['January','February','March','April','May','June','July','August','September','October','November','December'][d.getMonth()];y=d.getFullYear();a=d.getHours();b=d.getMinutes();c=d.getSeconds();l=a&&b&&c?" at "+a+":"+b+":"+c:"";g=d>new Date()?"will die":"died";n=i[1].split(" ");n[1]?n[0][n[0].length-1]==","?n=i[1]:n=n[1]+", "+n[0]:n[0];s=i[2]=="Male"?"He":i[2]=="Female"?"She":n;document.write(n+" "+g+" on the "+t+" of "+m+", "+y+l+".<br>"+s+" "+g+" of "+i[3]+".");

```

Sample I/O:

```
2 September 1973
J.R.R. Tolkien
Male
pneumonia

```

> Tolkien, J.R.R. died on the 2nd of September, 1973. He died of pneumonia.

```
January 19, 2038 03:14:08 GMT
Everyone
Unknown
Y2K38

```

> Everyone will die on the 18th of January, 2038 at 21:14:8. Everyone will die of Y2K38.

Try it out on JsFiddle.
> 6 votes

# Answer
## VB.NET, ~~727~~ 695

Okay, golfed a bit. Requires `Option Strict Off`.

```
Module M
Sub Main
Dim d=Date.Parse(Console.ReadLine),n=Console.ReadLine,o=Date.Now,g=Console.ReadLine,r=Console.ReadLine,i=n.IndexOf(" "),f=d.Day Mod 10+(d.Day\10=1)*5,a=Array.IndexOf("male|female|he|she|him|her|guy|girl|boy|lady|man|woman".Split("|"), g.ToLower),b="|st|nd|rd".Split("|"),m="|January|February|March|April|May|June|July|August|September|October|November|December".Split("|")
If n.IndexOf(",")<0 Then n=n.Substring(i+1)&", "&n.Substring(0,i)
g=If(a<0,n,If(a Mod 2,"She","He"))
Console.Write("{0} {11} on the {1}{2} of {3}, {4} at {5}:{6:00}:{7:00}.{8}{9} {11} of {10}.",n,d.Day,If(f<4,b(f),"th"),m(d.Month),d.Year,d.Hour,d.Minute,d.Second,vbCrLf,g,r,If(o<d,"will die","died"))
End Sub
End Module

```

It accepts the dates in all the test cases, and many other formats thanks to `Date.Parse`. It accepts *many* genders (as you can see) as well. If Kira decides to put only the person's first or last name, the program will crash.
> 5 votes

# Answer
### CSharp - 463 chars

```
void Main(){Func<String>c=()=>Console.ReadLine();var d=DateTime.Parse(c());var n=c();if(!n.Contains(",")&&n.Contains(" "))n=n.Split(' ')[1]+", "+n.Split(' ')[0];n+=" ";var g=c().ToLower();g=g.Contains("male")?g.Replace("female","She").Replace("male","He"):"They";var r=c();var f=(DateTime.Now<d);Console.Write(String.Format(n+"{0} on the {1} {2}\n{3} {0} of {4}",(f?"will die":"died"),d.ToString("dddd 'of' MMMM, yyyy"),d.Date==d?"":d.ToString("hh:mm:ss"),g,r));}

```
> 2 votes

# Answer
## PHP, 509 474 462 461 characters

```
<?for($l=0;$l<4;)$i[$l++]=chop(fgets(STDIN));
putenv('TZ=GMT');
$t=strtotime(preg_match("/(\d+)\/(\d+)\/(\d+)(.*)/",$i[0],$q)?"$q[1]-$q[2]-".($q[3]<100?19+1*($q[3]<70):"").$q[3].$q[4]:$i[0]);
$z=$t<time()?" died":" will die";
$f="jS \of F, Y".($t%86400?" \a\\t g:i:s A":"");
$n=strpos($i[1],',')?$i[1]:explode(" ",$i[1]);
if(is_array($n))$n=$n[1]!=""?$n[1].", ".$n[0]:$n[0];?>
<?=$n."$z on the ".date($f,$t)."\n\n".($i[2][0]==M?He:($i[2][0]==F?She:$n))."$z of ".$i[3];

```

I've added newlines after each `;` but not counted them as they don't need to be there.
Whether the code handles dates beyond January 19, 2038 03:14:07, depends on whether it's run on a 64bit machine.
> 1 votes

# Answer
# VBA, ~~384~~ 366 Bytes

### Golfed

Full `sub`routine that takes input of expected type `Variant\String` and outputs the associated deathnote message to the VBE immediates window

*Note: VBA is incapable of handling Timezones without declaring Windows API functions, so as these are not necessary for the question, they have been excluded*

```
Sub x(d,n,g,r)
e=CDate(d)
f=Day(e) Mod 10
w=IIf(e>Now," will die"," died")
i=InStr(1,n," ")
n=IIf(InStr(1,n,","),n,Mid(n,i+1)&", "&Mid(n,1,i-1))
g=LCase(g)
Debug.?n;w" on the "Day(e)Split("th|st|nd|rd","|")(IIf(f>3,0,f))" of "MonthName(Month(e))", "Year(e)IIf(InStr(1,d,":")," at "&TimeValue(d),"")"."vbCr;IIf(g="male","He",IIf(g="female","She",n))w" of "r".
End Sub

```

### Bonus Verison, ~~394~~ 376 Bytes

Slightly modified version of the above that handles all of the bonus cases with the exception of timezones (Correction for handling mononyms)

```
Sub x(d,n,g,r)
e=CDate(d)
f=Day(e) Mod 10
i=InStr(1,n," ")
w=Space(0 ^i)&IIf(e>Now,"will die","died")
n=IIf(InStr(1,n,",")^i,n,Mid(n,i+1)&", "&Mid(n,1,i))
g=LCase(g)
Debug.?n;w" on the "Day(e)Split("th|st|nd|rd","|")(IIf(f>3,0,f))" of "MonthName(Month(e))", "Year(e)IIf(InStr(1,d,":")," at "&TimeValue(d),"")"."vbCr;IIf(g="male","He",IIf(g="female","She",n))w" of "r".
End Sub

```

### Usage

input and output sequence of the example problems as seen from the VBE immediate window

```
?Now
01-Jun-17 1:59:35 PM

x "2 September 1973", "J.R.R. Tolkien", "Male", "pneumonia"
Tolkien, J.R.R. died on the 2nd of September, 1973.
He died of pneumonia.

x "21/12/12 23:59:59", "Harper, Stephen", "Unknown", "a heart attack for no reason"
Harper, Stephen died on the 21st of December, 2012 at 11:59:59 PM.
Harper, Stephen died of a heart attack for no reason.

x "July 21, 1969 02:56:15", "Armstrong, Neil", "Male", "poisoned moon cheese"
Armstrong, Neil died on the 21st of July, 1969 at 2:56:15 AM.
He died of poisoned moon cheese.

## Using Bonus Version

x "January 19, 2038 03:14:08","Everyone","Unknown","Y2K38"
Everyone will die on the 19th of January, 2038 at 3:14:08 AM.
Everyone will die of Y2K38.

```
> 1 votes

---
Tags: code-golf
---


title: Let's get the gang back together!

text:
# Question
Title: Let's get the gang back together!
A narcissist program is a program that only accepts its own source code. A bigotous program is a program that only accepts the source code of programs semantically equivalent to itself. A gang member is somewhere in between.

In particular, we will define a **gang** as set of programs `G`, which may or may not be in the same programming language, such that each program, when executed, will only accept members of its gang, and reject everything else (since they all do the same thing, this means that are semantically equivalent). A gang member is a program that is part of a gang, and the set of programs that it accepts is its gang.

So, a narcissist program is a gang of size 1, and a class of bigots is a maximally sized gang (every equivalent program gets to be part of the gang).

Your job is to create a gang of programs. It must be of size at least 2, and can have programs in different languages (you can even count the same program multiple times if it's a polyglot).

Your score is (average length of gang member)/(# of unique programming languages), which you are trying to minimize (so you are rewarded for using different languages). It is considered cheating to use built in language features that allow a program to access its own code.

Note: We'll define acceptance v.s. rejection via https://codegolf.meta.stackexchange.com/a/12685/16842 or https://codegolf.meta.stackexchange.com/a/12684/16842, your choice.

# Answer
> 4 votes
# 0 points (average length 0 bytes, 2 unique language)

I'm assuming we can define acceptance and rejection as the output of two different values.

The gang size is 2 (the languages are **05AB1E** and **2sable**), and the program is the empty program.

For some reason, both an empty **05AB1E** program and an empty **2sable** program appear to outputs `2` (plus a newline in the case of 2sable) when the input is not empty (i.e. a different program; rejection). They output nothing if there is no input (i.e. the same program; acceptance).

Since I "can even count the same program multiple times if its a polygot", these are two programs.

*(I know neither 05AB1E nor 2sable at all and just tried golfing languages in TIO until I found some that seemed to work, so this answer might be wrong if they output something else for some specific inputs.)*

# Answer
> 2 votes
# ∞ points (Average length ∞, 1 unique language)

I might not win the challenge, but I sure have the biggest gang. (Watch out!)

```
main=interact$ \x->if length(lines x)==1&&take 279x==quine q++"--"then"Yarr!"else"It's one of them PyRulez guys!";quine s=s++show s;q="main=interact$ \\x->if length(lines x)==1&&take 279x==quine q++\"--\"then\"Yarr!\"else\"It's one of them PyRulez guys!\";quine s=s++show s;q="--

```

The language is Haskell. You can keep adding any letter to the end of the program except newlines. Outputs `Yarr!` for gang members and `It's one of them PyRulez guys!` for everything else.

---

# 141.9 points (Average length 141.9 bytes, 1 unique language, 255 gang members)

```
f x=elem '\n'x||take 141x/=k q++"--"||length x>142;k s=s++show s;q="f x=elem '\\n'x||take 141x/=k q++\"--\"||length x>142;k s=s++show s;q="--

```

# Answer
> 2 votes
# 140.75 points (average length 281.5 bytes, 2 unique languages)

These programs use cryptographic hashing to identify the gang members, and the first line of each program is identical and encodes the hash of the remainder of each program. Each program then compares the first line to the given list and the hash of the remainder, and returns `true`/`True` if it's accepted and `false`/`False` if it's rejected.

**JavaScript (Node.js)**, 338 bytes

```
x=["69fa7652b24a3aa2a56122db2f3ce27395a3be0a6e6eed00b01592b9","604e0bb526a9af96f90a964c3849be96862bb3d31b9fcfbc83d6c7aa"]
c=[]
process.stdin.on('data',d=>c.push(d)).on('end',_=>console.log((d=Buffer.concat(c)).slice(0,121)=='x='+JSON.stringify(x)&&x.some(y=>y==require('crypto').createHash('sha224').update(d.slice(121)).digest('hex'))));

```

**Python 2**, 225 bytes

```
x=["69fa7652b24a3aa2a56122db2f3ce27395a3be0a6e6eed00b01592b9","604e0bb526a9af96f90a964c3849be96862bb3d31b9fcfbc83d6c7aa"]
import hashlib,sys,json
I=sys.stdin
print I.read(121)=='x='+json.dumps(x,separators=',:')and hashlib.sha224(I.read()).hexdigest()in x

```

# Answer
> 1 votes
## 0 points (Average length 24 bytes, ∞ unique languages)

This is noncompeting since the MetaGolfScript family is banned, but I thought it would be fun to post it anyways.

The languages are MetaGolfScript-`N`, for every natural number `N`. There is one program in each language, which all have the following source code:

```
{s ":p`:s;p" + =}:p`:s;p

```

---
Tags: code-challenge, decision-problem, quine
---