title: Some ASCII art for N64's 20th B-Day

text:
# Question
Title: Some ASCII art for N64's 20th B-Day
The official release of the Nintendo 64 in North America was on September 29, 1996.\[1\] I figured that this anniversary deserved an ASCII art challenge. There's one small twist though, you have to output a different ASCII art for each of three different inputs.

If the input is `1`, output this ASCII art of an N64 Controller: (source)

```
                 | |
             _,.-'-'-.,_
      ______|           |______
   ,-'      |  NINTENDO |      `-.
 ,'   _                          `.
/   _| |_                     (^)   \
|  |_   _|                  (<) (>) |
\    |_|         (S)     (B)  (v)   /
|`.              ___       (A)    ,'|
|  `-.______   ,' _ `.   ______,-'  |
|      |    `. | (_) | ,'    |      |
|      |      \`.___,'/      |      |
|      |      |       |      |      |
|      /      |       |      \      |
\     /       |       |       \     /
 `._,'        \       /        `._,'
               \     /
                `._,'

```

If the input is `2`, output this ASCII art of the N64 logo:(source)

```
                  .-"-.
               .-"     "-.
              /"-.     .-|
             /    "-.-"  |
            /      /     |
   .-"-.   /      /      |       .-"-.
.-"     "-/      /       |    .-"     "-.
|-.     .-"\    /        |   /"-.     .-|
|  '-.-"    \  /         | /'    "-.-"  |
|     \      \/   .-"-.  /'        |    |
|      \      \.-"     "-.         |    |
|       \      |-.     .-"\        |    |
|        \     |  "-.-"    '\      |    |
|         \    |    |        '\    |    |
|    |\    \   |    |          '\  |    |
|    | \    \  |    |            '\|    |
|    |  \    \ |    |    :\.            |
|    |   \    \|    |    |  \.          |
|    |    \         |    |    \.        |
'-.  |  .-"\        |    |    '.\.    .-'
   "-|-"    \       |    |      "-\.-"
             \      |    |
              \     |    |
               "-.  |  .-'
                  "-|-"

```

Finally, if the input is `3`, outout this ASCII art of a console and TV: (source)

```
              o
     o       /
      \     /
       \   /
        \ /
   ______________
  |.------------.|
  ||            ||
  ||            ||
  ||            ||
  ||            ||
  ||____________||_
  |OO ....... OO | `-.
  '------_.-._---' _.'
   _____||   ||___/_
  /  _.-|| N ||-._  \      .-._
 / -'_.---------._'- \    ,'___i-i___
/_.-'_  NINTENDO _'-._\  ' /_+  o :::\
|`-i /m\/m\|\|/=,/m\i-'| | || \ O / ||
|  |_\_/\_/___\_/'./|  | | \/  \ /  \/
`-'              '-.`-'  ,      V
                    `---'

```

## Rules:

* Input may be either as a number or a string/char.
* You may have any amount of leading or trailing spaces and trailing or leading newlines. (Output must be aligned correctly though)
* Your submission may be either a full program or a function.
* No retrieving the ASCII art from the internet.

This is , so smallest byte count wins.

# Answer
> 6 votes
# Javascript ES6, 1175 bytes

Using a simple Run Length Encoding to encode just the spaces.

```
let F=

  z=>[(f=d=>d.replace(/\d+/g,e=>' '.repeat(e)))(`17|1|
13_,.-'-'-.,_
6______|11|______
3,-'6|2NINTENDO1|6\`-.
1,'3_26\`.
/3_|1|_21(^)3\\
|2|_3_|18(<)1(>)1|
\\4|_|9(S)5(B)2(v)3/
|\`.14___7(A)4,'|
|2\`-.______3,'1_1\`.3______,-'2|
|6|4\`.1|1(_)1|1,'4|6|
|6|6\\\`.___,'/6|6|
|6|6|7|6|6|
|6/6|7|6\\6|
\\5/7|7|7\\5/
1\`._,'8\\7/8\`._,'
15\\5/
16\`._,'`),f(`18.-"-.
15.-"5"-.
14/"-.5.-|
13/4"-.-"2|
12/6/5|
3.-"-.3/6/6|7.-"-.
.-"5"-/6/7|4.-"5"-.
|-.5.-"\\4/8|3/"-.5.-|
|2'-.-"4\\2/9|1/'4"-.-"2|
|5\\6\\/3.-"-.2/'8|4|
|6\\6\\.-"5"-.9|4|
|7\\6|-.5.-"\\8|4|
|8\\5|2"-.-"4'\\6|4|
|9\\4|4|8'\\4|4|
|4|\\4\\3|4|10'\\2|4|
|4|1\\4\\2|4|12'\\|4|
|4|2\\4\\1|4|4:\\.12|
|4|3\\4\\|4|4|2\\.10|
|4|4\\9|4|4\\.8|
'-.2|2.-"\\8|4|4'.\\.4.-'
3"-|-"4\\7|4|6"-\\.-"
13\\6|4|
14\\5|4|
15"-.2|2.-'
18"-|-"`),f(`14o
5o7/
6\\5/
7\\3/
8\\1/
3______________
2|.------------.|
2||12||
2||12||
2||12||
2||12||
2||____________||_
2|OO1.......1OO1|1\`-.
2'------_.-._---'1_.'2
3_____||3||___/_
2/2_.-||1N1||-._2\\6.-._
1/1-'_.---------._'-1\\4,'___i-i___
/_.-'_2NINTENDO1_'-._\\2'1/_+2o1:::\\
|\`-i1/m\\/m\\|\\|/=,/m\\i-'|1|1||1\\1O1/1||
|2|_\\_/\\_/___\\_/'./|2|1|1\\/2\\1/2\\/
\`-'14'-.\`-'2,6V
20\`---'`)][z-1]

G=_=>h.innerHTML = F(a.value)

h.innerHTML = F(1)
```

```
<input id=a onchange="G()" type="number" value="1"></input>
<pre id=h>
```

# Answer
> 3 votes
## JavaScript (ES6), ~~907~~ ~~904~~ 903 bytes

Implements a compression by successive substitutions of the most frequent sub-strings.

This can be compressed significantly more (down to about 850 bytes) by assuming Windows-125x encoding and using replacement characters in the range `0xA0` \- `0xFF`. But the result is just ugly. :-)

```
let f =

n=>[...Array(78)].map((_,i)=>s=~":<=>ABNOSV\\^_`imov|".indexOf((c=String.fromCharCode(125-i)))?s:s.split(c).join(['\\','NINTENDO',`
`][c]||"9|XsD'RE405398T08kU8K0\"-G/'0|W7/;_E/C62G5|557970..-\"6_ /|52F8@04D\"`.-','??7 25\";7|3 3|4 .-662|---. |4|43__4433  ".substr(k+=2,2)),s="c99JE_,zP;,_27fX39fe,PH3197`;2 MG_cwQ2/G_|9_cE(^)G0@F_G_Xw(<) (>)9208_X (S)E(B)3(v)n@Q57ZK(A)4M|@3`;fGM _ QGf,PF@H4Q9 (_)9 M8H@HaQZM/HH@HHbHH@jHbaH20gbbqg2 Q_M50K/5Q_MJqgJ5Q_M~c3DIJKyIJjIED|Jg4I[FJ4/j49eDInjHKDI2yp/jb4yI@;ERT/dnIED|@3';[x3/59Y'4I[F@E0a/GDI3/'dUaayI59UqH;ER0dU5T93I[4lHU5 0885l8rt3uwlFr tF854l|r3tu4:0.5rGt|8830.5F@8x5ux.d2';F3R0d84'.0.4zep|[xb87p0RJE0H8J7TuJKIF3zJwp|[~57o2EoK/2ag2qnJ0YeCCfW.LL?-;k{{{{|CCC||_WOO ]]]. OO9 `;23'L?_.h?P _.'eC_||3}Z/_23/3_D|| N}h307.h2Y P_.LLh'- TMZi-iZ2/_z_31 _'h03'Y_+3o :::0@`-iYm0/m0|0|/=,/m0iP|9} 0 OY}@F_0_/0_/Z0_/'./|F9 0/30Y30/2`P57';`P3,7VJ54`?P",k=-2)&&s.split`~`[n-1]

console.log(f(1));
console.log(f(2));
console.log(f(3));
```

### Making-Of

The above JS was generated with the following PHP script, where `"n64.txt"` is basically the concatenation of the 3 original pictures separated with `~` characters.

```
<?php
  $str = file_get_contents("n64.txt");

  // ignore line-breaks between 2 pictures
  $str = str_replace("~\n", "~", $str);

  // replace backslashes with 0's
  $str = str_replace("\\", "0", $str);

  // replace 'NINTENDO' with 1's to have more uppercase letters
  // available as replacement characters
  $str = str_replace("NINTENDO", "1", $str);

  // replace line-breaks with 2's
  $str = str_replace("\n", "2", $str);

  // $skipped is the list of characters that can't be used as replacement
  // characters (backslash + anything existing in the original string)
  $skipped = '';

  // $dic is the replacement dictionary
  $dic = '';

  for($i = 0; $i < 75; $i++) {
    // $r = current replacement character
    $r = chr(51 + $i);

    // can we use it?
    if($r == "\\" || strpos($str, $r) !== false) {
      $skipped .= $r;
      continue;
    }

    // look for the most frequent 2-character sub-string
    $count = array();

    for($n = 0; $n < strlen($str) - 1; $n++) {
      $s = substr($str, $n, 2);
      $count[$s] = isset($count[$s]) ? $count[$s] : 0;
      $count[$s]++;
    }

    asort($count);
    $keys = array_keys($count);
    $s = array_pop($keys);

    // add it to the dictionary
    $dic = $s.$dic;

    // replace all occurences with the replacement character
    $str = str_replace($s, $r, $str);

    printf("'%s' => '%s' %d\n", $s, $r, strlen($str));
  }

  // generate JS
  file_put_contents(
    "n64.js",
    sprintf(
      "n=>[...Array(78)].map((_,i)=>".
      "s=~\"%s\".indexOf((c=String.fromCharCode(125-i)))?s:".
      "s.split(c).join(['\\\\','NINTENDO',`\n`][c]||\"%s\".substr(k+=2,2)),".
      "s=\"%s\",k=-2)".
      "&&s.split`~`[n-1]",
      str_replace("\\", "\\\\", $skipped),
      str_replace('"', '\"', $dic),
      $str
    )
  );
?>

