title: Verify the birth number

text:
# Question
Title: Verify the birth number
A Norwegian Birth Number consists of 11 digits, composed the following way:

```
DDMMYYiiikk

```
* `DD` is the day (from 01-31)
* `MM` is the month (from 01-12)
* `YY` is the year (from 00-99). It's not differentiated between 1900 and 2000
* `iii` is the "individual number"
* `kk` are two control digits

`iii` is determined by birthyear and gender the following way

* 0000-1900: Disregard, there is some inconsistency and special cases
* 1900-1999: Range = 000-499
* 2000-2039: Range = 500-999
* Female: Even numbers (and 000)
* Male: Odd numbers

The control numbers are determined the following way:

Let's call the 11 digits:

```
d1 d2 m1 m2 y1 y2 i1 i2 i3 k1 k2

```

Then the control digits can be calculated using the equations:

```
k1 = 11 - ((3 * d1 + 7 * d2 + 6 * m1 + 1 * m2 + 8 * y1 + 9 * y2 + 4 * i1 + 5 * i2 + 2 * i3) mod 11)

k2 = 11 - ((5 * d1 + 4 * d2 + 3 * m1 + 2 * m2 + 7 * y1 + 6 * y2 + 5 * i1 + 4 * i2 + 3 * i3 + 2 * k1) mod 11).

```

For some combinations, the control numbers `k1` or `k2` can become `10`. If that's the case, the number will be invalid.

If the sum modulus 11 for `k1` or `k2` is 11, i.e. `k1 = 11 - (11 mod 11)`, then the control digit will be 0, not 11.

**Challenge**

Take a letter, `M` or `F` (male or female), and an eleven digit number as input, and check if the Birth Number is valid according to the rules above.