```

# Answer
> 2 votes
# Racket, 1059 bytes

```
(require file/gunzip net/base64)(display((λ(o)(gunzip-through-ports(open-input-bytes(base64-decode(list-ref'(#"H4sICMov7lcCAzEAdZExDsMgDEV3TuENkAhcoKrUqh2ypEM7osIpOvnwtTEkgaaOFIvvZ8efAAyBgKoTkvOTpse7VAupBO6bROK6m3QbBMu8vO7L7QGVzZNX4Lie4G9krwITtMgxZd6W3lEhCNFt0piTBXO25CXKfhtjnlbylbL58CEozL4fQG4afym808hfJAvitUjkozSKVKwXqvpnM5RNokXEd7uJniI3mcc6HTp1pBCOjisVDqnYqLiHRqpiQdHKyWno1K1Lqmq47bX351cy/AXpeU7EYwIAAA=="#"H4sICNkv7lcCAzIAbdIxDgQhCAXQfk5BbKzUfs/CUTj8qiACMo2J/xl/cADi11tp/Xs39/pGY24JIR8NObCO+mjYZUf70pgAuUq3g1fMbEPSSgUt3NIVnhu1yVE0cMpRXX/ugpziuJ3ZaY8jlZpikMtDY+1ECiUtNvtjLpmSnaNYKwkP9ZKtk3BolMt6eeiVP+z2wJVCyZa11kjAMECe75V1DZCyAe6SnW1v9dvvQfruEEdV2no3/z/7OUOSpRE/POm9Tzpr/AEE2h7HhgMAAA=="#"H4sICOIv7lcCAzMApVG7DsIwDNzzFd48UNt7JTYYWNoFMUVy1gyIH/DHc0l4tBIb1yjxXf1MiLZ4pHG8qA1Kecc6/RCwbvsOUEJlA40mxbZY/Clt64E1bV1JBwhmUBGFzKMFV1HHyeTKRJ+me/KezloSg6wCcYGIiPf41MITfgv7dzR1luEwMTJUqW16gwcjcrks1/NyWgle6nBjMj+0C57nOacoUsnuGSty2HGCUYUDnaN+phXVMCz6C89uWEiOndWahi9bfwBslgom2wE1uzYNekv0A6XfyBPSqZrcBwIAAA==")(-(read)1))))o)(get-output-string o))(open-output-string)))

```

Just gzipped data encoded as base64.

## Ungolfed

```
(require file/gunzip net/base64)
(display ((λ (o)
            (gunzip-through-ports
             (open-input-bytes
              (base64-decode
               (list-ref
                '(#"H4sICMov7lcCAzEAdZExDsMgDEV3TuENkAhcoKrUqh2ypEM7osIpOvnwtTEkgaaOFIvvZ8efAAyBgKoTkvOTpse7VAupBO6bROK6m3QbBMu8vO7L7QGVzZNX4Lie4G9krwITtMgxZd6W3lEhCNFt0piTBXO25CXKfhtjnlbylbL58CEozL4fQG4afym808hfJAvitUjkozSKVKwXqvpnM5RNokXEd7uJniI3mcc6HTp1pBCOjisVDqnYqLiHRqpiQdHKyWno1K1Lqmq47bX351cy/AXpeU7EYwIAAA=="
                  #"H4sICNkv7lcCAzIAbdIxDgQhCAXQfk5BbKzUfs/CUTj8qiACMo2J/xl/cADi11tp/Xs39/pGY24JIR8NObCO+mjYZUf70pgAuUq3g1fMbEPSSgUt3NIVnhu1yVE0cMpRXX/ugpziuJ3ZaY8jlZpikMtDY+1ECiUtNvtjLpmSnaNYKwkP9ZKtk3BolMt6eeiVP+z2wJVCyZa11kjAMECe75V1DZCyAe6SnW1v9dvvQfruEEdV2no3/z/7OUOSpRE/POm9Tzpr/AEE2h7HhgMAAA=="
                  #"H4sICOIv7lcCAzMApVG7DsIwDNzzFd48UNt7JTYYWNoFMUVy1gyIH/DHc0l4tBIb1yjxXf1MiLZ4pHG8qA1Kecc6/RCwbvsOUEJlA40mxbZY/Clt64E1bV1JBwhmUBGFzKMFV1HHyeTKRJ+me/KezloSg6wCcYGIiPf41MITfgv7dzR1luEwMTJUqW16gwcjcrks1/NyWgle6nBjMj+0C57nOacoUsnuGSty2HGCUYUDnaN+phXVMCz6C89uWEiOndWahi9bfwBslgom2wE1uzYNekv0A6XfyBPSqZrcBwIAAA==")
                (- (read) 1))))
             o)
            (get-output-string o))
          (open-output-string)))

```

# Answer
> 1 votes
# PHP, ~~2113~~ 2112 bytes

If nobody else is going to compete I'll just grab the trophy and leave..

```
<?php function a($n){if($n<2){?>
                 | |
             _,.-'-'-.,_
      ______|           |______
   ,-'      |  NINTENDO |      `-.
 ,'   _                          `.
/   _| |_                     (^)   \
|  |_   _|                  (<) (>) |
\    |_|         (S)     (B)  (v)   /
|`.              ___       (A)    ,'|
|  `-.______   ,' _ `.   ______,-'  |
|      |    `. | (_) | ,'    |      |
|      |      \`.___,'/      |      |
|      |      |       |      |      |
|      /      |       |      \      |
\     /       |       |       \     /
 `._,'        \       /        `._,'
               \     /
                `._,'<?php }else if($n==2){?>
                  .-"-.
               .-"     "-.
              /"-.     .-|
             /    "-.-"  |
            /      /     |
   .-"-.   /      /      |       .-"-.
.-"     "-/      /       |    .-"     "-.
|-.     .-"\    /        |   /"-.     .-|
|  '-.-"    \  /         | /'    "-.-"  |
|     \      \/   .-"-.  /'        |    |
|      \      \.-"     "-.         |    |
|       \      |-.     .-"\        |    |
|        \     |  "-.-"    '\      |    |
|         \    |    |        '\    |    |
|    |\    \   |    |          '\  |    |
|    | \    \  |    |            '\|    |
|    |  \    \ |    |    :\.            |
|    |   \    \|    |    |  \.          |
|    |    \         |    |    \.        |
'-.  |  .-"\        |    |    '.\.    .-'
   "-|-"    \       |    |      "-\.-"
             \      |    |
              \     |    |
               "-.  |  .-'
                  "-|-"<?php }else{?>
              o
     o       /
      \     /
       \   /
        \ /
   ______________
  |.------------.|
  ||            ||
  ||            ||
  ||            ||
  ||            ||
  ||____________||_
  |OO ....... OO | `-.
  '------_.-._---' _.'
   _____||   ||___/_
  /  _.-|| N ||-._  \      .-._
 / -'_.---------._'- \    ,'___i-i___
/_.-'_  NINTENDO _'-._\  ' /_+  o :::\
|`-i /m\/m\|\|/=,/m\i-'| | || \ O / ||
|  |_\_/\_/___\_/'./|  | | \/  \ /  \/
`-'              '-.`-'  ,      V
                    `---' <?php }}?>

```

Thanks to @KevinCruijssen for a byte!

# Answer
> 1 votes
# PHP, 881 Bytes

```
<?=json_decode(gzinflate(base64_decode("rVY9rxQxDPwr0Ta5E0lWQHcCJBAUNHcFiCoi217xeBIFDea/M3acr80eFXlPG6094x07TnK/l5fLZTH7QYbiz/hjsCUXvMVfcKn5kgzqqdmkEOdtiWiun69fP10/3ozCNx8E5RiSJg11bAKLK6Mg7Bh5+n7GM0aGksmoQVfBvTmb07tzzi/GrLjhTl/Oef6A+fRLYq4ScwtjIORYOO+F4yzpx5FYLoJYkZpws0kKUoBaGE4R8ylBVq5GKdEE5BQ3ju6sFOSf0JIWPQTuYrRvdFB9KdA91lS/LCbEOWtGV0fO/qm39lF2Q0iLW14d9aoJPi7aSrMjRz3041uwK3Lu96yZIRJmApScdC7+rGb213o1ub2+PTrDpwyoCo5LLlkrLR3mBKv1JQ5TGgGMuNo5y6y0LB721NrlpYwqcWinShmEm4eE1mlTXsf4QqBOMxKsYWaCMqg+OsIOTlrROOGVscebRtjjhTHhG6HhL6hWzxvwldDwEiU8wrc912vqCAK3XG46LrdoD8rAka99jXJT10U7Qu5hWfZ5I02LY478j9zaQtSLmRGsDSfE6+mEeK6U54LuzpijY0ds40EEUzWkYWQjBd+NoFnQ0A/0H629Aryp+XYzIQ9z41u2XLA4AGSkgIsJM66kgE3c5yMfkrhx1XC868GA5woPmG0lOY6AgPE2teRDsl5RziLY3d+1RgiL5UvdrwBAEQVYizDpBa/P5XLRG3zzd1if+OzBg/h/fevk5e4t8Q8U2X03lkBlC6ASEQnIg7/LM1p5JflFoyeZrGU+1pi2eWuGAVlic/n123HL8S3PlVz+/AU=")),1)[$argv[1]];

```

Making of fill the lines with the graphics use the heredoc syntax in PHP

```
$a[1]=<<<A

A;
$a[2]=<<<B

B;
$a[3]=<<<C

C;
echo base64_encode(gzdeflate(json_encode($a)));

```

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


# Question
Title: Help the architects visualize the skyline
As part of a city planning project, you've gotten the assignment of creating a program or function that will display the city skyline, given some input from the architects. The project is only in the startup phase, so a very rough sketch is sufficient. The easiest approach is of course to simply draw the skyline in ASCII-art.

All buildings will be by the river, thus they are all aligned. The architects will give the height of each building as input, and your code should display the skyline.

The input from the architects will either be an integer or a half-integer. If the number is an integer, the building will have a flat roof, while a half-integer will result in a pitched roof. A zero will just be flat ground. The walls of a building are 3 characters apart, while a zero will be a single character wide. Adjacent buildings share walls.

For details and clarifications regarding the output, please have a look at the examples below:

```
N = 3
 ___
|   |
|   |
|___|

N = 3.5
  _
 / \
|   |
|   |
|___|

N = 6
 ___
|   |
|   |
|   |
|   |
|   |
|___|

n = 0
_

```

Example input: `3 3.5 0 2`

```
      _
 ___ / \
|   |   |  ___
|   |   | |   |
|___|___|_|___|

```

Example input: `0 0 2.5 3 0 4 1`

```
             ___
    _  ___  |   |
   / \|   | |   |
  |   |   | |   |___
__|___|___|_|___|___|

```

Louisville, `0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1`

```
                                    ___     ___
                                   |   |   |   |  ___
           _    ___     ___     ___|   |   |   | |   |
          / \  |   |   |   |   |   |   |   |   | |   |
  ___    |   | |   |___|   |___|   |   |   |   | |   |
 |   |___|   | |   |   |   |   |   |   |___|   | |   |___
_|___|___|___|_|___|___|___|___|___|___|___|___|_|___|___|

```

The ASCII-characters used are: newline, space, and `/\_|` (code points 10, 32, 47, 92, 95, 124).

**Rules:**

* It's optional to make a program that only take integers as input, by multiplying all numbers by two. So, instead of taking `3 3.5 2`, your program may take `6 7 4`. If the second input format is chosen, an input of 6 should result in a 3 story building, 7 should be a 3 story building with pitched roofs etc.
* The output should be exactly as described above, but trailing spaces and newlines are OK.
* The exact format of the input is optional. Whatever is best in your language.
* The result must be displayed on the screen, so that the architects can have a look at it.
* You can assume there will be at least one integer given, and that only valid input will be given.

**This is codegolf, so the shortest code in bytes win.**

# Answer
> 5 votes
# Python 2, ~~199~~ ~~193~~ ~~188~~ 185 bytes

```
a=map(int,raw_input().split())
l=max(a)+1|1
while~l:print''.join((x%2*'/  _\\ '[x<l::2]*(x<=l<x+4)or'_ '[x|1!=l>1]*3)[x<1:x+2]+'| '[x<=l>=y]*(x+y>0)for x,y in zip([0]+a,a+[0]))[1:];l-=2

```

This is a full program that accepts integers as input. Example input.

# Answer
> 5 votes
# MATLAB, ~~219 209~~ 203 bytes

```
i=input('');x=1;c=0;m(1:4*numel(i))='_';for a=i;b=fix(a);m(1:b,x)='|';s=95;if a~=b;m(b+2,x+2)=95;s='/ \';end;m(b+1,x+(1:3))=s;x=x+(a>0)*3+1;m(1:b,x)='|';x=x+(a<1&c>0);c=a;end;disp(flipud(m(:,1:x-(a<1))))

```

This unfortunately doesn't work on **Octave**. Not entirely sure why, seems to be something to do with the disp/flipud bit that breaks.

Also, there is currently no definition of what a 0.5 height building looks like, nor any mention of them, so in this code I assume that they are disallowed.

The following is the code in a slightly more readable way:

```
i=input(''); %e.g. [0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1 0 0 1 0]
x=1;
c=0;
m(1:4*numel(i))='_';
for a=i;
    b=fix(a);
    m(1:b,x)='|';
    s=95;
    if a~=b;
        m(b+2,x+2)=95;
        s='/ \';
    end;
    m(b+1,x+(1:3))=s;
    x=x+(a>0)*3+1;
    m(1:b,x)='|';
    x=x+(a<1&c>0);
    c=a;
end;
disp(flipud(m(:,1:x-(a<1))))

```

---

First we take an input as an array, and do some variable initialisation.

```
i=input(''); %e.g. [0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1]
x=1;
c=0;

```

Because the zero height buildings are a pain - they basically end up with a width which is dependent on what they are next to (though what is printed doesn't change), we simplify things by drawing enough ground for all of the buildings. We assume each building will be 4 characters wide (because adjacent buildings merge together) - zero height ones aren't, but the excess will be trimmed later.

```
m(1:4*numel(i))='_';

```

Now we draw out each building in turn.

```
for a=i

```

First we get the integer part of the height as this will determine how many '|' we need.

```
    b=fix(a);

```

Now draw in the wall for this building - if there are two adjacent buildings, the wall for this new one will be in the same column as the wall from the last one.

```
    m(1:b,x)='|';

```

Check to see if this is a half height building. If it is, then the roof will be different. For the half heights, the roof is going to be `/ \` whereas full height ones it will be `___` (Matlab will implicitly replicate this from a single underscore, so save a couple of bytes there). There is an extra bit of roof one row higher for the half height buildings, so that is added as well.

```
    s=95;
    if a~=b;
        m(b+2,x+2)=95;
        s='/ \';
    end;

```

Draw in the roof

```
    m(b+1,x+(1:3))=s;

```

Now move to the start of the next building and draw in the shared wall (if the wall is too short at this point, it will be made larger when the next building is drawn). Note that zero height buildings are 1 wide, normal buildings are 4 wide, so we simplify what would otherwise be an if-else by treating (a\>0) as a decimal number not a Boolean.

```
    x=x+(a>0)*3+1;
    m(1:b,x)='|';

```

Next comes a bit of hackery to work with zero height buildings. Basically what this says is if this building was zero height, and the one before that wasn't, it means the place of the next building needs incrementing by 1 because a zero height building sandwiched between two other buildings is effectively twice as wide - this accounts for the extra wall which is normally shared with an adjacent building. We also keep track of this building height for doing this check next time.

```
    x=x+(a<1&c>0);
    c=a;
end;

```

Once done, flip the building matrix to be the correct way up, and display it. Note that we also trim off any excess ground here as well.

```
disp(flipud(m(:,1:x-(a<1))))

```

---

So, when we run this script, we are asked for our input, for example:

```
[0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1 0 0 1 0]

```

It then generates the building and displays the result. For the above input, the following is generated:

```
                                     ___     ___
                                    |   |   |   |  ___
            _    ___     ___     ___|   |   |   | |   |
           / \  |   |   |   |   |   |   |   |   | |   |
   ___    |   | |   |___|   |___|   |   |   |   | |   |
  |   |___|   | |   |   |   |   |   |   |___|   | |   |___    ___
__|___|___|___|_|___|___|___|___|___|___|___|___|_|___|___|__|___|_

```

# Answer
> 4 votes
## Kotlin, ~~447~~ 442 bytes

```
val a={s:String->val f=s.split(" ").map{it.toFloat()}.toFloatArray();val m=(f.max()!!+1).toInt();for(d in m downTo 0){var l=0f;for(c in f){val h=c.toInt();print(if(h==d&&d!=0)if(h<l-0.5)"|" else{" "}+if(c>h)"/ \\" else "___" else if(h<d)if(d<l-0.5)"|" else{" "}+if(h==0)" " else if((c+0.5).toInt()==d)" _ " else "   " else{if(h==0)if(l<1)"  " else "| " else "|   "}.replace(' ',if(d==0)'_' else ' '));l=c;};if(d<l-0.5)print("|");println();}}

```

## Ungolfed version:

```
val ungolfed: (String) -> Unit = {
    s ->

    val floats = s.split(" ").map { it.toFloat() }.toFloatArray()
    val maxH = (floats.max()!! + 1).toInt()

    for (drawHeight in maxH downTo 0) {
        var lastBuildingH = 0f
        for (f in floats) {
            val buildingH = f.toInt()
            if (drawHeight == 0) {
                // Baseline
                if (buildingH == 0)
                    if (lastBuildingH.toInt() == 0) print("__")
                    else print("|_")
                else print("|___")
            } else if (buildingH == drawHeight) {
                // Ceiling
                if (buildingH < lastBuildingH - 0.5) print("|")
                else print(" ")
                if (f > buildingH) print("/ \\")
                else print("___")
            } else if (buildingH < drawHeight) {
                // Above building
                if (drawHeight < lastBuildingH - 0.5) print("|")
                else print(" ")
                if (buildingH == 0) print(" ")
                else {
                    if ((f + 0.5).toInt() == drawHeight) print(" _ ")
                    else print("   ")
                }
            } else {
                if (buildingH == 0) print("| ")
                else print("|   ")
            }
            lastBuildingH = f;
        }
        if (drawHeight < lastBuildingH - 0.5) print("|")
        println()
    }
}

```

# Answer
> 3 votes
## Python 2, ~~357~~ ~~306~~ ~~299~~ ~~294~~ ~~287~~ ~~281~~ 276 bytes

```
def s(l):
 d=len(l)+1;l=[0]+l+[0];h=(max(l)+3)/2;o=''
 for i in range(d*h):
  a=l[i%d+1];c=l[i%d];b=2*(h-1-i/d);o+="|"if(a>b+1)+(c>b+1)else" "*(a+c>0);o+=" _/__  _\\"[a-b+1::3]if b*(1>=abs(a-b))else" "*(1+2*(a>0))
  if b==0:o=o.replace(" ","_")
  if i%d==d-1:print o[:-1];o=''

```

This uses the "doubled" encoding, to be passed to the function as a list. Edit: Shaved bytes by redoing part of the big conditional as an array selector, and switching to the doubled encoding. Shaved more bytes by rearranging the conditional even more and converting more logic to arithmetic.

EDIT: xsot's is better

### Explanation:

```
d=len(l)+1;l=[0]+l+[0];m=max(l);h=m/2+m%2+1;o=''

```

`d` is 1 more than the length of the array, because we're going to add zeros on each end of the list from the second element up to the zero we added on the end. `h` is the height of the drawing. (We have to divide by 2 in this calculation because we are using the doubled representation, which we use specifically to avoid having to cast floats to ints all over the place. We also add 1 before dividing so odd heights--pointy buildings--get a little more clearance than the regular kind.) `o` is the output string.

```
 for i in range(d*h):

```

A standard trick for collapsing a double for loop into a single for loop. Once we do:

```
  a=l[i%d+1];c=l[i%d];b=2*(h-1-i/d)

```

we have now accomplished the same as:

```
for b in range(2*h-2,-2,-2):
 for j in range(d):
  a=l[j+1];c=l[j]

```

but in a way which nets us ten bytes saved (including whitespace on the following lines).

```
  o+="|"if(a>b+1)+(c>b+1)else" "*(a+c>0)

```

Stick a wall in any time the height of either the current building or the previous building is taller than the current line, as long as there is at least one building boundary here. It's the equivalent of the following conditional:

```
  o+=("|" if a>b+1 or c>b+1 else " ") if a or c else ""

```

where b is the current scan height, a is the current building height, and c is the previous building height. The latter part of the conditional prevents putting walls between ground spaces.

```
  o+=" _/__  _\\"[a-b+1::3]if b*(1>=abs(a-b))else" "*(1+2*(a>0))

```

This is the part that draws the correct roof, selecting roof parts by comparing the building's height with the current scan height. If a roof doesn't go here, it prints an appropriate number of spaces (3 when it's an actual building, e.g., a\>0, otherwise 1). Note that when we're at ground level, it never attempts to draw a roof, which means 0.5 size buildings don't get pointy roofs. Oh well.

```
  if b==0:o=o.replace(" ","_")

```

When we're at ground level, we want underscores instead of spaces. We just replace them all in at once here.

```
  if i%d==d-1:print o[:-1];o=''

```

Just before we start processing the next line, print the current one and clear the output line. We chop off the last character because it is the "\_" corresponding to the ground space we added by appending a zero at the beginning of the function. (We appended that zero so we would not have to add a special case to insert a right wall, if it exists, which would add far more code than we added by adding the 0 and chopping off the "\_".)

# Answer
> 2 votes
# Python 3

## ~~725 bytes~~

## 608 bytes

Golfed code:

```
import sys,math;
m,l,w,s,bh,ls,ins,r,a="|   |","___","|"," ",0,[],[],range,sys.argv[1:]
def ru(n):return math.ceil(n)
def bl(h,n):
    if(n>ru(h)):return(s*5,s)[h==0]
    if(h==0):return"_"
    if(n==0):return w+l+w
    if(n<h-1):return m
    return("  _  "," / \ ")[n==ru(h)-1]if(h%1)else(s+l+s,m)[n==h-1]
for arg in a:
    f=ru(float(arg))
    if(bh<f):bh=f
for i in r(bh,-1,-1):
    ln=""
    for bld in a:ln+=bl(float(bld),i)
    ls.append(ln)
for i in r(len(ls[-1])-1):
    if(ls[-1][i]==ls[-1][i+1]==w):ins.append(i-len(ins))
for ln in ls:
    for i in ins:ln=(ln[:i]+ln[i+1:],ln[:i+1]+ln[i+2:])[ln[i]==w]
    print(ln)

```

Here's the ungolfed code. There are some comments but the basic idea is to create buildings with double walls, so the bottom line looks like:

```
_|___||___|_|___||___|

```

Then to get indexes of those double walls and remove those columns so we get:

```
_|___|___|_|___|___|

```

Code:

```
import sys
import numbers
import math

mid="|   |";
l="___";
w="|";
s=" ";

def printList(lst):
    for it in lst:
        print(it);

# h = height of building
# l = line numeber starting at 0
def buildingline(h,n):
    #if (h==0):
    #   return " " if(n>math.ceil(h)) else "   ";
    if(n>math.ceil(h)):
        return s if(h == 0) else s*5;
    if(h==0): return "_";
    if(n==0): return w+l+w;
    if(n<h-1): return mid;
    if(h.is_integer()):
        return mid if(n==h-1) else  s+l+s;
    else:
        return " / \ " if (n==math.ceil(h)-1) else "  _  ";
# max height
bh=0;

for arg in sys.argv[1:]:
    f = math.ceil(float(arg));
    if(bh<f):bh=f;

# lines for printing
lines = []

for i in range(bh,-1,-1):
    line="";
    for bld in sys.argv[1:]:
        bld=float(bld);
        line += buildingline(bld,i);
        #lh = bld;
    lines.append(line);

#for line in lines:
#   print(line);
#printList(lines);

# column merging
#find indexes for merging (if there are | | next to each other)
indexes = [];
for i in range(len(lines[-1])-1):
    if (lines[-1][i]=='|' and lines[-1][i+1] == '|'):
        indexes.append(i-len(indexes));

#printList(indexes);

#index counter
for line in lines:
    newLine = line;
    for i in indexes:
        if newLine[i] == '|' :
            newLine=newLine[:i+1] + newLine[i+2:];
        else : newLine = newLine[:i] + newLine[i+1:];
    print(newLine);

```

Time to do some golfing!

# Answer
> 2 votes
## PHP, ~~307~~ ~~297~~ 293 bytes

```
<?$r=str_pad("",$p=((max($argv)+1)>>1)*$w=4*$argc,str_pad("\n",$w," ",0));for(;++$i<$argc&&$r[$p++]=_;$m=$n)if($n=$argv[$i]){$q=$p+=!$m;eval($x='$r[$q-1]=$r[$q]=$r[$q+1]=_;');for($h=$n>>1;$h--;$q-=$w)$r[$q-2]=$r[$q+2]="|";$n&1?($r[$q-1]="/")&($r[$q-$w]=_)&$r[$q+1]="\\":eval($x);$p+=3;}echo$r;

```

Takes arguments\*2 from command line. save to file, run with `php <filename> <parameters>`.

**breakdown**

```
// initialize result
$r=str_pad("",              // nested str_pad is 3 bytes shorter than a loop
    $p=                     // cursor=(max height-1)*(max width)=(start of last line)
    ((max($argv)+1)>>1)     // max height-1
    *
    $w=4*$argc              // we need at least 4*($argc-1)-1, +1 for newline
    ,
    // one line
    str_pad("\n",$w," ",0)  // (`str_pad("",$w-1)."\n"` is one byte shorter,
);                          // but requires `$w+1`)

// draw skyline
for(;
    ++$i<$argc              // loop through arguments
    &&$r[$p++]=_                // 0. draw empty ground and go one forward
    ;
    $m=$n                       // 7. remember value
)
    if($n=$argv[$i])            // if there is a house
    {
        $q=                         // 2. copy $p to $q
        $p+=!$m;                    // 1. go one forward if there was no house before this
        // offset all further positions by -2 (overwrite empty ground, share walls)
        eval($x=                    // 3. draw floor
        '$r[$q-1]=$r[$q]=$r[$q+1]=_;'
        );
        for($h=$n>>1;$h--;$q-=$w)   // 4. draw walls
            $r[$q-2]=$r[$q+2]="|";
        $n&1                        // 5. draw roof
            ?($r[$q-1]="/")&($r[$q-$w]=_)&$r[$q+1]="\\"
            :eval($x)               // (eval saved 7 bytes)
        ;                           // (ternary saved 6 bytes over `if`)
        $p+=3;                      // 6. go three forward (5-2)
    }

// output
echo$r;

```

# Answer
> 1 votes
# C++, ungolfed

(or maybe ungolfable)

Assuming there are less than 100 elements and each element is less than 100. `s` is the number of buildings (required in input).

```
#include <iostream>
using namespace std;
int main()
{
float a[100];
int i,j,s;
cin>>s;
for(i=0;i<s;++i)
 cin>>a[i];
for(i=100;i>=1;--i)
{
for(j=0;j<s;++j)
{
if((a[j]>=i)||(a[j-1]>=i))
 cout<<"|";
else
 cout<<" ";
if(i==1)
 cout<<"___";
else if(a[j]+1==i)
 cout<<"___";
else if(a[j]+1.5==i)
 cout<<" _ ";
else if(a[j]+0.5==i)
 cout<<"/ \\";
else cout<<"   ";
}
if(a[s-1]>=i)
 cout<<"|";
cout<<endl;
}
}

```

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


title: Modulo code golf

text:
# Question
Title: Modulo code golf
Write a function `f(a,b)` that returns `a mod b` given the constraints:

* you can't use division in any way
* `f(a,b)` is always positive, eg: `f(-1,5) = 4`
* it performs reasonably well for values of ~`10e50` for `a` and `b`

# Answer
## Haskell ~~36~~ 35 (~~34?~~ 33)

If I may call the function `?` instead:

```
1234567890123456789012345678901234
a?b|a<0=(a+b)?b|a>b=(a-b)?b|0<1=a

```

Elseway:

```
f a b|a<0=f(a+b)b|a>b=f(a-b)b|0<1=a

```
> 6 votes

# Answer
## Perl, 62 bytes

Regex modulo

```
sub f{($a,$b)=@_;$_=1x$a;s/^(1{$b})+(1+)$/return length $2/e;}

```
> 3 votes

# Answer
## Java Solution, 114 66 chars

Its now 66, thanks sepp2k!~

```
 int m(int x,int y){x=(x<0)?-(x*y-x):x;while(x>=y) x-=y;return x;}

```
> 2 votes

# Answer
## Haskell (22)

Abuse of the rules, please don't downvote: Mathematically, the modulus may be arbitrary large, because all moduli are equivalent. Thus, you may also use this, it WILL always return a positive result:

```
1234567890123456789012
a?b|a<0=(a+b)?b|True=a

```

And it will also always satisfy the equation

```
a?b = c <-> n*b + c = a

```

For some integer n.
> 2 votes

# Answer
# Ruby - 72 chars

```
f=->a,b{a==b&&0||a<b&&a+(a<0&&b||0)||(t=b;t<<=1until t>a;f[a-(t>>1),b])}

```

Uses recursion like a Binary Search to find the remainder.

Test

```
p f[106, 95]
p f[23, 2]
p f[-1, 5]
p f[20, 7]
p f[10**100, 3]
p f[4*10**200, 3123123]

11
1
4
6
1
823660

```
> 2 votes

# Answer
## Brainfuck - 37 characters

```
,>,<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>.

```

Takes a and b as bytes from standard input. Outputs one byte. Does not meet criteria to work with arbitrary size numbers, but to do so in brainfuck would not be simple.
> 2 votes

# Answer
# Python 2, 35 bytes

```
f=lambda a,b:a if a<b else f(a-b,b)

```

Sadly, I can't use `and`/`or` short-circuiting here, so I have to do with one more byte.
> 1 votes

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


title: Priority to the right

text:
# Question
Title: Priority to the right
Your task is to regulate traffic on a crossroads. There are 4 roads coming from north, east, south and west.

The input is a string representing the upcoming traffic on each road. For example, `NNNWS` indicates there is a total of 5 cars: three at the north, one at the west and one at the south. The order of characters has no importance here, `NNNWS` is equivalent to `WNNSN`.

You must output the order in which the cars should go, using the priority to the right rule: cars coming from the south must let cars coming from east go first, east gives way to north, north gives way to west and west gives way to south.

For example, with the input `NNNWS`, the south car should go first, then the west car, then the 3 north cars. The output should thus be `SWNNN`.

There are some indecidable cases, for example `NS` or `NNWSE` : you should then output the string `stuck`.

**Test cases**

```
N => N
NW => WN
NWS => SWN
SNW => SWN
SSSSS => SSSSS
ENNNNES => NNNNEES
NS => stuck
NNWSE => stuck

```

# Answer
> 2 votes
# Perl, 65 bytes

Includes +2 for `-lp`

Give input on STDIN. Assumes the empty string is not a valid input

```
#!/usr/bin/perl -lp
s%.%'+(y/NESW/ESWN/*s/N(.*)W/W$1N/,/N/^/S/)'x4%gere+0or$_=stuck

```

If you don't mind the absence of a newline after `stuck` you can drop the `l` option

# Answer
> 2 votes
# PHP, 267 Bytes

use the new spaceship operator and usort -5 Bytes by @IsmaelMiguel

```
<?foreach($f=[E,S,W,N]as$l)$s.=+!($r=strstr)($i=$argv[1],$l);if(in_array($s,[0101,1010,0000]))die(stuck);$x=($p=strpos)($s,"1");$t=$r($j=join($f),$f[$x]).$r($j,$f[$x],1);$a=str_split($i);usort($a,function($x,$y)use($t,$p){return$p($t,$x)<=>$p($t,$y);});echo join($a);

```

## Breakdown

```
# Extended Version without notices
$s="";
foreach($f=["E","S","W","N"] as $l){$s.=+!strstr($i=$argv[1],$l);} #bool concat swap the false true values in string
if(in_array($s,["0101","1010","0000"])){die("stuck");} # NS WE NESW -> stuck = end program
$x=strpos($s,"1"); # find the first false value for an begin for the sort algorithm
$t=strstr($j=join($f),$f[$x]).strstr($j,$f[$x],1); # create the sort pattern
#sort algorithm example sort string = NESW-> N is not in the string
function c($x,$y){
    global $t;
    return strpos($t,$x)<=>strpos($t,$y); # e.g. comparison E<=>W =-1 , W<=>S=1, W<=>W =0
}
$a=str_split($i); # Input in an array
usort($a,"c"); #sort array
echo join($a);# output array as string

```

# Answer
> 1 votes
## JavaScript (ES6), ~~108~~ ~~107~~ ~~106~~ 104 bytes

```
s=>(r=t=`NESWNE`,s.replace(/./g,c=>r|=2<<t.search(c)),t.substr(449778192>>r&3,1053417876>>r&3)||`stuck`)

```

Accumulates a bitmask of which directions have approaching cars and extracts the appropriate portion of the priority string.

# Answer
> 1 votes
## Batch, 216 bytes

```
@echo off
set/pt=
set/an=2,e=4,s=8,w=16,r=0
:l
set/ar^|=%t:~0,1%
set t=%t:~1%
if not "%t%"=="" goto l
set/a"o=449778192>>r&3,l=1053417876>>r&3"
if %l%==0 (echo stuck)else set t=NESWNE&call echo %%t:~%o%,%l%%%

```

Simple port of my JavaScript answer. Takes input on STDIN in upper or lower case.

---
Tags: code-golf
---


title: Pen Pineapple Apple Pen!

text:
# Question
Title: Pen Pineapple Apple Pen!
Your task is to print the following:

```
I have a pen
I have an apple
Uh! Apple pen!

I have a pen
I have pineapple
Uh! Pineapple pen!

Apple pen...
Pineapple pen...
Uh! Pen Pineapple Apple Pen!

```

Remember, this is , so the code with the smallest number of bytes wins.

### Leaderboards

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

```

```
var QUESTION_ID=95124,OVERRIDE_USER=12537;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+)(?=[^\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>
```

# Answer
> 4 votes
# Bubblegum, 72 bytes

```
00000000: f354 c848 2c4b 5548 5428 48cd e3f2 8472  .T.H,KUHT(H....r
00000010: f214 120b 0a72 52b9 4233 1415 1c41 2c90  .....rR.B3...A,.
00000020: ac22 175c 1e59 7141 665e 2a42 7500 8c07  .".\.YqAf^*Bu...
00000030: d501 d7ad a7a7 c785 2209 1200 eb48 cd43  ........"....H.C
00000040: d205 510f 1453 0400                      ..Q..S..

```

Try it online!

The above is the `xxd` hexdump of the actual code.

# Answer
> 2 votes
## JavaScript (ES6), ~~145~~ 143 bytes

```
_=>`P325|I have |pple|inea|
Uh! | pen`.split`|`.reduce((s,r,i)=>s.split(i).join(r),`1a5
1an a24A25!

1a5
1p3240!

A25...
0...4Pen P32 A2 Pen!`)

```

```
let f =

_=>`P325|I have |pple|inea|
Uh! | pen`.split`|`.reduce((s,r,i)=>s.split(i).join(r),`1a5
1an a24A25!

1a5
1p3240!

A25...
0...4Pen P32 A2 Pen!`)

console.log(f());
```

# Answer
> 1 votes
# ///, 117 bytes

```
/@/I have //#/apple//$/Apple //&/Uh! //%/pen//*/Pine/@a %
@an #
&$%!

@a %
@pine#
&*# %!

$%...
*# %...
&Pen *# $Pen!

```

Try it online!

# Answer
> 1 votes
# Jelly, 94 bytes

```
“/¢ȷKcḞvßÇwİµɼUṡ]nk]¹¤%Ƭ*|ẊƓẸḢÇ2ẋbịʋ]dṀ⁸)ṇẎ⁶ėDṭD’b⁴ị“I“have“a“p“en“¶“n“A“pple“Uh“!“ine“P“...“

```

**TryItOnline**

How?

Manual compression:

I looked for strings that repeated and made a list, there were 15.
I ordered these like so:
`“I“have“a“p“en“¶“n“A“pple“Uh“!“ine“P“...“`
so as to make the smallest base-16 number from the text (with no leading 0)
here:  separates;  represents a line feed; and the last entry (index 0) is a space.

I then converted the number to base-250 and wrote it out in the first 250 of the 256 characters in the Jelly code-page:
`/¢ȷKcḞvßÇwİµɼUṡ]nk]¹¤%Ƭ*|ẊƓẸḢÇ2ẋbịʋ]dṀ⁸)ṇẎ⁶ėDṭD`

The code the inverses the same process: “(base-250-encoded-number)’
b⁴ị - base 16, index into
`“I“have“a“p“en“¶“n“A“pple“Uh“!“ine“P“...“`

Note: base-15 would have the same byte-count, one less in the encoded number but one more to decode as literal 15 is `15` whereas literal 16 is . Maybe a substring list of 16 items could cost less in total.

# Answer
> 1 votes
# Perl, 139 bytes

With UNIX line terminators (`LF` = one byte) :

```
s//0an a1
5A12!

0p4
5P42!

A123P4235Pen P4A1Pen!/;s/4/inea1/g;s/0/I have a pen
I have /g;s/1/pple /g;s/2/pen/g;s/3/...
/g;s/5/Uh! /g;print

```

# Answer
> 0 votes
## Batch, 203 bytes

```
@echo off
set e=echo(
call:l "an a" A
call:l pinea Pinea
%e%Apple pen...
%e%Pineapple pen...
%e%Uh! Pen Pineapple Apple Pen!
exit/b
:l
%e%I have a pen
%e%I have %~1pple
%e%Uh! %2pple pen!
%e%

```

Batch is so verbose that the `set e=echo(` saves a whole byte. (Worth it of course for code golf purposes.)

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


title: Am I old enough?

text:
# Question
Title: Am I old enough?
It is currently December 31, 2015, 11:59:00pm, and you must be at least 1324900 seconds old to be able to go to the New Year Celebration. Given the year, month, day, hour, minute, and second of your birth, determine if you are old enough to go.

Notes:

* Assume that you are in the same timezone.
* Leap years are every 4 years, but if the year is a multiple of 100, it is not a leap year, unless it is a multiple of 400.

Remember, this is , so the code with the smallest number of bytes wins.

## Leaderboards

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

```

```
var QUESTION_ID=95129,OVERRIDE_USER=12537;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+)(?=[^\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>
```

# Answer
> 2 votes
## Python, 28 bytes

```
[2015,12,16,15,57,20].__le__

```

Going back 1324900 seconds from December 31, 2015, 11:59:00pm gives December 16, 2015 at 3:57:20 pm. We convert this date to a list and take it's less-than-or-equals method to compare to the input list. This compares it lexicographically, so first by year, then by month, and so on.

# Answer
> 1 votes
# Mathematica, 66 bytes

```
DateObject@{2015,12,31,23,59,0}-DateObject@#>1324899~Quantity~"s"&

```

Anonymous function. Takes a list of integers as input, and returns `True` or `False` as output.

---
Tags: code-golf
---


title: So sayeth the Shepherd

text:
# Question
Title: So sayeth the Shepherd
I'm tired, but I can't seem to fall asleep. Help me count sheep.

Given an input N (positive integer), make N sheep jump over an ascii fence, like the sample below. Only one frame should be displayed at once:

```
o |-|
──|-|──  0

```

---

```
 o|-|
──|-|──  0

```

---

```
   o
  |-|
──|-|──  0

```

---

```
  |-|o
──|-|──  0

```

---

```
  |-| o
──|-|──  0

```

---

```
o |-|
──|-|──  1

```

---

```
 o|-|
──|-|──  1

```

---

```
   o
  |-|
──|-|──  1

```

Count should be kept at the lower right side of the 'ground'. Trailing and leading whitespace and newlines are allowed. If your language of choice has difficulty clearing the screen for each frame you can add sufficient newlines to clear the screen - please state how many lines you add for this in your answer. The program should terminate when the N'th sheep is on the fifth floortile.

I need to get up early tomorrow, so shortest code in bytes wins. Please submit a function or complete program. Standard loopholes apply.

# Answer
> 15 votes
# MATL, ~~60~~ ~~56~~ 53 bytes

```
:"@qXJx[HKCbO]"7Z"'  |-|  'v'o'@('--|-|--  '  JVhXxXD

```

The animation with the above code runs very fast. The following version includes a pause to make the animation slower and thus easier to see (not required by the challenge), at the cost of 4 more bytes:

```
:"@qXJx[HKCbO]"7Z"'  |-|  'v'o'@('--|-|--  '  JVhXxXD.2Y.

```

Try it at **MATL Online!** The interpreter is a beta; refresh the page if it doesn't work.

Or see a recording from the offline compiler:

### Explanation

```
:"              % Input N implicitly. Repeat N times
  @q            %   Push iteration index minus 1, that is, from 0 to N-1. This
                %   are the numbers of sheep
  XJx           %   Copy into clipboard J and delete
  [HKCbO]       %   Push array [2 4 7 -2 0]
  "             %   For each value in that array. This loops generates the 5
                %   frames for each number of sheep
    7Z"         %     Push string of 7 spaces
    '  |-|  '   %     Push this string
    v           %     Concatenate vertically. This gives a 2x7 char array
                %     with the upper part of the frame, except the 'o',
                %     which will be now placed in a varying position
    'o'         %     Push string 'o'
    @           %     Push loop variable, that is, 2, 4, 7, -2 or 0
    (           %     Write 'o' into that position of the 2x7 char array.
                %     The position is interpreated linearly, that is, a single
                %     number is used as index into the 2D array in column-major
                %     order (down, then across). So index 2 is lower-left corner,
                %     index 4 is to the right of that etc. Indexing is
                %     semi-modular (modular for non-positive values). So 0 is
                %     the lower-right corner, and -2 is to the left of that
    '--|-|--  ' %     Push this string
    JV          %     Push current number of sheep converted to string
    h           %     Concatenate horizontally
    Xx          %     Clear screen
    XD          %     Display all stack contents
    .2Y.        %     Pause for 0.2 seconds (optional)
                %   End implicitly
                % End implicitly

```

# Answer
> 6 votes
# JavaScript (ES6), ~~120~~ 124 bytes

```
f=(n,m=`   2
43|-|10
──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+(n-1),(++s%5?f(n,m,s):f(n-1,m,0))):''

```

The last frame computed is showing first. Thanks to this the jump number is `n-1`
In `alert`, charaters have different width so it looks like it's broken.

```
f=(n,m=`   2
43|-|10
──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+(n-1),(++s%5?f(n,m,s):f(n-1,m,0))):''
;

f(2);//You'll get 10 alert popup
```

---

Previous answer:

120 bytes, the jump number is wrong because it starts at 1 instead of 0

```
f=(n,m=`   2
43|-|10
──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+n,(++s%5?f(n,m,s):f(n-1,m,0))):''

```

# Answer
> 6 votes
## JavaScript (ES6), ~~144~~ 142 bytes

Clears the output and waits 300ms between each frame:

```
n=>(F=j=>((c=console).clear(),c.log(`   2
01|-|34
──|-|── `.replace(/\d/g,i=>(j-i)%5?' ':'o')+(j/5|0)),++j<n*5&&setTimeout(`F(${j})`,300)))(0)

```

You can **test it here** (make sure to open the console).

# Answer
> 4 votes
# C#, 234 Bytes

```
using C=System.Console;class P{static void Main(string[]a){for(int n=0;n-1+""!=a[0];++n){foreach(int p in new[]{5,6,3,10,11}){C.Clear();C.Write("    \n  |-|  \n──|-|── ".Remove(p,1).Insert(p,"o")+n);for(var w=3e7;w>0;--w);}}}}

```

# Answer
> 4 votes
# Ruby, 83 bytes

```
->n{(n*5).times{|i|$><<"   c
  |-|
ab|-|de  #{i/5}
".tr('abcde',' '*(i%5)+'o ')}}

```

Prints to stdout. Output separated by newlines. Reducing screen height to 3 makes only one image visible at a time.

# Answer
> 3 votes
# PHP+JavaScript, 168 bytes

```
<?extract($_GET);$s="     ";$s[$f=++$f%5]=o;echo strtr("<pre>   C
AB|─|DE
──|─|── $c",EABCD,$s),($c+=!$f)<$n?"<script>location.href='s.php?n=$n&c=$c&f=$f'</script>":"";

```

Save to file `s.php`, call in browser with `s.php?n=<n>`.

Calls itself with new parameters for every frame, no delay.

---

I could save 5 more with `index.php`; but I don´t want to go that far.

# Answer
> 3 votes
# Tcl, 168 bytes

Version using 10-row-high screen. (Replace the `7` below with your screen height in columns minus four.)

```
set s {0 1 2 3 4 }
for {set n 0} {$n<$argv} {incr n} {foreach x $s {
puts [string repe \n 6][string map [split $s {}] [string map "$x o" {   2
01|-|34
--|-|--  }]]$n}}

```

That runs really fast, so you can add a pause on line two:

# Tcl, 177 bytes

```
set s {0 1 2 3 4 }
for {set n 0} {$n<$argv} {incr n} {foreach x $s {after 250
puts [string repe \n 6][string map [split $s {}] [string map "$x o" {   2
01|-|34
--|-|--  }]]$n}}

```

It works by reusing the string at the top for two different things:

* as a list for the inner loop (to display each version of the sheep+fence)
* as a mapping of digit→space to remove digits from the sheep+fence image template

The template itself is the string image to display. First we map (string replace) the sheep's current position digit (inner loop) to an 'o'. Then we map the remaining digits to spaces. Then we print the resulting string.

(The string itself starts after the last { on the third line and ends with the leftmost } on the last line.)

# Answer
> 3 votes
## QBasic, 110 bytes

```
INPUT n
FOR i=0TO 5*n-1
CLS
?
?"  |-|"
?"--|-|-- ";i\5
x=i MOD 5
LOCATE(x=2)+2,1+x-(x>1)+x\3
?"o"
SLEEP 1
NEXT

```

Loops over `5*n` ticks. At each tick, clears the screen, prints the stile and sheep count, and then uses `LOCATE` to print the `o` at the appropriate spot. With `x` being the position code between 0 and 4:

* Row: `(x=2)+2`
    + If `x=2` is true, `-1+2` = `1`
    + If `x=2` is false, `0+2` = `2`
* Column: `1+x-(x>1)+x\3`
    + If `x` is `0` or `1`, `x>1` is false and `x\3` is `0`: `1+x-0+0` = `1` or `2`
    + If `x` is `2`, `x>1` is true and `x\3` is `0`: `1+x-(-1)+0` = `4`
    + If `x` is `3` or `4`, `x>1` is true and `x\3` is `1`: `1+x-(-1)+1` = `6` or `7`

Finally, `SLEEP` for 1 second and loop. If you don't mind hitting enter at every frame, I can shave two bytes by removing the argument to `SLEEP`.

# Answer
> 3 votes
# node.js + sleep, 169 bytes

```
c='   2\n01|-|34\n──|-|──  '
for(i=0;i<process.argv[2]*5;require('sleep').sleep(1))console.log('\033[2J'+c.replace(i%5,'o').replace(/\d/g,' ')+Math.floor(i++/5))

```

### Original solution

# node.js, ~~146~~ ~~142~~ 185 bytes

Tested with ubuntu terminal only (and now with n sheeps):

```
i=0
c='   2\n01|-|34\n──|-|──  '
setInterval(function(){console.log('\033[2J'+c.replace(i%5,'o').replace(/\d/g,' ')+Math.floor(i++/5))
if(process.argv[2]*5==i)process.exit()},9)

```

Well, that's a frame every 9 ms. A more sleep-soothing version (frame every 1s):

```
i=0;setInterval(function(){console.log('\033[2J'+'   2\n01|-|34\n──|-|──  '.replace(i%5,'o').replace(/\d/g,' ')+Math.floor(i++/5))},1000)

```

And ungolfed:

```
var i = 0;
setInterval(function(){
  console.log('\033[2J' + '   2\n01|-|34\n──|-|──  '.replace(i%5, 'o').replace(/\d/g, ' ') + Math.floor(i++/5));
}, 1000)

```

# Answer
> 3 votes
# PHP, ~~132~~ 131 bytes

Edits after comments (thanks!):

```
<?php for(;$i<$argv[1]*5;sleep(1),system(clear),$c="
  |-|
──|-|──  ".floor($i/5),$c[[5,6,3,10,11][$i++%5]]=o)echo$c;

```

Which is ungolfed:

```
<?php

ini_set('error_reporting', '0');        # golfing precondition

for(; $i<$argv[1]*5;                    # repeat N times
  sleep(1),                             # sleep after iteration
  system(clear),                        # clear screen (linux only)
  $c = "
  |-|
──|-|──  " . floor($i / 5),             # define template
  $c[[5, 6, 3, 10, 11][$i++ % 5]] = o)  # replace with sheep (and finish "for" statement)
  echo $c;                              # output result

```

### Original post

```
<?php $i=0;for(;;){system("clear");$c="  \n  |-|  \n──|-|──  ";$c[[3,4,1,8,9][$i%5]]='o';echo"  $c".floor($i++/5);sleep(1);}

```

Tested on ubuntu (don't know, if `system("clear")` works on windows)

Ungolfed:

```
<?php
$i = 0;
for(;;) {
  system("clear");
  $content = "  \n  |-|  \n──|-|──  ";
  $content[[3,4,1,8,9][$i%5]] = 'o';
  echo "  $content " . floor($i++/5);
  sleep(1);
}

```

# Answer
> 2 votes
# 05AB1E, ~~66~~ ~~60~~ 59 bytes

```
FNU5Fð4×N<i¨'oJ},N<iðë'o}ðNÉis}"|-|  "JN1›iR},…──|Â'-sððXJ,

```

Uses CP-1252 encoding.

## Explanantion

Iteration refers to the inner iteration (0 -\> 4) of the sheeps journey.

**Main loops**

```
F      # For N in range [0 .. input)
 NU    # Save N in variable X
 5F    # For N in range [0 .. 5)

```

**Generate top row**

```
ð4×         # push 4 spaces
N<i    }    # if we're on the 2nd iteration
   ¨'oJ     # replace the last space with an "o"
,           # print row

```

**Generate middle row**

```
N<iðë'o}     # push a space if we're on the 2nd iteration, else push "o"
ð            # push a space
NÉis}        # if we're on an odd numbered iteration, swap the stacks top 2 chars
"|-|  "      # push this string
J            # join the stack to one string
N1›iR}       # if we're on the any of the last 3 iterations, reverse the string
,            # print row

```

**Generate bottom row**

```
…──|  # push the string "──|"
Â     # push a reversed copy
'-s   # push "-" between the 2 strings on the stack
ðð    # push 2 spaces
X     # push the N we saved in the main loop (current sheep number)
J,    # join and print row

```

# Answer
> 1 votes
# Jelly, ~~55 54~~ 53 bytes

```
ị30214D¤“o    ”ṙ“   “
““|-|““
__|-|__  ”ż
×5Ḷµ:5ż@Ç€Y

```

**TryItOnline**

Prints frames separated by line feeds.

How?

```
ị30214D¤“o    ”ṙ“   “
““|-|““
__|-|__  ”ż           - Link 1, build a frame without counts: frameNumber
       ¤              - nilad and link(s) as a nilad:
 30214                -     literal 30214 (a nilad)
      D               -     to decimal: [3,0,2,1,4]
ị                     - index into (1-based and modular, so frames go 4,3,0,2,1,4,...)
        “o    ”       - string "o    "
               ṙ      - rotated to the left by that number
                “   “ - the rest, except the last character, is:
““|-|““               -     an array of strings ["   ","\n","","|-|","","\n__|-|__  "]
__|-|__  ”            -     i.e. split where a sheep might go

          ż           - zip the sheep (the rotated "o    ") into that

×5Ḷµ:5ż@Ç€Y - Main link: nSheep
×5          - multiply by 5 -> nFrames
  Ḷ         - lowered range: [0,1,2,...nFrames-1]
   µ        - monadic chain separation
    :5      - integer division by 5 (vectorises): [5 zeros, 5 ones, ..., 5 (nSheep-1)s]
      ż@    - zip with reversed arguments
        Ç€  - call last link (1) as a monad for each (zip sheep numbers with frames)
          Y - join with line feeds (TODO: replace with future animate frames atom :p)

```

# Answer
> 1 votes
# Python 2, ~~171~~ ~~159~~ 144 bytes, ~~163~~ ~~151~~ 136 characters

Solution using a recursive function. Call as f(int)

**EDIT**

-12 after rereading the comments and seeing that the count does not have to increment when the sheep reaches the end of the field

-15 by iterating through the index list directly and losing a variable

```
def f(a,x=0):
 if a>0:
  for c in 5,6,3,10,11:
   b=list('    \n  |-|  \n──|-|──  ');b[c]='o';print"\n"*50+"".join(b)+(`x`)
  f(a-1,x+1)

```

**Notes**

Assumes UTF-8 encoding

Using - instead of ─ (as in @Luis MATL answer) would bring the byte count down by 8 to match the character count and would lose the UTF-8 dependency

50 newlines added - output is at the bottom on the console (cheaper than importing and using os.system("clear") and works on Windows and Linux)

Version with 1 second time delay between outputs (170 bytes, 162 characters)

```
import time
def f(a,x=0):
 if a>0:
  for c in 5,6,3,10,11:
   b=list('    \n  |-|  \n──|-|──  ');b[c]='o';print"\n"*50+"".join(b)+(`x`);time.sleep(1)
  f(a-1,x+1)

```

# Answer
> 1 votes
# Bash + standard Linux utilities (339 bytes)

```
e(){ echo "$@";}
n(){ e -n "$@";}
r(){ [ $? -eq 0 ]&&s=o||s=" ";[ $1 ]&&n " $s "||n "$s";}
f(){ k=$(($1%5));n "  ";[ $k -eq 2 ];r .;e "  ";for i in 0 1;do [ $k -eq $i ];r;done;n "|-|";for i in 3 4;do [ $k -eq $i ];r;done;e;n "──|-|──";}
for l in `seq 1 $1`;do for z in `seq 0 4`;do clear;f $z;e "  $((l-1))";sleep 1;done;done

```

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


title: A Mouse with Dynamite

text:
# Question
Title: A Mouse with Dynamite
You're a mouse. Your mouse friends have all been captured, and are unconscious and trapped in a maze that has only one entrance/exit. You happen to have a perfect map of the maze, so you can plot a solution to rush in and carry them all to safety. However, the maze is guarded with a security system that will trigger an alert if a threshold of `1000` is reached, causing you to be captured and fail your rescue mission.

From your previous investigations of the maze, each square you step (i.e., each horizontal or vertical movement -- *mice can't move diagonally*) adds `1` to the security system's counter. However, if you're carrying a weight (either a block of dynamite or an unconscious mouse friend), it instead adds `2` since it detects the additional pressure. The entrance/exit square doesn't have this security system, and so doesn't add to the counter.

You have an unlimited supply of dynamite that you've brought to the entrance, so you can simply blow up all the walls to free your friends. But you need to be cautious with doing so, since each explosion adds `50` to the counter from the concussive pressure. Additionally, you can only carry one thing at a time, either one mouse or one block of dynamite. Since each block of dynamite can only detonate one wall space, this means that if there are multiple walls in a row, you need to make an empty-handed trip back to the entrance to grab more.

### Worked-through example

Suppose our maze looks like the following:

```
######
#M# E#
######

```

I'll use `c` for the counter. We start at the `E`ntrance, move one square left while carrying dynamite, `c=2`. We detonate the dynamite to explode the wall, `c=52`. We move two squares left, empty-handed, to get `c=54`, and we're now standing on the mouse's square. We pick our friend up, and move 3 squares back to the `E`xit, but the last square doesn't count since it doesn't have any sensors, so that's only 2 squares with something on our back. That means that when we reach the exit with the final mouse, `c=58`, which is less than `1000`, and therefore the mission succeeds.

### Challenge

Given an input maze, output whether you, the mouse hero, can successfully rescue all trapped mice within the constraints outlined above, or whether the mission is a failure.

### Input

* A 2D maze in any acceptable format (multiline string, array of strings, etc.).
* For this challenge, I will be using `#` for both the interior and exterior walls, `M` for the mouse friends, and `E` for the entrance.
* The entrance will never be immediately adjacent to an interior wall (there will always be at least one space in which to move freely).
* You can substitute any printable ASCII characters you wish so long as it's consistent. This *does* allow you to use two different symbols for interior walls vs. exterior walls, so long as you maintain consistency (e.g., if you choose to use `@` for interior walls instead, and leave `#` for exterior, *every* interior wall must be `@` and *every* exterior wall `#`).
* The maze will always be completely bounded by walls, but is not necessarily rectangular. If desired, you can assume that the maze is padded with spaces to make rectangular input (optional).
* The maze may have sections that are unreachable without dynamite.
* You cannot dynamite the exterior walls of the maze.

### Output

A truthy/falsey value. Truthy for "Yes, the mouse can rescue every other mouse" or Falsey for "No, the alarm system will be tripped."

### The Rules

* Either a full program or a function are acceptable.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### Examples

Truthy examples, separated by blank lines.

```
#####
#M E#
#####

######
#M# E#
######

########
#E  # M#
#   #  #
#   #  #
#      #
########

#############################
#    ##      #       #      #
#  M ## M    #       #      #
#    ##      #   M   #    E #
#M   ##      #       #      #
#############################

###############
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMM MM#
#MMMMMMMMMMMME#
###############

```

Falsey examples, separated by blank lines

```
#############################
#M   ##      ##      ##     #
#  M ## M    ##      ##     #
#    ##      ##  M   ##   E #
#M   ##      ##      ##     #
#############################
#############################
                     ########
                     ########
                     #   #  #
                     # M # M#
                     ########

              #####
              # M #
              #####
              #####
              #####
              #####
###################
# # # ##   ## # # #
#M#M#M## E ##M#M#M#
# # # ##   ## # # #
###################
#######
######
#####
####
# M#
####

###############
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMME#
###############

```

# Answer
> 21 votes
# Perl, ~~216~~ 215 bytes

Includes +2 for `-0p`

Give input on STDIN. Use `%` for external walls, `#` for internal walls, `0` for empty spaces, `8` for mice and `r` for the starting position. The whole boards must be padded so it forms a rectangle. You can transform and run the examples as:

```
cat dynamite.txt | perl -p0e 's/.+/$a^=$&/egr;s//sprintf"%-*s",length$a,$&/eg;1while/\n/,s/^ *\K#|#(?= *$)|^ *.{@{-}}\K#|\A[^\n]*\K#|#(?=[^\n]*\n\z)|#(?=.{@{-}} *$)/%/sm;y/ EM/0x2/' | dynamite.pl

```

`dynamite.pl`:

```
#!/usr/bin/perl -0p
sub f{@a{@_}||=push@{$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)},@_}f$_;for(@{$%}){f y/xr|/ytx/r;{f s/\pL\d/$&^(E&$&)x2/er}{f s/(q|s|y)#/$&^"\x01\x13"/er}my$o;{$\|=/x/>/2/;$o.="
"while s/.$/$o.=$&,""/meg}f$o}$%++>999|$\||redo}{

```

Replace the `\xhh` escapes for the claimed score.

The program can't realistically handle complex cases. In particular it can't handle any of the failure cases. This is because there are just too many different ways of blowing up the internal walls or picking up mice so the search becomes too wide and uses too much memory even though it's at least smart enough to never process the same state multiple times. The pressure limit has to be lowered to `100` or so for somewhat bearable runtimes and memory usage.

## Explanation

I use the bit pattern of a character to represent the state of a field:

```
contains victim: 0000 0010
has hero:        0100 0000
carry dynamite   0000 0001
carry mouse      0000 0100
home             0000 1000
walkable         0001 0000 (not really needed but results in shorter regexes)
make printable   0010 0000
wall             0010 xxxx (bit patterns not very important,
permawall        0010 xxxx  just avoid letters and digits)

```

For example the hero (`01000000`) carrying dynamite (`00000001`) must be on a place he can walk (`00010000`) and we want all values to be printable ASCII (`00100000`). Taking the bitwise `or` of all these bitmasks gives `01110001` which is the ASCII code for `q`. In total this becomes::

```
p: hero                     r hero on victim
q: hero carrying dynamite   s hero carrying dynamite on victim
t: hero carrying mouse      v hero carrying mouse on victim

x : hero at home
y : hero at home carrying dynamite
| : hero at home carrying mouse

0: empty  without hero
8: home   without hero
2: victim without hero

%: permanent wall
#: normal wall

```

The program will only consider the hero moving to the right (the rotation explained later will take care of the other directions). The bitmasks were carefully chosen such that the hero is always represented by a letter and a place he can move to by a digit (except the hero at home carrying a victim, but again this is intentional so that the hero's only move will be to drop the victim). So a hero that can move forward is matched by `/\pL\d/`. The matched substring has to be modified so that the hero and what he is carrying is removed from the first character and added to the second one, which can be done with a bitwise `xor` with the same value for both characters. The xor value consists of the hero bit (`01000000`), the dynamite bit (`00000001`) and the carry mouse bit (`00000100`). Together they `or` to `01000101` which is ASCII `E`. So moving the hero becomes:

```
s/\pL\d/$&^(E&$&)x2/e

```

The hero can blow up a wall if he is standing right in front of it and is carrying dynamite (`q`, `s` or `y`). The hero will lose his dynamite (`xor` with `00000001`) and the wall `#` will change to a passage `0` (xor with `00010011`), so

```
s/(q|s|y)#/$&^"\x01\x13"/e

```

To handle the other directions the whole board is rotated (rotated board ends up in `$o`):

```
my$o;$o.="\n"while s/.$/$o.=$&,""/meg

```

Apart from moving the hero also has a number of other choices he can make:

```
When at home, pick up dynamite:                   x -> y
When on victim not carrying anything pick him up: r -> t
When at home carrying a victim, drop him off:     | -> x

```

This is done by

```
y/xr|/ytx/

```

The board is finished if the hero is at home carrying nothing (`x`) and there are no more victims to rescue (no `2`). This can be conveniently tested using

```
/x/>/2/

```

Once the board is solved I want to remember this state and at the end print it. For that I carry the "is solved" flag in `$\` and print that at the end of the program without printing `$_`, so

```
$\|=/x/>/2/  ...   }{

```

The states to be processed at pressure 0 are kept in `@0`, at pressure 1 on `@1` etc. The current pressure is kept in `$%`. Using `$n` or something like it would be shorter but the code doesn't work if the variable isn't initialized to something because autovivification will otherwise change `$n` to an ARRAY reference.Looping over the states at a certain pressure is done using a `for` and not a `map` because with a `for` you can extend the array while it is still being looped over and will pick up the new elements. This is needed because the rotations and single field choices of the hero happen in 0 time and end up in the same pressure array. So the loop for a given pressure is done by

```
for(@{$%}){...}

```

This is repeated until the pressure reaches 1000 or a solution is found:

```
$%++>999|$\||redo

```

All that is left is adding newly discovered states to their respective pressure arrays. That will be done by subroutine `f`. We only want to add a state if it has not been seen yet. States that have been seen before are kept in `%a` so:

```
sub f{@a{@_}||=push@$n, @_}

```

`$n` represents the new pressure for a state. I will derive that from the state that the regex variables still have as a result of the hero's action leading to this call:

```
if $1 is set it was from s/(q|s|y)#/$&^"\x01\x13"/e which blows a wall -> 50
else if $& is set it was from s/\pL\d/$&^(E&$&)x2/e, so the hero moves.
    if $& contains 8 the hero went home -> 0
    else if the hero has carry bits (5) -> 2
    else                                   1
else ($& was not set) it was from y/xr|/ytx/r -> 0

```

This leads to the following formula for `$n`:

```
$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)

```

All the substitutions get an `r` modifier so they return the changed state and leave the current state in `$_` alone. `f` is then called on this changed state, so you get code like

```
f y/xr|/ytx/r;

```

Because the calculation of `$n` needs the regex variables they must default to unset in case the substitutions changes nothing (because the condition to trigger them is not fulfilled). I must also not pick up any regex variables from a previous loop. Therefore the substitutions are wrapped in `{}` blocks to save and restore the regex state. That's how you get statements like

```
{f s/\pL\d/$&^(E&$&)x2/er}

```

In particular the rotation is so wrapped so it calls `f` without regex variables and gets a pressure contribution of 0.

The only thing still to do is to prime `@0` with the initial state at the start

```
f$_

```

This is in the main loop so it also tries to add `$_` to later pressure arrays, but since the initial state will already be in `%a` nothing will happen.

Together all this basically finds the shortest solution using Dijkstra's algorithm. There is a potential problem though. The current code won't add a state if it is rediscovered with a lower pressure than the first discovery. I've not been able to construct a board that would trigger this, but have also been unable to prove it is impossible.

# Answer
> 13 votes
# JavaScript, ~~863~~ ~~834~~ ~~785~~ 781 bytes

Saved 29 bytes thanks to ETHproductions
Saved 53 bytes thanks to Jordan

```
L=[]
f=(S,r="",R="",p=0,s=S.replace(RegExp(r),R),l=`((.|\n){${s.split`
`[0].length}})`,q=p+1,o=p+2,n=p+50)=>s in L|p>999?1e3:!/M/.test(s,L[s]=0)&/E/.test(s)?p:Math.min(...[[/ E/,"me",q],[/ E/,"de",o],[/ME/,"ce",q],[/E /,"em",q],[/E /,"ed",o],[/EM/,"ec",q],[`E${l} `,"e$1m",q],[`E${l} `,"e$1d",o],[`E${l}M`,"e$1c",q],[` ${l}E`,"m$1e",q],[` ${l}E`,"d$1e",o],[`M${l}E`,"c$1e",q],[/ m/,"m ",q],[/m /," m",q],[`m${l} `," $1m",q],[` ${l}m`,"m$1 ",q],[/ (d|c)/,"$1 ",o],[/(d|c) /," $1",o],[`(d|c)${l} `," $2$1",o],[` ${l}(d|c)`,"$3$1 ",o],[/d#/,"m ",n],[/#d/," m",n],[`#${l}d`," $1m",n],[`d${l}#`,"m$1 ",n],[/mM/," c",q],[/Mm/,"c ",q],[`M${l}m`,"c$1 ",q],[`m${l}M`," $1c",q],[/[mc]e/," E",p],[/e[mc]/,"E ",p],[`e${l}[mc]`,"E$1 ",p],[`[mc]${l}e`," $1E",p]].map(a=>f(s,...a)))
F=s=>f(s)<1e3

```

Takes input as a multiline string.

This defines an anonymous function that uses a recursive function `f` to determine if you trip off the alarm before retrieving all the mice. `f` returns `1000` if the pressure is above 1000 (to avoid endless recursion), returns the pressure if there are no more mice to rescue and the mouse in the exit, and returns the minimum pressure of all possible moves from the current state otherwise. It uses an array `L` to keep track of already visited positions where `L[pos]==0` if it is visited, and undefined if it isn't. This may not be necessary, but it prevents the mouse from doing useless moves and throwing recursion errors at the very least. (This does mean you should redefine `L` if you are testing this multiple times)

This uses the format in the question other than that it requires you to use a different character for the external walls. (Anything other than `# MEmecd`)

More readable version:

```
stateList = []
f=(s,regex="",replacement="",pressure=0,state=s.replace(regexp(regex),replacement),line=`((.|\n){${state.split("\n")[0].length}})`)=>{
    if (state in stateList || pressure > 999) return 1e3
    if (!/M/.test(state) && /E/.test(state)) return pressure

    stateList[state] = 0

    return [
        [/ E/,"me",pressure+1],
        [/ E/,"de",pressure+2],
        [/ME/,"ce",pressure+1],
        [/E /,"em",pressure+1],
        [/E /,"ed",pressure+2],
        [/EM/,"ec",pressure+1],
        [`E${line} `,"e$1m",pressure+1],
        [`E${line} `,"e$1d",pressure+2],
        [`E${line}M`,"e$1c",pressure+1],
        [` ${line}E`,"m$1e",pressure+1],
        [` ${line}E`,"d$1e",pressure+2],
        [`M${line}E`,"c$1e",pressure+1],
        [/ m/,"m ",pressure+1],
        [/m /," m",pressure+1],
        [`m${line} `," $1m",pressure+1],
        [` ${line}m`,"m$1 ",pressure+1],
        [/ ([dc])/,"$1 ",pressure+2],
        [/([dc]) /," $1",pressure+2],
        [`([dc])${line} `," $2$1",pressure+2],
        [` ${line}([dc])`,"$3$1 ",pressure+2],
        [/d#/,"m ",pressure+50],
        [/#d/," m",pressure+50],
        [`#${line}d`," $1m",pressure+50],
        [`d${line}#`,"m$1 ",pressure+50],
        [/mM/," c",pressure+1],
        [/Mm/,"c ",pressure+1],
        [`M${line}m`,"c$1 ",pressure+1],
        [`m${line}M`," $1c",pressure+1],
        [/[mc]e/," E",pressure],
        [/e[mc]/,"E ",pressure],
        [`e${line}[mc]`,"E$1 ",pressure],
        [`[mc]${line}e`," $1E",pressure]
    ].map(a=>f(state,...a)).reduce((a,b)=>a-b<0?a:b) //reduce used for support in more browsers.
}
s=>f(s)>1e3

```

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


# Question
Title: Smallest Hamming distance to a palindrome containing a substring
This was inspired by a now removed CS.SE question.

### Task

Given two non-empty input strings A and B, output the smallest distance from A to a palindrome that contains B as a substring. Distance is defined by the number of character replacements (Hamming distance).

### Restrictions

* Sensible input: a palindrome exists. This means |A| ≥ |B|.
* A and B contain only lower ASCII characters, lowercase and uppercase are distinct (as are all other characters).
* If your language cannot deal with ASCII characters, you may use integers (or some other reasonable data type) as well, and you may choose to limit the range to 128 elements.
* You may take input from stdin, function arguments, command line arguments, etc.
* You may give the result on stdout, return value, etc.
* You do not need to give a working palindrome, the smallest distance to one is sufficient.

### Examples

```
A                   B            Output
thilloaoyreot       hello        4 (thelloaolleht)
benjonson           stack        9 (stackcats)
neversaynever!      odd          9 (neveroddoreven)
ppcggcpp            gg           0 (ppcggcpp)
stars               tat          1 (stats)

```

### Scoring

This is code golf, shortest code in bytes wins.

# Answer
> 5 votes
# Pyth, 19 bytes

```
hSmsnVQd/#z_I#^+Qzl

```

Demonstration

Extreme brute force approach. Generate all strings of the appropriate length with characters in either string, filter for palindromes and for containing the second input, map to hamming distance from first string, output smallest.

Explanation:

```
hSmsnVQd/#z_I#^+Qzl
hSmsnVQd/#z_I#^+QzlQ     Variable introduction
                         Q = string A, z = string B.
               +Qz       Concatenate A and B
              ^   lQ     Form every string of length equal to len(A)using
                         characters from the concatenation.
             #           Filter on
           _I            Invariance under reversal (palindrome)
         #               Filter on
        / z              Nonzero occurences of B
  m                      Map to
    nV                   !=, vectorized over
      Qd                 A and the map input
   s                     Sum (gives the hamming weight)
hS                       Min

```

# Answer
> 3 votes
# Pyth, 45 bytes

```
hSmsnVQdf}zTsmm+hc2KsXcd+Bklz1z_hc2PKh-lQlz_B

```

Try it online. Test suite.

I'm still not exactly satisfied with how this turned out. But at least it's quite hard to understand without an explanation now. (Success, I guess?)

### Explanation

* Take in A as `Q` and B as `z`.
* `m``_BQ` Compute the following for both A and its reverse as `d`:
    + `m``h-ldlz` Compute the following for all `k` from 0 to `len(A) - len(B)` inclusive:
        - `+Bklz` Get the pair `k, k + len(B)`.
        - `cd` Split `d` at those indices.
        - `X``1z` Replace the second (middle) part with B.
        - `Ks` Concatenate the pieces and save to `K`. B is now inserted at position `k` in A or its reverse.
        - `hc2` Split the resulting string in two and keep the first piece. This gives half of the string with the possible middle character.
        - `hc2PK` Remove the last character and do the same split, keeping the first piece. This gives half of the string without the possible middle character.
        - `+``_` Add the reverse of the shorter piece to the longer piece. We now have a palindrome.
* `s` Concatenate the results for A and its reverse.
* `f}zT` Remove all strings that don't contain B.
* `m` Compute the following for all the resulting strings `d`:
    + `nVQd` Get the pairwise inequality with A. This gives True for pairs that need to be changed.
    + `s` Sum the list. This gives the Hamming distance.
* `hS` Take the minimum result.

# Answer
> 1 votes
# JavaScript (Firefox 30+), ~~152~~ 146 bytes

```
(A,B)=>Math.min(...[...Array(A[l='length']-B[l]+1)].map((_,i)=>[for(c of q=A.slice(j=t=0,i)+B+A.slice(i+B[l]))t+=(c!=A[j])+(c!=q[q[l]-++j])/2]|t))

```

Brute force approach: generate each possible overlap of A and B, make each into a palindrome, calculate Hamming distances from A, and take the smallest of the resulting distances.

Probably could be golfed a bit more...

### Test snippet

```
f=(A,B)=>Math.min(...[...Array(A[l='length']-B[l]+1)].map((_,i)=>[for(c of q=A.slice(j=t=0,i)+B+A.slice(i+B[l]))t+=(c!=A[j])+(c!=q[q[l]-++j])/2]|t))
g=(A,B)=>console.log("A:",A," B:",B," f(A,B):",f(A,B))

g("thilloaoyreot", "hello")
g("benjonson", "stack")
g("neversaynever!", "odd")
g("ppcggcpp", "gg")
```

```
<input id=A value="amanaplanacanalrussia">
<input id=B value="panama">
<button onclick="g(A.value,B.value)">Run</button>
```

---
Tags: code-golf, string, palindrome
---


title: How many times will a bell tower ring?

text:
# Question
Title: How many times will a bell tower ring?
# Introduction

A bell tower will ring its bells every hour, `n` times, with `n` being the the current hour on a 12 hour clock.

For example, a bell will ring 5 times at 5pm, and 10 times at 10am.

# Task

Given two times in a suitable format, output the number of times the bell will ring, inclusive of the start and end times

# Examples

```
"10am-12pm"
10+11+12= 33

[01:00, 05:00]
1+2+3+4+5 = 15

[11, 15]
11+12+1+2+3 = 29

[10:00pm, 10:00am]
10+11+12+1+2+3+4+5+6+7+8+9+10 = 88

```

If the start is the same as the end then the you simply just ouput the number of chimes for that hour:

```
[5pm, 5pm]
5 = 5

```

As you can see, you may choose an input method but the output must be an integer on its own (or an acceptable alternative) trailing/ leading newlines and spaces are allowed.

Note:

* inputs may span from the afternoon of one day to the morning of the next.
* the difference between the two times will never be more than 24 hours.
* input is flexible so long as you clearly state what format your input is.
* your input must have a **clear** distinction between AM and PM.

# Answer
> 12 votes
# JavaScript (ES6), ~~38~~ 35 bytes

```
f=(x,y)=>~-x%12-~(x-y&&f(x%24+1,y))

```

Recursively adds the current number of bell rings to the total. Called like `f(11,15)`; midnight is represented as `24`. I got part of the `~-` trick from @xnor's Python answer.

## Test snippet

```
f=(x,y)=>~-x%12-~(x-y&&f(x%24+1,y))
g=(x,y)=>console.log("x:",x,"y:",y,"result:",f(x,y))

g(10,12)
g(1,5)
g(11,15)
g(22,10)
```

```
<input id=A type="number" min=1 max=24 value=9>
<input id=B type="number" min=1 max=24 value=17>
<button onclick="g(A.value,B.value)">Run</button>
```

### Non-recursive version (Firefox 30+), 56 bytes

```
(x,y,t=0)=>[for(_ of Array((y-x+25)%24))t+=x++%12||12]|t

```

Equivalent to the following ES6 function:

```
(x,y,t=0)=>[...Array((y-x+25)%24))].map(_=>t+=x++%12||12)|t

```

# Answer
> 7 votes
# Python 2, 46 bytes

```
f=lambda x,y:(x%12or 12)+(x-y and f(-~x%24,y))

```

Based on my JS answer. The recursive formula **f** for the solution is defined as so:

1. Start with two integers **x** and **y**.
2. Take **x mod 12**; if this is 0, take **12** instead.
3. If **x != y**, add the result of **f(x+1 mod 24, y)**.

# Answer
> 6 votes
# Python 2, ~~59~~ 54 bytes

```
a=lambda x,y:sum(1+i%12for i in range(x-1,y+24*(x>y)))

```
Equivalent to
```
summ=0
if start > end:
    end+=24
for hour in range(start-1,end):
    summ +=1+hour%12
print summ

```

# Answer
> 3 votes
# 05AB1E, 13 bytes

With a lot of help from *Emigna*.

```
-24%Ý¹+<12%>O

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 3 votes
# Jelly, ~~17 16 15~~ 14 bytes

```
>×24+⁹⁸r’%12‘S

```

**TryItOnline**

How?

```
>×24+⁹⁸r’%12‘S - Main link: a, b (24 hr integers, midnight may be 0 or 24)
>              - a>b? (1 if true, 0 if false)
 ×24           - times 24 (24 if a>b, else 0)
    +⁹         - add to b (b+24 if a>b, else b)
      ⁸        - a
       r       - range(a, b+24 or b) ([a,a+1,...,b+24 or b])
        ’      - decrement (vectorises) ([a-1,a,...,b+23 or b-1])
         %12   - mod 12 (vectorises) (number of tolls at each occurrence - 1)
            ‘  - increment (vectorises) (number of tolls at each occurrence)
             S - sum

```

# Answer
> 3 votes
## Python, 42 bytes

```
f=lambda a,b:~-a%12-~(b-a and f(-~a%24,b))

```

A recursive function that takes two numbers from 0 to 23. Expanding the `~x`'s to `-x-1` gives

```
f=lambda a,b:(a-1)%12+1+(b-a and f((a+1)%24,b))

```

The expression `(a+1)%12+1` converts a time to the number of rings `1` to `12`. Then, the lower bound is incremented modulo 24 and the function for the recursive result is added. That is, unless the current hour is the end hour, in which case we stop.

I've been trying to write a purely arithmetical solution instead, but so far I've only found long and messy expressions.

# Answer
> 3 votes
## Haskell, 48 43 bytes

```
s%e=sum[mod x 12+1|x<-[s-1..e+23],x<e||s>e]

```

Usage is `startHour % endHour`, with both inputs given in 24-hr format.

*edit: added @xnor's improvement, saving 5 bytes*

# Answer
> 3 votes
# C#, 73 bytes

```
a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};

```

Acceptable input: integers in range \[0,23\].

**This solution does not use LINQ.**

---

Full program with test cases:

```
using System;

namespace HowManyTimesABellTowerRings
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,Func<int,int>>f= a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};

            Console.WriteLine(f(10)(12));   //33
            Console.WriteLine(f(1)(5));     //15
            Console.WriteLine(f(11)(15));   //29
            Console.WriteLine(f(22)(10));   //88
            Console.WriteLine(f(10)(10));   //10
            Console.WriteLine(f(11)(10));   //156
            Console.WriteLine(f(0)(23));    //156
            Console.WriteLine(f(22)(1));    //34
        }
    }
}

```

# Answer
> 2 votes
# PHP, 90 Bytes

Input format '\[1,24\]' between 1 and 24

In this challenge that I am hate why PHP loose against other languages. I prefer to show all my ideas. Maybe an other PHP Crack finds a shorter solution.

```
<?list($f,$g)=$_GET[b];for($i=$f;$i-1!=$g|$f>$g&!$c;$s+=$i++%12?:12)$i<25?:$c=$i=1;echo$s;

```

99 Bytes

```
<?for($i=($b=$_GET[b])[0],$c=($d=$b[1]-$b[0])<0?25+$d:$d+1;$c--;$s+=$i++%12?:12)$i<25?:$i=1;echo$s;

```

113 Bytes a way with min and max

```
<?for($i=min($b=$_GET[b]);$i<=$m=max($b);)$s+=$i++%12?:12;echo($b[0]>$b[1])?156-$s+($m%12?:12)+($b[1]%12?:12):$s;

```

okay this crazy idea works with an array 149 Bytes fills the array `$y[0]` and `$y[1]` if `$_GET["b"][0]<=$_GET["b"][1]` if `$y[1]` is `null` we can sum this array `array_diff_key($y[0],array_slice($y[0],$b[1],$b[0]-$b[1]-1,1))`

```
<?for(;++$i<25;)$y[$i>=($b=$_GET[b])[0]&$i<=$b[1]][$i]=$i%12?:12;echo array_sum($y[1]??array_diff_key($y[0],array_slice($y[0],$b[1],$b[0]-$b[1]-1,1)));

```

This could be golfed down 124 Bytes

```
<?for(;++$i<25;)$x[($v=($b=$_GET[b])[0]>$b[1])?$i<$b[0]&$i>$b[1]:$i>=$b[0]&$i<=$b[1]][$i]=$i%12?:12;echo array_sum($x[!$v]);

```

Now at this point we can reduce the array with only two ints 101 Bytes Make 2 sums `$x[0]` and `$x[1]`

`list($f,$g)=$_GET[b];`

if `$v=($f>$g` then add value to `$x[$i<$f&$i>$g]` else add value to `$x[$i>=$f&$i<=$g]` the output will be find by case `echo$x[!$v];`

```
<?list($f,$g)=$_GET[b];for(;++$i<25;)$x[($v=$f>$g)?$i<$f&$i>$g:$i>=$f&$i<=$g]+=$i%12?:12;echo$x[!$v];

```

After that i found a way to calculate the result directly 112 Bytes

```
<?list($x,$y)=$_GET[t];echo(($b=$x>$y)+(($x-($s=$x%12?:12)^$y-($t=$y%12?:12))xor$b))*78-($s*($s-1)-$t*($t+1))/2;

```

recursive 103 Bytes

```
<?list($x,$y)=$_GET[t];function f($x,$y){return($x%12?:12)+($x-$y?f(++$x<25?$x:1,$y):0);}echo f($x,$y);

```

# Answer
> 2 votes
# Java, ~~72~~ ~~71~~ ~~78~~ 76 bytes

```
Usage:
    pm:    true if first time is past 11am
    time:  first time%12
    pm2:   true if second time is past 11am
    time2: second time%12

```

**Edit**:

* ***-1** byte off. Thanks to @1Darco1*
* *Fixed function head. **+7** bytes on.*
* ***-2** bytes off. Thanks to @Kevin Cruijssen*
* ***+2** bytes on. Now `e`/`clock` is initialized.*

---

```
(a,b,c,d)->{int e=0;b+=a?12:0;d+=c?12:0;for(;b!=d;e+=b%12,b=++b%24);return e;}

```

Ungolfed:

```
public static int clock(boolean pm, int time, boolean pm2, int time2){
  int clock=0;
  time+=pm?12:0;
  time2+=pm2?12:0;
  while(time!=time2){
    clock+=time%12;
    time=++time%24;
  }
  return clock;
}

```

# Answer
> 2 votes
# MATL, 14 bytes

```
yy>24*+&:12X\s

```

Input format is as in the third example in the challenge, that is, two numbers in 24-hour format.

Try it online!

### Explanation

Take inputs `22`, `10` as an example.

```
yy      % Take two inputs implicitly. Duplicate both
        %   STACK: 22, 10, 22, 10
>       % Is the first greater than the second?
        %   STACK: 22, 10, 1
24*     % Multiply by 24
        %   STACK: 22, 10, 24
+       % Add
        %   STACK: 22, 34
&:      % Binary range
        %   STACK: [22 23 24 25 26 27 28 29 30 31 32 33 34]
12X\    % Modulo 12, 1-based
        %   STACK: [10 11 12 1 2 3 4 5 6 7 8 9 10]
s       % Sum of array
        %   STACK: 88
        % Implicitly display

```

# Answer
> 2 votes
# PHP, 69 bytes

```
list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;

```

The list extraction was inspired by Jörg Hülsermann's answer but the rest of the similarities are a result of convergent evolution and because it's quite a lot shorter and the conditionals in the loop are different enough I'm posting it as a separate answer.

Takes input as 24 hour times (fine with either 0 or 24). Run like:

```
php -r "list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;" 9 18

```

# Answer
> 1 votes
## QBIC, ~~90~~ 47 bytes

So, here's the answer printing only the total number of bell-rings:

```
::{c=a~c>12|c=c-12]d=d+c~a=b|_Xd]a=a+1~a>24|a=1

```

Input is in range `1-24`; `a` and `b` are the inputs (`::` in the code), `c` keeps track of am/pm, `d` is the total number of rings. When we've counted down all the hours, `_Xd` terminates the program, printing `d` in the process.

---

OK, I misunderstood the question and thought the `1+2+3...=` text was part of the output, so I wrote that:

```
::{c=a~c>12|c=c-12]X=!c$Z=Z+X+@+| d=d+c~a=b|?left$$|(Z,len(Z)-1)+@ =|+!d$_X]a=a+1~a>24|a=1

```

Now, I'll go code the proper answer...

# Answer
> 1 votes
# Pyth - 11 bytes

```
s|R12%R12}F

```

Test Suite.

# Answer
> 1 votes
## C#, 76 bytes

```
(a,b)=>Enumerable.Range(a,Math.Abs(b-a)+1).Select(n=>n%12==0?12:n%12).Sum();

```

# Answer
> 1 votes
# Perl, 36 bytes

Includes +1 for `-p`

Give start and end time in 24-hour format on a line each on STDIN:

```
toll.pl
11
15
^D

```

`toll.pl`:

```
#!/usr/bin/perl -p
$\+=$_%12||12for$_..$_+(<>-$_)%24}{

```

# Answer
> 1 votes
# \>\<\>, 48 + 2 = 50 bytes

```
<v$&%$-&:$+}:*2c
{>:?!v1-}:1+
v?=1l<++1%c+b$
>n;

```

Input is expected to be present on the stack at program start, so +2 bytes for the `-v` flag. Input is two integers specifying the hour on the 24 hour clock, so `10am - 10pm` would be given as `10 22`.

Try it online!

# Answer
> 1 votes
## Batch, ~~168~~ 91 bytes

```
@cmd/cset/ax=(%1+23)%%24,y=x+(%2+24-%1)%%24,z=y%%12+1,(y/12-x/12)*78+z*-~z/2-(x%%=12)*-~x/2

```

Edit: Saved 77 byte by switching to a closed form for the answer.

* `%1` and `%2` are the two command-line parameters
* `@` Disable Batch's default which is to echo the command
* `cmd/c` Fool Batch into immediately printing the result of the calculation
* `set/a` Perform a numeric calculation
* `x=(%1+23)%%24,` Normalise the starting hour to be the number of hours since 1AM (1PM would also work, but 11 is no shorter than 23)
* `y=x+(%2+24-%1)%%24,` Normalise the ending hour to be ahead of the starting hour, advancing to the next day if necessary
* `z=y%%12+1,` Number of bells struck at the ending hour
* `(y/12-x/12)*78+` Number of bells due to extra half days
* `z*~-z/2-` Number of bells from 1 o'clock to the ending hour inclusive
* `(x%%=12)` One less than the number of bells struck at the starting hour
* `*-~x/2` Number of bells that would have been struck from 1 o'clock to the starting hour, but not including the starting hour

# Answer
> 1 votes
# Java 7, 64 bytes

```
int c(int x,int y){return(x%12<1?12:x%12)+(x!=y?c(-~x%24,y):0);}

```

Recursive method based on *@ETHproductions*'s Python 2 answer. Uses a 24-hour clock input.

**Ungolfed & test code:**

Try it here.

```
class M{
  static int c(int x, int y){
    return (x%12 < 1
             ? 12
             : x%12)
         + (x != y
             ? c(-~x % 24, y)
             : 0);
  }

  public static void main(String[] a){
    System.out.println(c(10, 12));
    System.out.println(c(1, 5));
    System.out.println(c(11, 15));
    System.out.println(c(10, 22));
    System.out.println(c(5, 5));
  }
}

```

**Output:**

```
33
15
29
88
5

```

# Answer
> 1 votes
### C, 56 Bytes

```
f(a,b,c=0){while(b-->a){c+=b>12?b-12:b;}printf("%d",c);}

```

# Answer
> 1 votes
# Cubix, ~~45~~ 44 bytes

*Saved 1 byte, thanks to @ETHproductions*

My first foray into Cubix...

```
)$424tU4OI0Iuq;;-!^;^%&21u+rr;ss!;sqU>&%r$@;

```

Or, cubified:

```
      ) $ 4
      2 4 t
      U 4 O
I 0 I u q ; ; - ! ^ ; ^
% & 2 1 u + r r ; s s !
; s q U > & % r $ @ ; .
      . . .
      . . .
      . . .

```

You can try it out at the online interpreter. Input is in 24 hour format, with the end time first. For example, from 5pm to 1am the input should be `1 17`.

---

Previous version, 45 bytes:

```
)$442t\/OI0Iuq;;-!^;^%&21u+rr;ss!;sqU>&%r$@.;

```

# Answer
> 0 votes
# Qbasic, 112 bytes

```
input "",a
input "",b
do
if a=25 then a=1
if a<=12 then
c=c+a
else
c=c+a-12
endif
a=a+1
loop until a=b+1
print c

```

# Answer
> 0 votes
# Python, 73 bytes

It would be so much shorter if we didn't have to support `pm` to `am`. I use recursion to support it.

```
f=lambda a,b:sum([~-i%12+1for i in range(a,b+1)]*(a<b)or[f(a,24),f(1,b)])

```

**Try it online**

Without supporting `pm` to `am` (45 bytes):

```
lambda a,b:sum(~-i%12+1for i in range(a,b+1))

```

---
Tags: code-golf, clock
---