* Input format and order is optional
* The 11 numbers must be a single number or a consecutive string (you can't take the input as `DD, MM, YY, iii, kk`).
* You can assume the date is valid (310699xxxxx will not be given as input)
* Output is a truthy/falsy value (1/0, true/false etc.)
* Program or function
* All standard rules apply

You can find all valid numbers on this page (in Norwegian) by choosing a date.

Examples:

```
M, 01010099931
True

F, 01029042620
True

M, 0101009841
False

F, 01010051866
True

F, 08021690849
True

M, 01029040105
True

M, 01029037473
False

```

Shortest code in bytes win.

# Answer
> 2 votes
# Python 3, ~~227~~ 221 bytes

Function that takes two arguments, the gender 'm', and the birthnumber 'n', both as strings. There may be some more golfing to be done, especially in the last line. I'll keep working on it.

```
def a(m,n):
 o=[3,7,6,1,8,9,4,5,2];t=[5,4,3,2,7,6,5,4,3,2];n=list(map(int,n));y=z=b=0;q=11
 for i in n[:9]:z+=o[b]*i;y+=t[b]*i;b+=1
 print((q-z%q)%q==n[9] and (q-(y-z-z)%q)%q==n[-1] and len(n)<12 and ord(m)%2==n[8]%2)

```

# Answer
> 2 votes
## JavaScript (ES2016), 275 259 255 254 252 Bytes

**Golfed**:

```
f=(g,I)=>{[,d,m,y,i,k]=/(..)(..)(..)(...)(..)/.exec(I.padEnd(12)),v=g.charCodeAt()%2!=i%2|y<=39&i<500,s=k=>11-([...I].slice(0,-2).map((e,i)=>e*[..."376189452543276543"][i+!k|9]).reduce((a,b)=>a+b)+2*k)%11,[s(0),s(s(0))].map((s,i)=>v&=k[i]!=s);return!v}

```

**Tests**:

```
for (let args of [
    ["M", "01010099931"], // true
    ["F", "01029042620"], // true
    ["M", "0101009841"],  // false
    ["F", "01010051866"], // true
    ["F", "08021690849"], // true
    ["M", "01029040105"], // true
    ["M", "01029037473"]  // false
]) {
    console.log(f(...args));
}

```

**Ungolfed**:

```
let f = (g, input) => {

    /* Sanitize input, destructure arguments via RegExp */
    let [, d, m, y, i, k] = /(..)(..)(..)(...)(..)/.exec(input.padRight(12));

    /* Validate gender and year */
    let violation = g.charCodeAt() % 2 != i % 2 | y <= 39 & i < 500;

    let n = [..."376189452543276543"];
    /* This function computes k1 if given no arguments, k2 if given one argument */
    let s = k => 11 - ([...input].slice(0, -2).map((e, i) => e * n[i + !k | 9]).reduce((a, b) => a + b) + 2 * k) % 11;

    /* Validate the control numbers k */
    [s(0), s(s(0))].map((s, i) => violation &= k[i] != s);

    return !violation;
}

```

# Answer
> 1 votes
## JS, 343 Bytes

```
x=prompt().replace(/F/,1).replace(/M/,2).match(/\d{1}/g);v=Math.abs((x[0]-x[9])%2);v++;t=x[5]*10+x[6]*1;i=x[7]*1;if(t>39&&i>4){v--}if((11-(3*x[1]+7*x[2]+6*x[3]+1*x[4]+8*x[5]+9*x[6]+4*x[7]+5*x[8]+2*x[9])%11)%11===x[10]*1&&(11-(5*x[1]+4*x[2]+3*x[3]+2*x[4]+7*x[5]+6*x[6]+5*x[7]+4*x[8]+3*x[9]+2*x[10])%11)%11===x[11]*1){v++}alert(Math.floor(v/3))

```

---
Tags: code-golf, arithmetic
---


# Question
Title: Illustrate football team formations on a pitch
Football is the sport where players kick the ball, not carry it. Some confused individuals might call this soccer.

---

A football team has one goalkeeper, and 10 players out on the pitch. There are many formations used in football, that dictates where each player should be (the player of course moves around, but it's the base position).

The most common formation is 4-4-2, which means that there are 4 defenders, 4 midfielders and two attackers. Other formations are ("defenders, midfielders, attackers" or "defenders, midfielders, midfielders, attackers"):

* 4-4-2
* 4-3-3
* 5-3-2
* 3-4-3
* 3-5-2
* 4-5-1
* 5-4-1
* 4-4-1-1
* 4-3-1-2
* 4-1-2-3
* 4-1-3-2
* 4-3-2-1
* 3-4-1-2
* 3-3-3-1

The challenge is to take two inputs, one for each of the two teams and output a overview of the players on the field.

In general: Most information about the layout of the ASCII-art can be found in the figures (a picture says more than 1000 words). Only the way to place the 10 players on the field is explained in detail:

* The keeper and the penalty area takes up 3 rows of ASCII-characters
    + Layout and number of spaces can be found in the figure below
* There is no empty row between the penalty area and the defenders
* If there are 3 numbers in the formation (e.g. 4-4-2, 4-3-3 etc. Not 4-3-2-1):
    + There is no empty row between the defenders and the midfielders
    + There is one empty row between the midfielders and the attackers
* If there are 4 numbers in the formation (e.g. 4-3-2-1, 3-3-3-1 etc. Not 4-4-2):
    + There is no empty row between the defender and the first row of midfielders
    + There is no empty row between the first row of midfielders and the second
    + There is no empty row between the second row of midfielders and the attackers
* There is no empty rows between the attackers and the center line
* The team on the upper half are marked as `x`, and the team on the second half are marked as `o`.
* Each row of players shall be distributed on the pitch as shown in the figures below. The number of spaces can be seen in the figure.

The following figure does not represent a valid formation, but is used to illustrate the layout and number of required spaces between each player. The input for this would be `2 3 4 5` and `5 4 2`:

```
+-----------------+
|     |  x  |     |
|     +-----+     |
|     x     x     |
|    x   x   x    |
|  x   x   x   x  |
|  x  x  x  x  x  |
+-----------------+
|     o     o     |
|                 |
|  o   o   o   o  |
|  o  o  o  o  o  |
|     +-----+     |
|     |  o  |     |
+-----------------+

```

---

**Valid examples:**

```
Input:
4 4 2, 5 3 1 1

+-----------------+
|     |  x  |     |
|     +-----+     |
|  x   x   x   x  |
|  x   x   x   x  |
|                 |
|     x     x     |
+-----------------+
|        o        |
|        o        |
|    o   o   o    |
|  o  o  o  o  o  |
|     +-----+     |
|     |  o  |     |
+-----------------+

```

---

```
Input:
3 5 2, 4 4 1 1

+-----------------+
|     |  x  |     |
|     +-----+     |
|    x   x   x    |
|  x  x  x  x  x  |
|                 |
|     x     x     |
+-----------------+
|        o        |
|        o        |
|  o   o   o   o  |
|  o   o   o   o  |
|     +-----+     |
|     |  o  |     |
+-----------------+

```

**Rules:**

* Input can be on any convenient format, separated however you want. Format can be a single string (`5311`), comma separated digits (`5,3,1,1`), etc.
    + The input should not contain any other information than the two formations
* The output should look exactly as the sample figures, but trailing spaces and newlines are OK.
* You can assume only valid input is given (only formations in the list will be used).
* Full program or function

This is code golf, so the shortest code in bytes win.

# Answer
# JavaScript (ES6), 258 ~~262~~

Anonymous function, taking 2 parameters as numeric arrays

```
(a,b,H=f=>(f[3]||f.push(0,f.pop()),[z='+-----------------+',...[6,7,...f].map(x=>`|${'98,8o8,5o5o5,4o3o3o4,2o3o3o3o2,2o2o2o2o2o2,5|2o2|5,5+-----+5'.replace(/\d/g,x=>' '.repeat(x)).split`,`[x]}|`),'']))=>H(a).join`
`.replace(/o/g,'x')+z+H(b).reverse().join`
`

```

**Test**

```
F=(a,b,
   H=f=>(
    f[3]||f.push(0,f.pop()),
    [z='+-----------------+',...[6,7,...f].map(x=>`|${'98,8o8,5o5o5,4o3o3o4,2o3o3o3o2,2o2o2o2o2o2,5|2o2|5,5+-----+5'.replace(/\d/g,x=>' '.repeat(x)).split`,`[x]}|`),'']
   )
)=>
  H(a).join`\n`.replace(/o/g,'x')+z+H(b).reverse().join`\n`

function test() {
  var f1=F1.value.match(/\d+/g),f2=F2.value.match(/\d+/g)
  O.textContent=F(f1,f2)
}

test()
```

```
x <input id=F1 value='4,4,2' oninput='test()'><br>
o <input id=F2 value='4,3,1,2' oninput='test()'><br>
<pre id=O>
```
> 1 votes

# Answer
# Python 2, ~~401~~ 377 bytes

```
def g(x,o):
 r=lambda r:["|"+"  x"*5+"  |","|        x        |","|     x     x     |","|    x   x   x    |","|  x   x   x   x  |"][r%5];d="+"+"-"*17+"+";h=[d,"|     |  x  |     |","|     +-----+     |"]+map(r,x);b=map(lambda r:r.replace("x","o"),[s for s in h[:3]]+map(r,o))[::-1];e="|"+" "*17+"|"
 if len(x)-4:h.insert(5,e)
 if len(o)-4:b.insert(1,e)
 print"\n".join(h+[d]+b)

```

Ungolfed version with test environment here!

Function that takes two lists of the format \[defenders, midfielders, midfielders, attackers\] while the one midfielder number is optional. Team X (top) comes first, team O (bottom) second.
> 2 votes

# Answer
## Perl, ~~360~~ ~~332~~ 324 bytes

```
sub f{$q="";($_,$p)=@_;@x=/\S+/g;splice@x,2,0,0if@x<4;for(@x) {$s=(17-$_)/($_+1);$s=$=+1if($s!=($==$s));$x=$"x$=;@a=();push@a,$p for 1..$_;$q.=$_==0?"|$u$u$u  |\n":"|$x".join($"x$s,@a)."$x|\n"}$q}($k,$j)=<>;$u=$"x5;$^="-"x17;$i="|$u+-----+$u|";say"x$^x\n|$u|  x  |$u|\n$i\n".f($k,x)."+$^+".(reverse f$j,o)."\n$i\n|$u|  o  |$u|\nx$^x"

```

Requires `-E`|`-M5.010`:

```
$ echo $'4 4 2\n4 4 1 1' | perl -M5.010 football.pl
x-----------------x
|     |  x  |     |
|     +-----+     |
|  x   x   x   x  |
|  x   x   x   x  |
|                 |
|     x     x     |
+-----------------+
|        o        |
|        o        |
|  o   o   o   o  |
|  o   o   o   o  |
|     +-----+     |
|     |  o  |     |
x-----------------x

```

Somewhat ungolfed:

```
sub f{
    $q="";
    ($_,$p)=@_;
    @x=/\S+/g;
    splice@x,2,0,0if@x<4;
    for(@x) {
        $s=(17-$_)/($_+1);
        $s=$=+1if($s!=($==$s));
        $x=" "x$=;
        @a=();
        push@a,$p for 1..$_;
        $q.=$_==0?"|$u$u$u  |\n":"|$x".join(" "x$s,@a)."$x|\n"
    }
    $q
}

($k,$j)=<>;
$u=" "x5;
$^="-"x17;
$i="|$u+-----+$u|";
say"x$^x\n|$u|  x  |$u|\n$i\n".f($k,x)."+$^+".(reverse f$j,o)."\n$i\n|$u|  o  |$u|\nx$^x"

```
> 1 votes

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


title: Number of steps for a binary search

text:
# Question
Title: Number of steps for a binary search
Given an input of a positive integer, output the number of steps it takes to find the input via a binary search starting at 1.

We are simulating a binary search for the integer that was given as input, in which the simulated searcher can repeatedly guess an integer and be told whether it is too high, too low, or correct. The strategy for finding the integer is as follows:

* Let n be the integer given as input that we are trying to find.
* Start with a guess of 1. (For every guess, increment the number of steps (regardless of whether it was correct or not), and immediately stop and output the total number of steps if the guess was correct.)
* Double the guess repeatedly until the guess is greater than n (the target number). (Or if it is correct, but that's already covered by our correct-guess rule mentioned above.)
* Now, set an upper bound of the first power of 2 that's greater than n (i.e. the number that was just guessed), and set a lower bound of the power of 2 directly below it.
* Repeatedly guess the average (rounded down) of the upper bound and the lower bound. If it is too high, set it as the upper bound. If it is too low, set it as the lower bound. This procedure is guaranteed to eventually result in a correct guess.

Here's an example, for the input of n=21:

```
1 -> 2 -> 4 -> 8 -> 16 -> 32 -> 24 -> 20 -> 22 -> 21
\__________________________/
   repeated doubling      \________________________/
                             repeated averaging

```

Since this is , the shortest code in bytes will win.

Here are all outputs from n=1 to n=100:

```
1
2
4
3
6
5
6
4
8
7
8
6
8
7
8
5
10
9
10
8
10
9
10
7
10
9
10
8
10
9
10
6
12
11
12
10
12
11
12
9
12
11
12
10
12
11
12
8
12
11
12
10
12
11
12
9
12
11
12
10
12
11
12
7
14
13
14
12
14
13
14
11
14
13
14
12
14
13
14
10
14
13
14
12
14
13
14
11
14
13
14
12
14
13
14
9
14
13
14
12

```

And here are some larger test cases:

```
1234 -> 21
1337 -> 22
3808 -> 19
12345 -> 28
32768 -> 16
32769 -> 32
50000 -> 28

```

# Answer
# Japt, ~~13~~ 12 bytes

Oh my gosh I was beating both Jelly and Pyth for a time :D

```
¢a1 ªJ +1+¢l

```

Test it online!

Here's the strategy I use: let **x** be the input integer, and let **b** be **x**'s binary representation. The correct output is 1 + the length of **b** \+ the last index of a **1** in **b**, minus 1 if this index is 0.
> 10 votes

# Answer
# Jelly, ~~18~~ ~~15~~ ~~10~~ 9 bytes

```
B>WU;BḄBL

```

Try it online! or verify the small test cases and large test cases.

### Background

Let **n** be a positive integer and **m** the smallest power of **2** that is greater or equal than or equal to **n**.

* The *doubling* phase takes one step for each digit in the binary representation of **m**.
* Take the binary representation of **n**, remove the first, most significant digit (always **1**) and all trailing zeroes. The *averaging phase* takes one step for each remaining digit.

To avoid calculating **m**, we observe that, if **n \< m**, the number of binary digits of **n** is exactly one less than the number of binary digits of **m**.

If we replace the first binary digit of **n** with a **0**, reverse the result, append the original binary digits and remove all leading zeroes, then following happens:

* If **n** is a power of **2**, *all* digits of the first (modified) half get removed, leaving only the digits of the original binary representation of **n = m**.
* If **n** is *not* a power of **2**, the digit in the first half that corresponds to the most significant digit does *not* get removed, compensating for the fact that **n** has a binary digit less than **m**.

### How it works

```
B>WU;BḄBL  Main link. Input: n

B          Compute the binary representation of n.
 >W        Compare it with [n].
           n is positive, so it is not less than the first binary digit and the
           comparison yields zero. When comparing lists of different length, the
           elements in the longer list that do not have a pair remain untouched.
           Therefore, this will just zero out the first binary digit.
   U       Reverse the modified binary representation.
    ;B     Concatenate it with the unmodified binary representation of n.
      ḄB   Convert from binary to integer, and back to binary.
           This removes leading zeroes.
        L  Get the length of the resulting array.

```
> 7 votes

# Answer
## ES6, 38 bytes

```
x=>33-(g=Math.clz32)(x-1)+g(x&-x)-g(x)

```

As alluded to by other answers, you can calculate the number of steps from the positions of the first and last bits.

The number of steps in the doubling phase is `n=33-Math.clz32(x-1)`. We want 2ⁿ ≥ x but `n=33-Math.clz32(x)` gives us 2ⁿ \> x so we subtract 1 from x to compensate.

The number of steps in the averaging phase is easier, it's simply `n=Math.clz32(x&-x)-Math.clz32(x)`. `x&-x` is a handy expression that evaluates to the lowest bit of `x` (as a power of 2).
> 4 votes

# Answer
# Pyth, ~~15~~ 13 bytes

```
h-y.ElQ/PPyQ2

```

I have found that the number to be calculated is `1 + 2*ceil(log_2(x)) - [number of 2s in x's prime factorization, minus 1 if x is a power of 2 greater than 1].`

Try it here.
> 2 votes

# Answer
# Julia, ~~37~~ 35 bytes

```
n->endof(strip(bin(n-1)bin(n),'0'))

```

*Thanks to @AlexA. for saving 2 bytes!*

This follows the observations from my Jelly answer, but deals differently with the edge cases.

If **n \> 1**, the binary representation of **n - 1** has one digit less than the one of the next power of **2**, which is compensated by not removing the first digit of the binary representation of **n**.

By removing all zeroes *from both sides*, we deal with the edge case **1** as well.
> 2 votes

# Answer
# Haskell, 82 bytes

This is a pretty straightforward implementation in Haskell:

```
f x=[j|j<-[1..],let g i|i<2=1|x>g(i-1)=2*g(i-1)|1<2=div(g(i-1)+g(i-2))2,g j==x]!!0

```

Less golfed:

```
f x = head [ stepNum | stepNum <- [1..], step stepNum == x]
  where
    prevStep i = step (i-1)
    step i | i == 1         = 1
           | x > prevStep i = 2 * prevStep i
           | otherwise      = div (prevStep i + step (i-2)) 2

```
> 0 votes

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


title: Help recalculate your rep!

text:
# Question
Title: Help recalculate your rep!
A couple months ago, we had a discussion on meta about increasing the reputation awarded for upvotes on questions. Here's the basics of our current reputation system for votes:1

* A question upvote `U` is worth 5 reputation.
* An answer upvote `u` is worth 10 reputation.
* A question or answer downvote `d` is worth -2 reputation.

There have been many different suggestions for a new system, but the current most popular is identical to the above, but with question upvotes scaled to +10 rep. This challenge is about calculating how much more rep you would earn if this system were put into place.

Let's look at an example. If the voting activity was `UUUUuuuuUUUUUduuudUU`, then you'd earn 121 under the current system:

```
U x 4 x  5 =  20 =  20
u x 4 x 10 =  40 =  60
U x 5 x  5 =  25 =  85
d x 1 x -2 =  -2 =  83
u x 3 x 10 =  30 = 113
d x 1 x -2 =  -2 = 111
U x 2 x  5 =  10 = 121
Total:             121

```

But the same activity would earn 176 under the new system:

```
U x 4 x 10 =  40 =  40
u x 4 x 10 =  40 =  80
U x 5 x 10 =  50 = 130
d x 1 x -2 =  -2 = 128
u x 3 x 10 =  30 = 158
d x 1 x -2 =  -2 = 156
U x 2 x 10 =  20 = 176
Total:             176

```

You would gain **55 rep** from this scenario.

So far, calculating the changed rep isn't that hard; just count the number of `U`s and multiply by 5. Fortunately, the rep system isn't that simple: there is also a **rep cap**, which is the most reputation you can earn from votes in one UTC day. This is set to 200 on all sites.

Also, the rep cap applies in real time: if you have already earned 196 rep and you receive an answer upvote, you will now have 200 rep. If you get a downvote right after that, the 2 rep will be subtracted from 200, so you will have 198 rep.

With the voting activity `UUUuuuuUUUUuuuuUUUUUUUd`, you would earn 148 rep under the current system:

```
U x 3 x  5 =  15 =  15
u x 4 x 10 =  40 =  55
U x 4 x  5 =  20 =  75
u x 4 x 10 =  40 = 115
U x 7 x  5 =  35 = 150
d x 1 x -2 =  -2 = 148
Total:             148

```

But you would earn 198 under the new system:

```
U x 3 x 10 =  30 =  30
u x 4 x 10 =  40 =  70
U x 4 x 10 =  40 = 110
u x 4 x 10 =  40 = 150
U x 7 x 10 =  70 = 200 (rep capped)
d x 1 x -2 =  -2 = 198
Total:             198

```

Thus, the increase is **50 rep**.

## Challenge

Your challenge is to write a program or function that takes in a multi-line string and outputs the total rep that would be gained with the above algorithm. Each line counts as 1 UTC day, so the rep cap only applies once per line.

### Test cases

(One or more lines of input, followed by the output integer.)

```
UUUuudd
15

UUUuUUUUuUuuUUUUudUUUUuU
57

UUUuUUUUuUuuUUUUudUUUUuU
UUUuudd
72

uuuuuuu
uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
uuuuuuuuuuuuuuuuuuuu
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
0

UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
5

(empty string)
0

UUUuuuuuUUUuuUUUUUUuuuUUUuuUUUUuuuuUUUdddddddUU
4

UUUuuuuuUUUuuUUUUUUuuuUUUuuUUUUuuuuUUUdddddddUU
UuuUUUudUU
UUUUUUUUUuuuuuuUUUUUUuuUUUUUUuuuuuUUUUUUUUuUUUuuuuUUUUuuuUUUuuuuuuUUUUUUUUuuUUUuuUU
UUu
U
d
UU
UUUUUUUUUUUU
119

```

**This is code golf, so shortest code in bytes wins.**

Related challenges: Calculate the bounded cumulative sum of a vector, Calculate your stack exchange reputation

1 This is a highly simplified version of the system. You also lose 1 rep for downvoting an answer, and there exist unupvotes, which are weird and follow rules of their own; and undownvotes, which don't even have rules to follow.

# Answer
## Perl, ~~104~~ 91 + 2 = 93 bytes

```
sub f{200*$.>$_[0]?$_[0]:200*$.}for(/./g){$a=/d/?-2:10;$s=f$s+$a;$o=f$o+$a-5*/U/}}{$_=$s-$o

```

Requires the `-p` flag:

```
$ echo UUUuUUUUuUuuUUUUudUUUUuU | perl -p recalc.pl
57
$ echo "UUUuUUUUuUuuUUUUudUUUUuU
UUUuudd" | perl -p recalc.pl
72

```

Breakdown:

```
sub f {
  # '$.' contains the line number (1, 2, ... n)
  200*$. > $_[0] ? $_[0] : 200*$.
}
for(/./g){
  $a= /d/ ? -2  : 10;
  $s=f( $s + $a );
  # /U/ returns `1` if true
  $o=f( $o + $a - 5*/U/ )
}
}{ # Eskimo exit while loop (do this after the outer (from -p) iteration)
$_=$s-$o

```
> 0 votes

# Answer
# Haskell, ~~98~~ 93 bytes

Thanks to BlackCap to golf this further. Now, I think to try lambda in later challenges, now.

```
x#'U'=x
_#'u'=10
_#'d'=(-2)
a&b=foldl1(\d g->min 200$d+a#g)
g=sum.map(\x->(10&x)-(5&x)).lines

```

The first 3 lines is the scoring, a&b is is the score, f is the difference and the g is the function sastifying the specification.

Usage:

```
g"UUUuuuuuUUUuuUUUUUUuuuUUUuuUUUUuuuuUUUdddddddUU" -- 4

```
> 2 votes

# Answer
## ES6, 104 bytes

```
s=>s.split`
`.map(l=>(g=U=>[...l].map(c=>(r+=eval(c))>200?r=200:0,r=0)|r,t+=g(10)-g(5)),u=10,d=-2,t=0)|t

```

Calculates the before and after rep for each line. My first use of `eval`!
> 1 votes

# Answer
# Lua, 196 Bytes

This program takes a single multi-line argument as input, and print the total difference in rep'

```
e,f,a=0,0,{u=10,U=10,d=-2}arg[1]:gsub(".-\n",function(s)x=0 y=0 s:gsub("[^\n]",function(c)t=x+a[c]x,t=t>199 and 200 or t,y+a[c]-(c<"V"and 5 or 0)y=t>199 and 200 or t end)e=e+x f=f+y end)print(e-f)

```

I assumed I am allowed to ask for a trailing new line in the input, if I'm not, here's a 204 Bytes solution that doesn't need it.

```
e,f,a=0,0,{u=10,U=10,d=-2}(arg[1].."\n"):gsub(".-\n",function(s)x=0 y=0 s:gsub("[^\n]",function(c)t=x+a[c]x,t=t>199 and 200 or t,y+a[c]-(c<"V"and 5 or 0)y=t>199 and 200 or t end)e=e+x f=f+y end)print(e-f)

```

### Ungolfed and explanations

```
a={u=10,U=10,d=-2}            -- define the table containing the vote values
e,f=0,0                       -- initialize the total sums of rep'

arg[1]:gsub(".-\n",function(s)-- iterate over each line
  x=0                         -- score by the new scoring method for this UTC day
  y=0                         -- score by the old method
  s:gsub("[^\n]",function(c)  -- iterate over each non new-line character
    t=x+a[c]                  -- new score for today
    x=t>199 and 200 or t      -- reduce it to 200 if >=200
                        -- Do the same thing with the old scoring method
    t=y+a[c]-(c<"V"and 5 or 0)-- if c=="U", this question vote gives only 5
    y=t>199 and 200 or t
  end)
  e=e+x f=f+y                 -- sum the scores over multiple days
end)
print(e-f)                    -- output the difference

```
> 1 votes

---
Tags: code-golf, arithmetic
---


title: Let's play some boardgame!

text:
# Question
Title: Let's play some boardgame!
## Introduction

Boardgames are a classic play between kids, but there are some kids that feel bored playing a boardgame step by step. Now they want the result to be shown before they put their hands on the board.

## Challenge

Suppose this boardgame: `>---#<---X---<X<--#-$`

```
>   means the start of the game
-   means a position without danger
<   means the player should return one step back
X   means the player won't move next round
#   means a portal where the player returns to the start position
$   the first player to get there or after there wins the game

```

The input consists of a string with the boardgame's aspects described above and two arrays with some values (from `1` to `6`) in order that both players (kid `A` and kid `B`) had got when playing one cube.

Both arrays will always have the same length \>= 1.

The kid `A` always start the game.

You must output the kid which got the end or closer to the end first.

If neither one got the end and both kids stay at the same position print `0` or any other falsy value.

If one array runs out while the other has remaining dice rolls (due to one player missing several turns on Xs), the remaining dice rolls should be used up.

For this task, you can create a program/function, that reads input from stdin, or take parameters/arguments and output/return/print the winner kid.

Since this is , shortest answer in bytes wins!

## Example Input and Output

You can also use diferrent formats of input, but you should only take the boardgame, the kid-A and the kid-B values.

Example 1:

```
board:  >---#<---X---<X<--#-$
kid-A:  [3,6,6,5,2,1]
kid-B:  [4,5,3,5,5,5]

output: A

```

Explaining:

```
>---#<---X---<X<--#-$     # both kids in position
B--A#<---X---<X<--#-$     # kid-A moved 3 to -
B--A#<---X---<X<--#-$     # kid-B moved 4 to # and returned home
B---#<---A---<X<--#-$     # kid-A moved 6 to X and will wait one round
B---#<---A---<X<--#-$     # kid-B moved 5 to < returned one to # and returned home
>--B#<---A---<X<--#-$     # kid-B moved 3 to -
>--B#<---X---<A<--#-$     # kid-A moved 6 to < returned one to X and will wait again
>---#<--BX---<A<--#-$     # kid-B moved 5 to -
>---#<---X--B<A<--#-$     # kid-B moved 5 to < returned one to -
>---#<---X--B<X<--#A$     # kid-A moved 5 to -
>---#<---X---<X<-B#A$     # kid-B moved 5 to -
>---#<---X---<X<-B#-$A    # kid-A moved 2 and won the game!

```

---

Example 2:

```
board:  >-<<<<<$
kid-A:  [1,2,3]
kid-B:  [5,5,4]

output: 0

```

---

Example 3:

```
board:  >-<-<#<-<-<-$
kid-A:  [5,4,2]
kid-B:  [1,1,1]

output: B

```

Explaining:

```
>-<-<#<-<-<-$     # both kids in position
>-<-<#<-<-<-$     # kid-A moved 5 to # returned home
AB<-<#<-<-<-$     # kid-B moved 1 to -
>B<A<#<-<-<-$     # kid-A moved 4 to < returned one to -
>B<A<#<-<-<-$     # kid-B moved 1 to < returned one to -
AB<-<#<-<-<-$     # kid-A moved 2 to # returned home
AB<-<#<-<-<-$     # kid-B moved 1 to < returned one to -

Current position: (A:0, B:1) output: B

```

# Answer
> 2 votes
## Perl, ~~188~~ 180 + 2 = 182 bytes

Wuhuu, got to use `goto`.

```
@q=/.(?!$)/g,next if$w=$e=!@q;for(@F){a:$w+=$_;$_=$q[$w];/</?($_=-1,goto a):/X/?$e++:/#/?$w=0:!$_&&last;$e++}$r+=$"lt$r?-$w:$w;$t+=$"lt$t?-$e:$e-1}{say$w>@q?$t<0?B:A:!$r?0:$r<0?B:A

```

Requires `-a` and `-E`|`-M5.010`:

```
$ echo $'>-<-<#<-<-<-<-$\n5 4 2\n1 1 1' | perl -M5.010 boardgame.pl
B

```

Somewhat ungolfed version:

```
#!/usr/bin/perl -a

# Read all but last char from the board into an array
@board = /.(?!$)/g,next if $pos = $turns = !@board;
for (@F) {
    a:
    $pos+=$_;
    $_=$board[$pos];
    /</?($_=-1,goto a):
    /X/?$turns++:
    /#/?$pos=0:
    # End of Game (Victory!)
    !$_&&last;

    $turns++
}
# Make sure '$pos_diff' and '$turns_diff' are not zero by checking against [:space:]
# ' ' is less than 0 on the ascii table
$pos_diff += $"lt$pos_diff ? -$pos : $pos;
$turns_diff += $"lt$turns_diff ? -$turns : $turns-1;
}{
    say $pos>@board?
            $turns_diff<0?B
            :A
        :
        !$pos_diff?0:
        $pos_diff<0?B:
        A

```

# Answer
> 1 votes
# ~~Haskell, 142~~

```
_![]=fail;g!(x:y)|x>length g=Just|1<2=g!fix(\f x->case(g!!x)of;'<'->f$x-1;'X'->(0:);'#'->map$(-)(-x);_->map(+x))x y;(g?a)b=(g!)a"A"<|>(g!)b"B"

```

Usage:

```
(?) "GAME" [kidA moves] [kidB moves]

```

Output:

```
(?) ">---#<---X---<X<--#-$" [3,6,6,5,2,1] [4,5,3,5,5,5]
Just "A"

```

---

**Edit:**
Jikes, I golfed it to death; it fails for the last example. I'll revive it shortly.

---
Tags: code-golf, board-game
---


title: What's the point?

text:
# Question
Title: What's the point?
Write a program or function that takes in two integers that represent the X and Y coordinates of a point on a Cartesian plane.

The input may come in any reasonable format as long as the X value comes before the Y. For example, `1 -2`, `(1,-2)`, `[1, -2]`, or `1\n-2` would all be fine for X = 1, Y = -2.

Print or return a single character string (followed by an optional trailing newline) that describes the location of the point in the plane:

* `1` if the point is in quadrant I
* `2` if the point is in quadrant II
* `3` if the point is in quadrant III
* `4` if the point is in quadrant IV
* `X` if the point is on the x-axis (lowercase `x` is not allowed)
* `Y` if the point is on the y-axis (lowercase `y` is not allowed)
* `O` if the point is on the origin (that's a capital letter "oh", not zero)

**The shortest code in bytes wins.** Tiebreaker goes to the higher voted answer.

## Test Cases

```
(1,-2) -> 4
(30,56) -> 1
(-2,1) -> 2
(-89,-729) -> 3
(-89,0) -> X
(0,400) -> Y
(0,0) -> O
(0,1) -> Y
(0,-1) -> Y
(1,0) -> X
(-1,0) -> X
(1,1) -> 1
(1,-1) -> 4
(-1,1) -> 2
(-1,-1) -> 3

```

# Answer
# Jelly, 14 bytes

```
Ṡḅ3ị“Y4X13X2YO

```

Try it online!

### How it works

```
Ṡḅ3ị“Y4X13X2YO    Main link. Input: [x, y]

Ṡ                 Apply the sign function to both coordinates.
 ḅ3               Convert the resulting pair from base 3 to integer.
                  Because of how base conversion is implemented in Jelly, this maps
                  [a, b] to (3a + b), even if a and b aren't valid ternary digits.
                  Therefore:
                      [0, 1]   ->  1
                      [1, -1]  ->  2
                      [1, 0]   ->  3
                      [1, 1]   ->  4
                      [-1, -1] -> -4
                      [-1, 0]  -> -3
                      [-1, 1]  -> -2
                      [0, -1]  -> -1
                      [0, 0]   ->  0
   ị“Y4X13X2YO    Retrieve the character at that index from the string.
                Indexing is 1-based and modular in Jelly, so 1ị retrieves the
                first character, -1ị the penultimate, and 0ị the last.

```
> 16 votes

# Answer
## Ruby, 35 bytes

```
->x,y{%w[OY X14 X23][x<=>0][y<=>0]}

```

Leveraging the "spaceship" (`<=>`) operator.

`x <=> 0` will return

* `0` if `x == 0`
* `1` if `x > 0`
* `-1` if `x < 0`

Hence,

* if `x == 0`, we return `'OY'[y<=>0]`. This is

+ `O` if `y == 0` (string indexing at `0`)
    + `Y` if `y != 0` (this is true because both `1` and `-1` will result in `Y` when indexing on this string, as `-1` refers to the last character in the string, which also happens to be the one at index 1)
* if `x > 0`, we return `'X14'[y<=>0]`. This is `X` if `y == 0`, `1` if `y > 0`, and `4` if `y < 0` (see explanation above).
* if `x < 0`, we return `'X23'[y<=>0]`.
> 11 votes

# Answer
# JavaScript, 44 bytes

```
(x,y)=>x?y?x>0?y>0?1:4:y>0?2:3:'X':y?'Y':'O'

```

```
f=(x,y)=>x?
            y?
                x>0?
                    y>0?1
                    :4
                :y>0?2:3
            :'X'
        :y?'Y':'O'

document.body.innerHTML = '<pre>' +
    'f(1,-2) -> ' + f(1,-2) + '<br>' +
    'f(30,56) -> ' + f(30,56) + '<br>' +
    'f(-2,1) -> ' + f(-2,1) + '<br>' +
    'f(-89,-729) -> ' + f(-89,-729) + '<br>' +
    'f(-89,0) -> ' + f(-89,0) + '<br>' +
    'f(0,400) -> ' + f(0,400) + '<br>' +
    'f(0,0) -> ' + f(0,0) + '<br>' +
    'f(0,1) -> ' + f(0,1) + '<br>' +
    'f(0,-1) -> ' + f(0,-1) + '<br>' +
    'f(1,0) -> ' + f(1,0) + '<br>' +
    'f(-1,0) -> ' + f(-1,0) + '<br>' +
    'f(1,1) -> ' + f(1,1) + '<br>' +
    'f(1,-1) -> ' + f(1,-1) + '<br>' +
    'f(-1,1) -> ' + f(-1,1) + '<br>' +
    'f(-1,-1) -> ' + f(-1,-1) + '<br>' +
'</pre>';
```
> 6 votes

# Answer
## ES6, 43 bytes

```
(x,y)=>"OYYX32X41"[3*!!x+3*(x>0)+!!y+(y>0)]

```

A whole byte shorter than all of those ternaries!
> 5 votes

# Answer
# Japt, ~~30~~ 22 bytes

```
"3Y2XOX4Y1"g4+3*Ug +Vg

```

Inspired by @Dennis' Jelly answer before he added an explanation. Test it online!

Fun fact: this would be two bytes shorter if I had added support for negative numbers in the `g` function for strings.

Another attempt, closer to the Jelly one (23 bytes):

```
"3Y2XOX4Y1"gNmg m+1 ¬n3

```

Sadly, incrementing a list costs 4 bytes...
> 3 votes

# Answer
# MATL, 22 bytes

```
'3X2YOY4X1'iZSQI1h*sQ)

```

This uses current release (10.2.1) of the language/compiler.

**Try it online!**

### Explanation

This shamelessly borrows the great approach in Dennis' answer.

```
'3X2YOY4X1'     % literal string. Will be indexed into to produce result
i               % input array of two numbers
ZS              % sign of each number in that array. Gives -1, 0 or 1
Q               % add 1 to produce 0, 1 or 2
I1h             % array [3 1]
*s              % multiply both arrays element-wise and compute sum
Q               % add 1. Gives a value from 1 to 9
)               % index into string. Display

```
> 2 votes

# Answer
# Pyth, 18 bytes

```
@"OY4X13X2Y"i._RQ3

```

Explanation:

```
                   - Autoassign Q = eval(input())
             ._RQ  - map(cmp, Q)
            i    3 - convert to base 3
@"OY4X13X2Y"       - "OY4X13X2Y"[^] (A lookup table)

```

Try it here.

Or the whole test suite
> 2 votes

# Answer
## Python 2, 75 bytes

```
lambda x,y,b=bool:[['OX','YO'][b(y)][b(x)],[[1,2],[4,3]][y<0][x<0]][b(x*y)]

```

Pretty straightforward.
> 1 votes

# Answer
# Mathematica 81 bytes

```
Switch[Sign@#,{1,-1},4,{1,1},1,{-1,1},2,{-1,-1},3,{0,0},"O",{_,0},"X",{0,_},"Y"]&

```

---

```
%/@{{1, -2}, {30, 56}, {-2, 1}, {-89, -729}, {-89, -0}, {0, 400}, {0, 0},{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}

```

> {4, 1, 2, 3, "X", "Y", "O", "Y", "Y", "X", "X", 1, 4, 2, 3}
> 1 votes

# Answer
# Retina, 52

This is a simple substitution-based method:

```
^0 0
O
^0.*
Y
.* 0
X
-.*-.*
3
^-.*
2
.*-.*
4
.* .*
1

```

Try it online. The extra `m``  at the start of some lines is only needed to test multiple inputs in one go, so are not counted in the score.

---

Previously I tried this more interesting approach, but its quite a bit longer (about 65 without the `m` modifiers):

```
[1-9]\d*
1
-1
2
(.) (.)
$1$*3$2$*1
3
111
m`^(.)*$
$#1
T`d`OYYX14X23

```
* substitute all non-zero numbers to `1`, leaving `-` signs in place
* Substitute `-1` with `2`
* Convert 1st and 2nd numbers unary with `3` and `1` respectively as the unary digits . This effectively gives 2 base3 digits, expressed in unary
* Convert to `3`s to `111`. This effectively gives the a single unary number that corresponds to each of the quadrants, axes and origin
* Convert the unary to one decimal digit
* Transpose the decimal digit to the appropriate output char.
> 1 votes

# Answer
# Pyth, 24

Too long, but perhaps an interesting approach:

```
?Q?sQ?eQh%/yPQ.n04\X\Y\O

```

The input must be specified as a complex number, e.g. `1-2j`. Basically a nested ternary to test:

* if input is zero - output `O`
* else if real part is zero - output `Y`
* else if imaginary part is zero - output `X`
* else calculate the complex phase, multiply by 2, integer divide by π, then mod and add to give the appropriate quadrant number.

Try it online.
> 1 votes

# Answer
# Octave, 34 bytes

```
@(p)['3X2YOY4X1'](sign(p)*[3;1]+5)

```

The old base-3 trick through vector multiplication (although I had to add 5 to account for 1-based array indices) plus some Octave indexing magic.

Input is a vector of the form `[1, -2]` (with or without the comma), so when assigned to a variable `w`:

```
>> w([1 -2])
ans = 4

```

Here it is on ideone.
> 1 votes

# Answer
# Java 8, 64 bytes

this is a lambda expression for a `BiFunction<Integer,Integer,String>`.

```
(x,y)->"OYYX14X23".charAt(3*(x>0?1:x<0?2:0)+(y>0?1:y<0?2:0))+"";

```

3 bytes could be saved by returning a `Character` instead of a `String` but i'm not completely sure if autoboxing will play nicely with the lambda.
> 1 votes

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


title: Write a radix sort

text:
# Question
Title: Write a radix sort
# Goal

As the title suggests, write a radix sort function (either MSB or LSB is fine) that accepts two parameters:

* an array of values of any type (you can assume that they are all of the same type / class, etc.)
* a function (or function pointer, depending on your language) that takes a single parameter of the same type as the objects given in the array and returns the coerced integer key of the object.

Implementation may mutate the array or operate out-of-place, but *must return the sorted array*.

### Tips

* If array indexing in your language is affected by the byte-size of each index, you can assume that the objects referenced in the array are pointers rather than values.
* If the size of an array pointed to in a function parameter cannot be determined in your language, then add another parameter to your radix sort signature, passing the size in bytes of your array, or number of elements in your array, whichever you prefer:

```
void *rsort(void *arr, size_t length, int(*key)(const void *));

```

## Bonus

A bonus reduction of 20% to your score will be given if your implementation memoizes the keys of the objects in the array so that the function provided only needs to be called once for each object in the array.

## Example Usage (and test-case)

Assuming an answer was provided in JavaScript, a test-case might look something like this:

```
/* note that this implementation will not be acceptable as a submission -
 * it is NOT a true radix sort
 */
function myFakeRadixSort(array, key) {
  return array.sort(function(a, b) {
    return key(a) - key(b);
  });
}

/* this will be used as an example key function -
 * you will not need to implement this
 */
function complexity(obj) {
  return JSON.stringify(obj).length;
}

var tree = {
  a: {
    b: {
      c: "a string",
      d: 12
    },
    e: ["an", "array"]
  },
  f: true,
  g: {
    h: null,
    i: {},
    j: {
      k: 500
    }
  }
};

/* another example key function
 */
function index(obj) {
  return JSON.stringify(tree).indexOf(JSON.stringify(obj));
}

var data = [];

/* this is a hack to traverse the object */
JSON.stringify(tree, function(key, value) {
  data.push(value);
  return value;
});

document.write(`<h2>Sorted by "complexity"</h2>`);
document.write(`<pre>${myFakeRadixSort(data, complexity).map(o=>JSON.stringify(o)).join`\n`}</pre>`);
document.write(`<h2>Sorted by "index"</h2>`);
document.write(`<pre>${myFakeRadixSort(data, index).map(o=>JSON.stringify(o)).join`\n`}</pre>`);
```

## tl;dr

Write a radix sort with this signature, or as close as possible to this signature:

```
void *rsort(void *arr, int(*key)(const void *));

```

## Leaderboards

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

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

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

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

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

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

**Shortest code in bytes wins!**

# Answer
> 1 votes
## Pyth, 6 bytes - 20% = 4.8

```
s.gykQ

```

This uses radix sort with base 2^64. Since all keys will be non-long positive integers, they are one digit long in base 2^64. We use `.g` to bucket the numbers, and `s` to flatten the resulting array. Calls to `y` are implicitly memoized.

Define the function `y` with L, which is a `lambda b`. For example:

```
Lab5        ## y = lambda b: abs(b-5)
s.gykQ

```

Less cheaty is this decimal LSB radix sort at **15 bytes - 20% = 12**:

```
us.ge/yk^THGyTQ

```

Which takes the last twenty decimal digits, plenty for 64-bit numbers.

Try it here.

# Answer
> 4 votes
## Haskell, ~~111~~ 89 bytes * 0.8 = 71.2

```
f%a=fst<$>iterate(\x->(even#x)++(odd#x))[(x,f x)|x<-a]!!64
f#x=[(i,j`div`2)|(i,j)<-x,f j]

```

Usage example (sort on the sum of the lists): `sum % [[1,2,3,4], [2,3,4,5], [1], [1,4,8], [9], [0]]` -\> `[[0],[1],[9],[1,2,3,4],[1,4,8],[2,3,4,5]]`.

Assuming the given functions maps to non-negative 64-bit integers.

This implements binary radix sort.

How it works:

```
           [(x,f x)|x<-a]    -- map each element x of the input list to a pair
                             -- (x,f x), so the given function f is used only once
   iterate (...) (...) !! 64 -- repeatedly apply one step of the radix sort and
                             -- take the 64th iteration
fst<$>                       -- remove the second element of the pair, i.e.
                             -- restore the original element

                             -- one step of the radix sort
\x->(even#x)++(odd#x)        -- partition the list in pairs with even and
                             -- odd second elements and divide the second
                             -- element of the pairs by 2. Re-concatenate

[(i,j`div`2)|(i,j)<-x,f j]   -- helper function: filter pairs where the second
                             -- element j satisfy predicate f. Adjust j.

```

Further calling examples:

```
length % ["Hello","World!","Golf"]
         -> ["Golf","Hello","World!"]

(fromEnum.last) % ["Strings","sorted","on","last","character"]
         -> ["sorted","on","character","Strings","last"]

maximum % [[1,2,3,4], [2,5,4], [5,5], [4], [6,2], [2,3]]
         -> [[2,3],[1,2,3,4],[4],[2,5,4],[5,5],[6,2]]

```

# Answer
> 2 votes
## ES6, 113 bytes - 20% = 90.4

```
(a,g)=>(s=(a,i)=>i?s(a.filter(x=>~x[1]&i).concat(a.filter(x=>x[1]&i)),i<<1):a)(a.map(x=>[x,g(x)]),1).map(x=>x[0])

```

Uses 2 as the radix. Ungolfed:

```
function rsort(array, key) {
    array = array.map(value => [value, key(value)]);
    // bit becomes zero when the bit falls off the left end
    for (bit = 1; bit; bit <<= 1) {
        zero = array.filter(pair => !(pair[1] & bit));
        one = array.filter(pair => pair[1] & bit);
        array = zero.concat(one);
    }
    return array.map(value => value[0]);
}

```

Test cases:

```
f=(a,g)=>(s=(a,i)=>i?s(a.filter(x=>~x[1]&i).concat(a.filter(x=>x[1]&i)),i<<1):a)(a.map(x=>[x,g(x)]),1).map(x=>x[0]);

/* example key function */
function complexity(obj) {
  return JSON.stringify(obj).length;
}

var tree = {
  a: {
    b: {
      c: "a string",
      d: 12
    },
    e: ["an", "array"]
  },
  f: true,
  g: {
    h: null,
    i: {},
    j: {
      k: 500
    }
  }
};

/* another example key function
 */
function index(obj) {
  return JSON.stringify(tree).indexOf(JSON.stringify(obj));
}

var data = [];

/* this is a hack to traverse the object */
JSON.stringify(tree, function(key, value) {
  data.push(value);
  return value;
});

document.write(`<h2>Sorted by "complexity"</h2>`);
document.write(`<pre>${f(data, complexity).map(o=>JSON.stringify(o)).join`\n`}</pre>`);
document.write(`<h2>Sorted by "index"</h2>`);
document.write(`<pre>${f(data, index).map(o=>JSON.stringify(o)).join`\n`}</pre>`);
```

---
Tags: code-golf, sorting
---


title: Inverse Champernowne Substrings

text:
# Question
Title: Inverse Champernowne Substrings
The Champernowne Constant is the irrational number 0.1234567891011... extending ad infinum.

We've done a question about it before. But this question is about its reciprocal, known as the Inverse Champernowne Constant. This is approximately 8.10000007.

Given a string of between one and three digits (every 3-digit string appears within the first 10,000 decimal places) inclusive, give the number of decimal places in the decimal portion of the Inverse Champernowne Constant that precede the first appearance of that string.

Builtins that perform this directly or generate approximations of either of these constants are forbidden, but builtins for arbitrary precision arithmetic are still permissible.

This is code golf, so the shortest program, in bytes, wins.

**Test cases:**

```
1 0
2 52
3 13
4 29
5 36
6 7
7 8
8 27
9 23
10 0
100 0
998 187
999 67
01 321
001 689
010 418

```

# Answer
> 3 votes
# MATL, 37 bytes

*Thanks to @AndrasDeak for his help with Octsympy's `vpa` function!*

```
'1/'1e4:"@V]N$h1e4H$Y$t32>)I0h)jXf1)q

```

*EDIT (June 11, 2016): due to changes in the language, replace `0` by `J` in the code. The link below includes that modification*

**Try it online!**

It takes a while in the online compiler (less than 1 minute).

```
'1/'        % literal string
1e4:        % array [1,2,...,1e4]
"           % for each number in that array
  @V        % push number and convert to string
]           % end loop
N$h         % concatenate all strings
1e4H$Y$     % compute 1/123456789101112... as a string with 1e4 significant digits
t32>)       % remove unwanted spaces and newlines in the output string
I0h)        % remove the first two characters ('8.')
j           % input string
Xf          % find indices of occurrences of input string within computed string
1)          % take first index
q           % subtract 1

```

# Answer
> 2 votes
## Ruby, ~~69~~ 67 bytes

```
->x{"#{1/BigDecimal.new(?.+[*1..9999]*'')}".index(x)-3}

```

Score: 55 source code bytes + 12 for the `-rbigdecimal` flag.

Pretty straightforward. Only weird part is that the `to_s` implicitly called by the `#{}` construction on `BigDecimal` returns

```
0.81000000670 [...] 3036E1

```

so it's necessary to subtract 3 to get the correct index.

# Answer
> 1 votes
# Python 2, 69 bytes

```
lambda s:str(10**30000/int("".join(map(str,range(3000))))).index(s)-1

```

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


title: Sort these bond ratings

text:
# Question
Title: Sort these bond ratings
## The task

The credit rating agencies assign ratings to bonds according to the credit-worthiness of the issuer, and the "Big Three" credit rating agencies use a similar (though not identical) tiered rating system. These have a clear, logical order - using the S&P tiers, AAA \> AA+ \> AA \> AA- \> A+ \> ... \> BBB \> B \> ... \> C. Moody's uses a similar system, but names their tiers differently (Aaa \> Aa1 \> Aa2 \> ... \> Baa1 \> ... \> C).

Your task is to design a program which takes as input a list of strings representing bond rating tiers and output the same list, sorted in descending order from the highest tier (AAA/Aaa) to the lowest tier (C).

## Input / Output

You may choose the format of the input (list, one per argument, CSV file). You may assume that every item in the input list is a *valid rating string* and that all rating strings in a list came from the *same rating agency*. Additionally, you may assume that none of the funky NA-style ratings such as "NR" or "WR" will be included - this is strictly from "Aaa/AAA" to "C". There may be duplicate ratings in the input list, and if found they should not be removed.

You may also choose the format of the output as is appropriate for your language, with the only restriction being that it should be outputting some standard text encoding like UTF-8 or ASCII.

## Rules and scoring

This is code golf, so lowest byte count wins, standard loopholes disallowed. Please specify what the input and output format is.

## Example program and test cases

The example Python program below can be used as a standard example of the correct sort order. The lists `Moody` and `SP` are the orderings to use.

```
Moody = ['Aaa', 'Aa1', 'Aa2', 'Aa3', 'A1', 'A2', 'A3',
         'Baa1', 'Baa2', 'Baa3', 'Ba1', 'Ba2', 'Ba3',
         'B1', 'B2', 'B3', 'Caa', 'Ca', 'C']

SP = ['AAA', 'AA+', 'AA', 'AA-', 'A+', 'A', 'A-',
      'BBB+', 'BBB', 'BBB-', 'BB+', 'BB', 'BB-',
      'B+', 'B', 'B-', 'CCC', 'CC', 'C']

test_cases = [
    (['Aa2', 'Aaa', 'Aa1'], ['Aaa', 'Aa1', 'Aa2']),
    (['AA', 'AA-', 'AA+'], ['AA+', 'AA', 'AA-']),
    (['Baa1', 'Ba1', 'A1', 'B1', 'Aaa', 'C', 'Caa', 'Aa1'],
     ['Aaa', 'Aa1', 'A1', 'Baa1', 'Ba1', 'B1', 'Caa', 'C']),
    (['BBB+', 'BB+', 'A+', 'B+', 'AAA', 'C', 'CCC', 'AA+'],
     ['AAA', 'AA+', 'A+', 'BBB+', 'BB+', 'B+', 'CCC', 'C']),
    (['B3', 'B1', 'B2'], ['B1', 'B2', 'B3']),
    (['B-', 'B+', 'B'], ['B+', 'B', 'B-']),
    (['B3', 'Caa', 'Aa1', 'Caa', 'Ca', 'B3'],
     ['Aa1', 'B3', 'B3', 'Caa', 'Caa', 'Ca']),
    (['B-', 'CCC', 'AA+', 'CCC', 'CC', 'B-'],
     ['AA+', 'B-', 'B-', 'CCC', 'CCC', 'CC'])
]

mdy_sort = lambda x: Moody.index(x)
sp_sort = lambda x: SP.index(x)

for l_in, l_out in test_cases:
    sort_key = mdy_sort if set(l_in).issubset(set(Moody)) else sp_sort
    assert sorted(l_in, key=sort_key) == l_out

```

### Test cases

In case the python-style test case formatting is inconvenient, I've output it as space-delimited input strings (grouped in two-line pairs input followed by output):

```
Aa2 Aaa Aa1
Aaa Aa1 Aa2

AA AA- AA+
AA+ AA AA-

Baa1 Ba1 A1 B1 Aaa C Caa Aa1
Aaa Aa1 A1 Baa1 Ba1 B1 Caa C

BBB+ BB+ A+ B+ AAA C CCC AA+
AAA AA+ A+ BBB+ BB+ B+ CCC C

B3 B1 B2
B1 B2 B3

B- B+ B
B+ B B-

B3 Caa Aa1 Caa Ca B3
Aa1 B3 B3 Caa Caa Ca

B- CCC AA+ CCC CC B-
AA+ B- B- CCC CCC CC

```

***Note****: I mention the "Big Three" but only specify Moody's and S&P here - the reason is that the third, Fitch, uses the same system as S&P when you don't take into account the NA-style ratings, so including Fitch would be redundant.*

# Answer
> 1 votes
## Pyth, 16 bytes

```
o+Xs}RGrN0N\z\,Q

```

We sort lexicographically by a key using @Neil's approach. Input and output are as lists; this does not mutate the list.

```
o+Xs}RGrN0N\z\,Q       Implicit: Q = input list
                        lambda N  (N is a bond rating)
       rN0               Convert N to lowercase
    }RG                  Map is-in G, the lowercase alphabet.
   s                     Sum the list of bools; the number of letters in N.
  X       N\z            Insert "z" at that position in N.
 +           \,          Append "," to the end.
                         This works because "," is between "+" and "-" lexicographically.
o              Q       Sort Q, using that lambda as a key.

```

Try it here. Test cases are all bond ratings of each rating scheme, with a duplicate thrown in.

# Answer
> 7 votes
## ES6, ~~71~~ 65 bytes

```
a=>a.sort((b,c)=>r(b)>r(c)||-1,r=s=>s.replace(/[^A-z]*$/,"z$&,"))

```

By inserting a `z` after the letters and suffixing a `,` we just have to sort the strings lexically.

Edit: Saved 6 bytes thanks to @user81655.

# Answer
> 2 votes
# Bash + GNU utilities, 45

Credit is due to @Neil for the approach.

```
sed s/$/e/|tr +-3 d-l|sort|tr -d e|tr d-l +-3

```

In my locale sort order, numbers sort before letters and `-` sorts before `+`. So these characters are transliterated into the alphabet range so they sort in the right order.

Try it online.

---
Tags: code-golf, sorting
---


title: The autopilot mode

text:
# Question
Title: The autopilot mode
A helicopter starting at the top left corner is descending (in a 2D space, for the purpose of this question) towards the ground. It has an autopilot mode and a manual mode.

The autopilot mode behaves as follows:

* If the space directly below is free, descend to it.
* Otherwise move a step left or right, totally at random. (It may move multiple steps in this manner.)

And it keeps repeating these two steps until it hits the ground. The manual mode is more smart and will find the optimal path to the ground, even if this requires moving upwards, or some skillful manoeuvring.

Your job is to determine if

1. The autopilot will pass in the given scenario,
2. The autopilot might fail in the given scenario,
3. The autopilot will fail, but the manual mode will pass, or
4. Both modes will fail (there is no valid path to the ground).

**Input**

* Given scenario as a 1d or 2d non-empty array, using two different characters to represent free and blocked spaces. Punctuation optional.
* Optional: dimensions of array

**Output**

One of four predefined characters indicating which of the cases has occurred.

**Sample data**

*Using 0 (empty) and 1 (blocked) in input, 1 2 3 4 in output (as numbered above)*

```
0 0 0 0
0 1 0 0
0 0 0 1
1 1 0 0

```

Output: `1`

```
0 0 1 0
1 0 0 1
0 0 0 0
0 1 1 0
0 0 0 1

```

Output: `2` (The helicopter will encounter the 1 in the fourth row, and it is possible it will trap itself at the end of row 5, if on autopilot mode)

```
0 0 0 1 0
0 1 1 0 0
0 1 0 0 0
0 0 0 1 0
1 1 1 1 0

```

Output: `3` (This requires moving upwards, so the autopilot fails)

```
1 0 0
0 0 0

```

Output: `4`

```
0 0 0 0 1
1 1 1 0 0
1 0 0 1 0
0 1 0 0 0
0 0 1 1 1

```

Output: `4`

# Answer
> 1 votes
# Ruby, 259

I had a lot of fun with this. Thank you! challenges tend to be excellent fun with interesting challenges. This assumes that "characters" in the question can be integers.

I think the major points of improvement here are:

1. The creation of `r`
2. The ghastly ternary abuse on the third line can likely be made into a more-ghastly, but terser something.

```
->a,h,w{f=->l,s=0,y=[0]{r=w-2<s%w ?w:1,1>s%w ?w:-1,w
v=(l ?r+[-w]:a[s+w]==0?[w]:r).map{|d|a[m=s+d]==0&&!y[m]?m:p}-q=[p]
a[s]>0?q:s/w>h-2?8:v[0]?v.map{|o|f[l,y[o]=o,y]}.flatten-q :r.any?{|i|a[s+i]<1}?p: !0}
g=f[p]
[8,g[0]&&g.all?,g.any?,f[8].any?,!p].index !p}

```

Ungolfed (slightly out of date, but real close):

```
# a is a one-dimensional array of 0s and 1s, h is height, w is width
->a,h,w{
  # f recursively walks the array and returns true/false/nil for each path.
  #    True means we can reach ground.
  #    False means we are stuck in a local minimum and cannot escape
  #    Nil means we reached a local dead-end and need to backtrack.
  # l: {true=>"manual", false=>"autopilot"}
  # s: the position index
  # y: an array of booleans - true-ish means we've visited that square before
  #         (this is to prevent infinite loops, esp in manual mode)
  f=->l,s=0,y=[0]{
    # d: all the legal deltas from s (maximally, that's [1,-1,w,-w], aka [LRDU])
    # r: but the right and left get tricky on the edges, so let's pre-calculate those
    #    we'll default to "down" if "left" or "right" are illegal
    r=[w-2<s%w ?w:1,1>s%w ?w:-1]
    # if manual, [LRDU]; if auto, and you can go down, [D]. else, [LR]
    d=l ?r+[w,-w]:a[s+w]==0?[w]:r
    # v: the legal deltas that you can go to from s (that is, unvisited and unblocked)
    v=d.map{|d|a[m=s+d]==0&&!y[m]?m:p}-[p]

    a[s]>0 ? [p]     # if we're currently blocked, return [nil] (this is only the case when a[0]==1)
      : s/w>h-2 ? !p # if we're at the bottom, return true
        : v[0] ?     # if we have a place to go....
        v.map{|o|f[l,y[o]=o,y]}.flatten-[p] # recurse with each step.
                                            # y[o]=o is a neat trick to make y[o] truthy and return o
          : r.any?{|i|a[s+i]==0} ? # otherwise, we have nowhere to go. If we could visit left/right, but have already been there
            p                      #    this is not a dead-end - return nil to remove this path
            : !!p                  # If we have a true dead-end (auto-mode with a local minimum), false
  }
  # g is the auto flight
  g=f[p]
  # finally, choose the first "true" out of:
  # 0: always 8.  Cuz why not 8?
  # 1: there is at least one auto path, and all are truthy
  # 2: any auto path is truthy
  # 3: any manual path is truthy
  # 4: true
  [8,g[0]&&g.all?,g.any?,f[!p].any?,!p].index !p
}

```

---
Tags: code-golf, grid, path-finding
---


# Question
Title: Golf Me a Random Dubstep of the Day List
Aside of nursing my child, Vitsy, and dabbling in the art of code golf, I also am an avid dubstep fan, listening to all the new dubstep that Monstercat puts out as regularly as I can. I also share a random dubstep of the day, though not regularly, in the Nineteenth Byte. This last bit is what this challenge relates to; so, without further ado, let me get to what you actually need to think about:

# The Challenge

You must generate a randomly sorted list of songs from this playlist in the following format:

```
<Title> - <Artist>: <link to the video>
```

# Rules

* The output list must update with the playlist provided, or every byte used counts as 2 (your score would be double your byte count).
* The output list must have no repeats.
* The output list must be given in the specified format.
* The output list must have all of the videos listed in the playlist provided.
* You may not use builtins for array shuffling (such as `Collections.shuffle(List<?> x)` from Java)
* You may not use the YouTube builtin shuffle mechanism (as this is not random).
* There are no limits on runtime.

# Example Output

```
Division - Ephixa: https://www.youtube.com/watch?v=M1mPFWhgYUM&list=PLF5C76212C58C464A&index=95
Wanna Know You (ft. Holly Drummond) - Direct: https://www.youtube.com/watch?v=6QWQfzYMJTs&list=PLF5C76212C58C464A&index=24
Edge of the World (feat. Becko) - Razihel & Xilent: https://www.youtube.com/watch?v=P0dQ55ZgNkw&index=4&list=PLF5C76212C58C464A
... until the final video ...
Way Too Deep - Grabbitz: https://www.youtube.com/watch?v=4T28WgVqdrA&index=8&list=PLF5C76212C58C464A
```

It may be worth perusing the YouTube API, but parsing the page with the playlist on it might save you some time.

# Answer
> 6 votes
# JavaScript, 532 536 538 582 bytes

Thanks to @ӍѲꝆΛҐӍΛПҒЦꝆ and @Quill for a whole bunch of bytes.

I did do a couple of things here which may not be 100% to the spec - If they aren't admissible please tell me and I'll fix them:

1. I shortened the YouTube URL
2. The shuffle is VERY weak, and is not considered in any way close to random.
3. There's a bit of whitespace due to the `join`.

I'd like to start by saying, to any JavaScript developers out there: I'm so sorry.

New version alternates captures to reduce on regex byte cost and strips some URL length, but sacrifices on alerts. Now instead of 3, you get like 20. Unfortunately the https on the URL's seem to be required or the page won't load, though that may be my setup :/.

This could possibly be improved with proper XML parsing and loops instead of weird recursion things with calls to other functions. I had fun taking advantage of the fact that `XMLHttpRequest` causes synchronous execution.

```
d="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&key={REALLY SUPER LONG GOOGLE API KEY HERE}",h=[];o=l=>{x=new XMLHttpRequest,x.open("GET",l,!1),x.send(0),j=x.responseText;y=`nextPageToken": "`;e(j)
j.includes(y)&&(q=j.split(y)[1].split('"')[0],o(d+"&pageToken="+q));h.sort(b=>.5-Math.random());alert(h.join `
`)}
e=v=>{for(r=/(title": "(.*)\[)|(oId": "(.*)")/g;null!==(m=r.exec(v));)a=m[2]+": https://youtu.be/"+r.exec(v)[4],z="] - ",a.includes(z)&&(a=a.split(z)[1]),h.push(a)}
o(d)

```

Replace the {REALLY SUPER LONG GOOGLE API KEY HERE} with your **39 character long** YouTube API key.

Ungolfed:

```
//Define base URL, sacrificing speed and pages for bytes
d = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&key={REALLY SUPER LONG GOOGLE API KEY HERE}";
h = [];
o = l => {
    //Grab API data
    x = new XMLHttpRequest();
    x.open("GET", l, false);
    x.send(0);
    j = x.responseText;
    //Set up a split since we use it twice
    y = `nextPageToken": "`;
    //At this point, jump off to the other function to deal with the output
    e(j);
    //If there are multiple pages of results, as we only get a couple from each API call to save bytes with URL's
    if (j.includes(y)) {
        //Get the ID for the next page
        q = j.split(y)[1].split("\"")[0];
        //Call again with an added parameter
        o(d + "&pageToken=" + q)
    }
    //Taking advantage of XMLHttpRequest forcing this as synchronous, so all the above happens first
    //Bad shuffle
    h.sort(b => .5 - Math.random())
    alert(h.join `
        `);
}
e = v => {
    //Regex for titles/ID's - Grabbitz doesn't fit the "[Genre] - Song - Artist" mould so we need a slightly longer regex
    r = /(title": "(.*)\[)|(oId": "(.*)")/g;
    //Since we know there's one title to one video, we can run them both at the same time
    while ((m = r.exec(v)) !== null) {
        //Build the string
        a = m[2] + ": https://youtu.be/" + r.exec(v)[4];
        z = "] - ";
        //That Grabbitz edge case ruining my day again, I'm glad it's a good track...
        if (a.includes(z)) {
            a = a.split(z)[1];
        }
        h.push(a);
    }
}
o(d)

```

# Answer
> 4 votes
# Julia, 590 bytes

```
using Requests
L="PLF5C76212C58C464A"
u="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=$L&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
R(x)=JSON.parse(readall(x))
F(x)=(s=x["snippet"];(s["title"],s["resourceId"]["videoId"],s["position"]))
g=get(u)
v=[F(i)for i=R(g)["items"]]
t="nextPageToken"
while haskey(R(g),t)
g=get("$u&pageToken="*R(g)[t])
v=[v;[F(i)for i=R(g)["items"]]]
end
for j=randperm(109)
t,d,i=v[j]
t=replace(t[13:end],r"\[Mo[\w ]+\]$","")
println(join(reverse(split(t," - ")),"- "),": https://www.youtube.com/watch?v=$d&list=$L&index=$(i+1)")end

```

This is a full program that uses Julia's `Requests` module to connect to the YouTube API, get the results, and print them to STDOUT. It will not likely win unless no one else participates. The X'd out portion is my Google Developer API key, which unfortunately is 39 characters.

Ungolfed:

```
using Requests

# Store the playlist ID
L = "PLF5C76212C58C464A"

# Store the initial API URL
u = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=$L&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

# Create a function for parsing JSON responses
R(x) = JSON.parse(readall(x))

# Create a function for constructing a tuple containing video information
F(x) = (s = x["snippet"]; (s["title"], s["resourceId"]["videoId"], s["position"]))

# Perform the initial API request
g = get(u)

# Collect all relevant returned information in an array
v = [F(i) for i = R(g)["items"]]

# Perform pagination to get all 109 items
t = "nextPageToken"
while haskey(R(g), t)
    g = get("$u&pageToken=" * R(g)[t])
    v = [v; [F(i) for i = R(g)["items"]]]
end

# Select the elements at random indices
for j = randperm(109)
    # Get the title, ID, and playlist index
    t, d, i = v[j]

    # Parse out the actual title
    t = replace(t[13:end], r"\[Mo[\w ]+\]$", "")

    # Print the current item
    println(join(reverse(split(t, " - ")), "- "),
            ": https://www.youtube.com/watch?v=$d&list=$L&index=$(i+1)")
end

```

# Answer
> 3 votes
# PHP, 594 bytes

Here's my submission using PHP.

```
<?php $t=[];$n='';while(1){$l='https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&pageToken='.$n.'&key={InsertKeyToContinueOnYourAdventure!!!}';$c=json_decode(file_get_contents($l),true);$t=array_merge($c['items'],$t);if(empty($c['nextPageToken']))break;else $n=$c['nextPageToken'];}$o=[];while(count($t)){$k=rand(0,count($t)-1);$s=$t[$k]['snippet'];echo preg_replace('/(?:\[.+\] - )?(.+) - (.+)/','${2} - ${1}',$s['title']).': https://www.youtube.com/watch?v='.$s['resourceId']['videoId'].'&list='.$s['playlistId'].'<br/>';array_splice($t,$k,1);}?>

```

It's probably not the best - or shortest - solution out there but it does the job. Before I go on, though, here's the ungolfed version:

```
<?php
$t = [];
$n = '';
while (1) {
    $l = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&pageToken=' . $n .'&key={InsertKeyToContinueOnYourAdventure!!!}';
    $c = json_decode(file_get_contents($l), true);
    $t = array_merge($c['items'], $t);
    if (empty($c['nextPageToken']))
        break;
    else
        $n = $c['nextPageToken'];
}
$o = [];
while (count($t)) {
    $k = rand(0, count($t) - 1);
    $s = $t[$k]['snippet'];
    echo preg_replace('/(?:\[.+\] - )?(.+) - (.+)/', '${2} - ${1}', $s['title']) . ': https://www.youtube.com/watch?v=' . $s['resourceId']['videoId'] . '&list=' . $s['playlistId'] . '<br/>';
    array_splice($t, $k, 1);
}
?>

```

I really feel like the regular expression can be improved - both in size and quality. Also, I couldn't think of a better way to break the first while other than that ugly if-else statement. Maybe the while statement could be handled better. I don't know. It's 1:15 am here and I'm half asleep.

Looking at the other answers, it seems that PHP probably isn't ideal for this due to its long function names. Still, file\_get\_contents() was pretty helpful and cut down a lot of request handling. I opted to use that instead of file() since it made decoding the request easier. I also did find a way to reduce some code around around that if-else statement, but the result would throw one notice when there was no 'nextPageToken' given on the last HTTP request. I suppose if you wanted to turn error reporting off then it could be possible, but I felt like that would be cheating. For those who are curious, the ungolfed if-else would look like this:

```
if ($d = $c['nextPageToken']))
    break;
else
    $n = $d;

```

Edit: I just realised that if this were to be run from a console I could reduce the size by 11 bytes (removing php tags + replacing br/ tag with \n). Oh well, at least's more readable on a browser IMHO. I'll just leave it for now.

> First code golf! Woooo! Now I must sleep. Good night, y'all!

---
Tags: code-golf, random, internet
---


title: Challenge about advacado

text:
# Question
Title: Challenge about advacado
*Inspired by this. No avocados were harmed in the making of this challenge.*

Hello I have challenge I need help juic an avocado so I need program to tell me how long to juic avocad for

Observe this ASCII art avocado:

```
    ######
   #      #
   # #### #
  #  # p# #
  ## #### #
   #      #
    ######

```

This avocado consists of an exterior of `#`s (specifically the first and last sequences of `#`s on each line) and a pit (a shape of `#`s in the avocado that does not touch the avocado exterior).

Through rigorous experiments on these ASCII art avocados I have discovered the following:

```
avocado juice in fluid ounces = number of spaces inside avocado but outside pit (the pit is marked with a p in the example) + 2 * number of spaces inside pit

time to juice avocado in minutes = 13 * number of spaces inside pit

```

For example, this avocado will take 26 (2 spaces inside pit * 13) minutes to juice and will give 23 (19 spaces inside avocado but outside pit + 2 * 2 spaces inside pit) fl oz of juice.

## Challenge

Given an input of **exactly one** ASCII art avocado such as the one above that consists of only `#` and whitespace, output the amount of time in minutes it will take to juice it and the amount of juice it will produce in any order.

You may assume that the input avocado will always have exactly one pit and both the avocado and the pit will always be closed. The pit and avocado will always be connected, and any subset of the pit will be connected as well. The avocado and the pit will always be convex. Note that the avocado exterior may be arbitrarily thick.

## Sample Inputs and Outputs

```
    ######
   #      #
   # #### #
  #  #  # # -> 26 23
  ## #### #
   #      #
    ######

   #######
  #       #
  #  ###   ##
  #  #  #   # -> 26 35
  #   ##   #
  #        #
  ##########

```

This is , so shortest code in bytes wins.

# Answer
# Pyth, ~~59~~ 51 bytes

```
*Ksm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z13+-/s.sR\ .zdK*2K

```

Try it here!

Outputs the time to juic the advacado (totally correct english) first and on the next line the amount of juic.

## Explanation

### Code - Overview

```
*Ksm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z13+-/s.sR\ .zdK*2K # .z=list of all input lines

                    fq4l:T"#+"4.z                   # Get the pit-lines
   m/.s.s.sd\ \#\ \                                 # Map the pit-lines to the whitespace amount
 Ks                                                 # Sum the amount of pit-spaces and assign to K
*                                13                 # Print the juic time
                                     /s.sR\ .zd     # Count all whitespaces in the advacado
                                    -          K    # Subtract the pit size from it
                                   +            *2K # Do the Rest of the amount calcluation and print it

```

*Detailed explanations of the size calculation parts see below.*

### Getting the advacado size

Let's look at this one:

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

```

First the leading and trailing whitespaces get removed. After that we wrap everything in one line, which results in this string:

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

```

This contains all whitespaces in the advacado, so we just have to count them (the advacado will always be convex, so this works for all valid inputs). This number still contains the spaces in the pit, but for the juic amount calculation we only need the spaces in the fruit without the pit-spaces. So we need to calculate them too.

**The code for that explained in detail:**

```
/s.sR\ .zd   # .z=list of all input lines

  .sR\ .z    # strip spaces from every input line
 s           # Concatenate all lines
/        d   # Count all spaces

```

### Getting the pit size

This is a bit trickier. First we remove the lines which don't contribute to the pit size. This is done by filtering out all lines that have less than 4 groups of hashes (using the regex `#+` and counting its matches). In the example above only one line will survive this process:

```
  #  #--# #

```

The spaces I marked with a `-` here are the ones we need to count. So we just strip spaces, then hashes and then spaces again which leaves us with this:

```
#  #

```

There we just have to count the spaces. We do all that for every line which survived the filtering process, sum everything and we are done. The rest is trivial math.

**The code for that explained in detail:**

```
sm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z   # .z=list of all input lines

                  f          .z   # filter the input
                     l:T"#+"4     # length of the matches for the regex `#+`
                   q4             # if there are 4 groups of hashes its a pit line
 m                                # map the pit lines to...
  /             \                 # The occurences of spaces in..
   .s.s.sd\ \#\                   # ...the stripped pit line (see explanation above)
s                                 # Sum all amounts of spaces in the pits

```
> 6 votes

# Answer
# Retina, 70

* 25 bytes saved thanks to @FryAmTheEggman and @randomra

```
T` `i`(?<=# +#+) *(?=#+ +#)
T` `f`# +#
i
13$*iff
((i)|(f)|\W)+
$#2 $#3

```

Try it online.
> 5 votes

# Answer
## Python, ~~141~~ 119 bytes

```
import sys
s=str.strip;l=len;o=i=0
for x in sys.stdin:x=s(s(x),'#');y=s(x);o+=l(x)-l(y);i+=l(s(y,'#'))
print o+2*i,13*i

```
> 3 votes

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


title: Sort these James Bond ratings

text:
# Question
Title: Sort these James Bond ratings
# Introduction

My grandpa is a fan of James Bond, but he is always unsure on how to rank his favourite actors. As such, he is always making lists, which is a lot of work. He asked me to produce a program that will make his life easier, but I do not have time for that, I have to work! So I will count on you guys.

# Challenge

The challenge is simple. The input will consist of a list, in the following format:

`<number> <space> <actor's name> <newline>`

Your task is to sort them based on the **number** at the beginning of the line, starting from the last, and ending with the first. All numbers should be removed.

However, my grandpa sometimes makes mistakes. As such, you will need to validate the data. If one of the names on the list doesn't refer to one of the actors who played Bond, you need to discard it. In case of repetitions, repeats should be removed, and the name should maintain the lowest weight it was associated with (example #3).

There is no limit to how many lines there may be.

The output only needs to be a list of some sort, whether it is an array, a comma separated string, just values separated by spaces, or something else entirely, i.e.

`Pierce Brosnan, Sean Connery, David Niven`

A trailing newline or space is allowed.

# Example Input and Output

Input:

> 1 Sean Connery
>
> 2 Emma Watson
>
> 5 Timothy Dalton
>
> 4 Roger Moore
>
> 3 Daniel Craig

Output:

> Timothy Dalton, Roger Moore, Daniel Craig, Sean Connery

Input:

> 2 Timothy Dalton
>
> 4 George Lazenby
>
> 5 George Lazenby
>
> 3 Bob Simmons

Output:

> George Lazenby, Bob Simmons, Timothy Dalton

Input:

> 3 Sean Connery
>
> 2 Pierce Brosnan
>
> 1 Sean Connery

Output:

> Pierce Brosnan, Sean Connery

As this is a code golf, shortest code (in bytes) wins!

# Appendix

List of actors who played the role of Bond:

* Barry Nelson
* Bob Simmons
* Sean Connery
* Roger Moore
* David Niven
* George Lazenby
* Timothy Dalton
* Pierce Brosnan
* Daniel Craig

# Answer
> 2 votes
# Pyth, ~~136~~ 132 bytes

```
_{mtcd\ f}stcTdc"BarryNelson BobSimmons SeanConnery RogerMoore DavidNiven GeorgeLazenby TimothyDalton PierceBrosnan DanielCraig"dS.z

```

Try it here!

### Explanation

```
_{mtcd\ f}stcTdc"BarryNelson BobSimmons ..."dS.z   # .z=list of all input lines
                                             S.z   # Sort input ascending
        f                                          # filter sorted lines with T being the current line
            cTd                                    # Split a line on spaces
          st                                       # Dicard the number and join first and last name
               c"BarryNelson BobSimmons ..."d      # Split the bond actor list on spaces...
         }                                         # only keep the lines which are in the actor list
   mtcd\                                           # remove the number from the filtered lines
_{                                                 # Remove duplicates from the mapping result and reverse the result

```

# Answer
> 12 votes
# Retina, ~~201 197~~ 191

```
\d+
$0$*1
G`^1+ (Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$
+`\b((1+)\D*)¶(\2.+)
$3¶$1
+s`1+(\D+)¶(.*\1)
$2
1+

```

Try it online!

6 bytes saved thanks to Martin!

Whee, bubble sort with regex. Note that ten bytes are spent doing decimal to unary conversion at the beginning, if unary input is OK then that isn't needed. Also, if numbers can't be in people's names, then a couple more bytes can be saved by moving the line that removes non-Bond actors to the end and removing the `1+` (untested with `\D` version).

### Explanation:

A Retina program is made up of several stages, so I will explain each stage separately.

Stage 1:

```
\d+
$0$*1

```

Replaces the numbers in the input with unary. This uses Retina's special replacement token: `$*` which repeats the character after a number of times equal to the preceding token's base 10 value.

Stage 2:

```
G`^1+ (Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$

```

The stuff before a ``` in a stage changes the mode being used. This turns on grep mode, which means that each line that doesn't match the regex is discarded. The anchors are necessary to prevent near matches from slipping by.

Stage 3:

```
+`\b((1+)\D*)¶(\2.+)
$3¶$1

```

This is the sorting stage. The `+` in the mode signifies that this stage should be repeated until the replacement makes no change when applied (i.e. we reach a fixed point). The regex finds a word boundry, followed by some number of `1`s and then all the rest of the line up to the newline. Then, if the next line has more `1`s than it, the regex will match and we swap the lines.

Stage 4:

```
+s`1+(\D+)¶(.*\1)
$2

```

This stage uses the `+` mode again, but also uses `s` to make the `.` meta-character also match newlines. This removes duplicate lines, by matching for exact duplicates after the `1`s and capturing the stuff after the first duplicate to replace the whole match with it. This will work without needing to consider the order of tie breaking, because the names are already sorted appropriately, with the larger numbers above, therefore we will always keep the smaller values.

Stage 5:

```
1+

```

Really simple one here, everything is in order, except we have a bunch of `1`s in front of our Bonds, so we replace them and the space after them with nothing.

# Answer
> 6 votes
## TSQL 426 bytes (includind data + input)

Golfed solution:

```
create table A(Name varchar(99))insert into A values('Barry Nelson'),('Bob Simmons'),('Sean Connery'),('Roger Moore'),('David Niven'),('George Lazenby'),('Timothy Dalton'),('Pierce Brosnan'),('Daniel Craig')declare @I as table (R int, N varchar(99))insert into @I values(3,'Sean Connery'),(2,'Pierce Brosnan'),(1,'Sean Connery')select N from(select N,min(R) R from @I where N in (select N from A) group by N) x order by R desc

```

Try it here

SQL excels (no pun intended) in this kind of task: relating sets, ordering, cutting off duplicates etc.

All you need is to create and populate a table of Actors like this:

```
create table Actor (Name varchar(99))
insert into Actor values
 ('Barry Nelson')
,('Bob Simmons')
,('Sean Connery')
,('Roger Moore')
,('David Niven')
,('George Lazenby')
,('Timothy Dalton')
,('Pierce Brosnan')
,('Daniel Craig')

```

Now if we use a table-variable as input we just need to get the intersection of both sets. Removing duplicates and ordering in SQL are really easy.

Example 1:

```
declare @Input as table (Rnk int, Name varchar(99))
insert into @Input values
 (1,'Sean Connery')
,(2,'Emma Watson')
,(5,'Timothy Dalton')
,(4,'Roger Moore')
,(3,'Daniel Craig')

select Name
from
(
    select Name, min(Rnk) as R
    from @Input
    where Name in (select Name from Actor)
    group by Name
) x
order by R desc

```

Example 2:

```
declare @Input as table (Rnk int, Name varchar(99))
insert into @Input values
 (2,'Timothy Dalton')
,(4,'George Lazenby')
,(5,'George Lazenby')
,(3,'Bob Simmons')

select Name
from
(
    select Name, min(Rnk) as R
    from @Input
    where Name in (select Name from Actor)
    group by Name
) x
order by R desc

```

The golfed version is just the full thing for example input 3

As a plus this SQL can work for older DBMS versions (even be rewrite to ANSI SQL) and run without problem in older computers than most languages.

# Answer
> 5 votes
# Perl, ~~242~~ ~~179~~ 217 bytes

```
print reverse grep{/^(Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$/&&!$s{$_}++}map{s/\d+ //;$_}sort{($a=~/(\d+)/)[0]<=>($b=~/(\d+)/)[0]}<>;

```

Nicer formatted version, with comments:

```
print
     # reverse ranking order
     reverse
     # filter entries...
     grep {
         # only actual bonds
         /^(Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$/
         # only new bonds
         && !$s{$_}++
     } map {s/\d+ //;$_}         # remove leading digits+space
     # sort according to embedded numbers
     sort {($a=~/(\d+)/)[0] <=> ($b=~/(\d+)/)[0]}
     <>;                        # slurp input as list (list context)

```

Most of the size is the list of Bonds; I can't find a nice way of compressing that regex without allowing false positives.

# Answer
> 4 votes
# Python 2, 250 bytes:

```
lambda I:zip(*sorted({k:v for v,k in[x.split(' ',1)for x in I.split('\n')]if k in'Barry Nelson,Bob Simmons,Sean Connery,Roger Moore,David Niven,George Lazenby,Timothy Dalton,Pierce Brosnan,Daniel Craig'.split(',')}.items(),key=lambda t:-int(t[1])))[0]

```

Demo:

```
>>> L = ["Barry Nelson",
...     "Bob Simmons",
...     "Sean Connery",
...     "Roger Moore",
...     "David Niven",
...     "George Lazenby",
...     "Timothy Dalton",
...     "Pierce Brosnan",
...     "Daniel Craig"]

>>> I="""2 Timothy Dalton
... 4 George Lazenby
... 5 George Lazenby
... 3 Bob Simmons"""
>>> F(I,L)
('George Lazenby', 'Bob Simmons', 'Timothy Dalton')

>>> I = """1 Sean Connery
... 2 Emma Watson
... 5 Timothy Dalton
... 4 Roger Moore
... 3 Daniel Craig"""
>>>
>>> F(I,L)
('Timothy Dalton', 'Roger Moore', 'Daniel Craig', 'Sean Connery')

```

# Answer
> 2 votes
## PowerShell v3+, ~~227~~ 219 bytes

```
$a=$args-split"`n"|sort|%{$c,$b=-split$_;$b-join' '}|?{$_-in('Barry Nelson,Bob Simmons,Sean Connery,Roger Moore,David Niven,George Lazenby,Timothy Dalton,Pierce Brosnan,Daniel Craig'-split',')}|select -u
$a[$a.count..0]

```

<sub>121 bytes of that is just the list of actors ...</sub>

Takes input `$args` and `-split`s it on newlines with ``n`. Pipe that to `sort`, which will sort the entries numerically ascending, which is OK for now. We pipe those to a foreach loop `|%{...}`, each iteration take the entry, `-split` it on spaces, then `-join` the second half back together with a space (i.e., stripping the numbers off the beginning). Those (ascending) sorted names are now left on the pipeline. We pipe those through a where with `?` that ensures they're `-in` the approved list of actors. Finally, we `select` only the `-u`nique entries, which for duplicates will select the first one it encounters (i.e., the lowest-weighted one) and discard the rest. We store the resultant array of names into `$a`.

So, now we've got a sorted ascending list of actors. Since the challenge requires descending, we do an in-place reversal operation on `$a` by indexing from `$a.count` down to `0`.

### Example

```
PS C:\Tools\Scripts\golfing> .\sort-these-james-bond-ratings.ps1 "1 Sean Connery`n2 Emma Watson`n5 Daniel Craig`n4 Roger Moore`n3 Daniel Craig"
Roger Moore
Daniel Craig
Sean Connery

```

<sub>Edit -- don't need to use \[array\]::Reverse() when indexing will do</sub>

# Answer
> 2 votes
# Python ~~309~~ 286 bytes

```
import sys
i='Barry Nelson.Bob Simmons.Sean Connery.Roger Moore.David Niven.George Lazenby.Timothy Dalton.Pierce Brosnan.Daniel Craig'.split('.')
print ', '.join(i.pop(i.index(x)) for x in zip(*sorted((x.strip().split(' ',1) for x in sys.stdin),None,lambda x:int(x[0]),1))[1] if x in i)

```

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

```
s=>s.split`
`.sort((a,b)=>(p=parseInt)(a)
l.replace(/\d+ /,"")).filter(l=>!p[l]&/^(Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$/.test(p[l]=l))

```

## Explanation

```
var solution =

s=>
  s.split`
`
  .sort((a,b)=>                 // sort the list by the number
    (p=parseInt)(a)
l.replace(/\d+ /,"")) // remove the number at the beginning of each line
  .filter(l=>
    !p[l]&                      // remove duplicates

    // Bond actor regex
    /^(Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$/

    .test(p[l]=l)               // test for bondness and add the line to p
  )
```

```
<textarea id="input" rows="6" cols="40">1 Sean Connery
2 Emma Watson
5 Timothy Dalton
4 Roger Moore
3 Daniel Craig</textarea>

<button onclick="result.textContent=solution(input.value)">Go</button>

```

---
Tags: code-golf, string, sorting
---