title: Square, diamond, square, diamond

text:
# Question
Title: Square, diamond, square, diamond
# Task

Given a non-empty string of lowercase ASCII letters `a`-`z`, take its first character, and:

* Surround it with a square of copies of the **second** character,
* Surround that with a diamond of copies of the **third** character,
* Surround that with a square of copies of the **fourth** character…

…alternating between square and diamond borders until the end of the string. Empty space between the borders should be represented by ASCII spaces ().

To add a **square** border, draw a square exactly around the entire current “working array”:

```
                                               sssssssssss
                                t              s    t    s
                               t t             s   t t   s
                              t   t            s  t   t  s
                             t aaa t           s t aaa t s
                            t  aca  t    =>    st  aca  ts
                             t aaa t           s t aaa t s
                              t   t            s  t   t  s
                               t t             s   t t   s
                                t              s    t    s
                                               sssssssssss

```

To add a **diamond** border, draw a centered diamond shape that touches the outermost square *diagonally*, but not *orthogonally*:

```
                                                     s
                                                    s s
                                                   s   s
                                                  s     s
                                                 s       s
                                                s         s
                                               s           s
                    wwwwwwwwwww               s wwwwwwwwwww s
                    w    o    w              s  w    o    w  s
                    w   o o   w             s   w   o o   w   s
                    w  o   o  w            s    w  o   o  w    s
                    w o eee o w           s     w o eee o w     s
                    wo  eme  ow    =>    s      wo  eme  ow      s
                    w o eee o w           s     w o eee o w     s
                    w  o   o  w            s    w  o   o  w    s
                    w   o o   w             s   w   o o   w   s
                    w    o    w              s  w    o    w  s
                    wwwwwwwwwww               s wwwwwwwwwww s
                                               s           s
                                                s         s
                                                 s       s
                                                  s     s
                                                   s   s
                                                    s s
                                                     s

```

Your program must output the final array.

* Each line may contain any amount of trailing spaces.
* You may output a list of strings representing lines, or a single newline-separated string with an optional trailing newline.
* Leading/trailing blank lines are disallowed.
* Leading columns of spaces are also disallowed.

This is . The shortest code in bytes wins.

# Test cases

The above examples are expected outputs for `cat`, `cats`, `meow`, and `meows`, in reading order. Some other cases worth handling:

* For the input `a`, your program should output:

```
a

```
* For the input `ab`, your program should output:

```
bbb
bab
bbb

```
* For the input `codegolf`, your program should output:

```
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
f                            l                            f
f                           l l                           f
f                          l   l                          f
f                         l     l                         f
f                        l       l                        f
f                       l         l                       f
f                      l           l                      f
f                     l             l                     f
f                    l               l                    f
f                   l                 l                   f
f                  l                   l                  f
f                 l                     l                 f
f                l                       l                f
f               l                         l               f
f              l                           l              f
f             l ooooooooooooooooooooooooooo l             f
f            l  o            g            o  l            f
f           l   o           g g           o   l           f
f          l    o          g   g          o    l          f
f         l     o         g     g         o     l         f
f        l      o        g       g        o      l        f
f       l       o       g         g       o       l       f
f      l        o      g           g      o        l      f
f     l         o     g eeeeeeeeeee g     o         l     f
f    l          o    g  e    d    e  g    o          l    f
f   l           o   g   e   d d   e   g   o           l   f
f  l            o  g    e  d   d  e    g  o            l  f
f l             o g     e d ooo d e     g o             l f
fl              og      ed  oco  de      go              lf
f l             o g     e d ooo d e     g o             l f
f  l            o  g    e  d   d  e    g  o            l  f
f   l           o   g   e   d d   e   g   o           l   f
f    l          o    g  e    d    e  g    o          l    f
f     l         o     g eeeeeeeeeee g     o         l     f
f      l        o      g           g      o        l      f
f       l       o       g         g       o       l       f
f        l      o        g       g        o      l        f
f         l     o         g     g         o     l         f
f          l    o          g   g          o    l          f
f           l   o           g g           o   l           f
f            l  o            g            o  l            f
f             l ooooooooooooooooooooooooooo l             f
f              l                           l              f
f               l                         l               f
f                l                       l                f
f                 l                     l                 f
f                  l                   l                  f
f                   l                 l                   f
f                    l               l                    f
f                     l             l                     f
f                      l           l                      f
f                       l         l                       f
f                        l       l                        f
f                         l     l                         f
f                          l   l                          f
f                           l l                           f
f                            l                            f
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff

```

# Reference implementation

I wrote some Julia code that your program’s output should match (at least visually). **Try it online!**

# Answer
> 6 votes
# MATL, ~~63~~ 54 bytes

```
l&)"X@o?TT@I$Ya}t&n2/Xkw2+-|thYa9Mqt_w&:|&+tleXM=@*+]c

```

**Try it Online!**

**Explanation**

```
            % Implicitly grab the input as a string
l&)         % Separate the first letter from the rest and push them onto the stack
"           % For every letter in the string besides the first
  X@o?      % If this is an odd iteration through the loop
    TT      % Push the array [1, 1]
    @       % Get current character
    I$Ya    % Pad the matrix with 1 copy of this character on all sides
  }         % Else (this is a diamond)
    t       % Duplicate the matrix
    &n      % Determine the number of rows and columns (push separately to stack)
    2/Xk    % Compute the radius (half the # of columns rounded up)
    w2+     % Flip the stack to get the # of rows and add 2. This is the new radius.
    -|      % Subtract the new and old radii and take the absolute value
    thYa    % Apply the necessary number of padding zeros to the matrix
    9Mqt_w&:% Generate the array [-radius ... 0 ... radius]
    |&+     % Take the absolute value and compute the element-wise sum with itself
            % and automatically broadcast to a matrix. For a radius of 5 this yields
            % the following:
            %
            %   8   7   6   5   4   5   6   7   8
            %   7   6   5   4   3   4   5   6   7
            %   6   5   4   3   2   3   4   5   6
            %   5   4   3   2   1   2   3   4   5
            %   4   3   2   1   0   1   2   3   4
            %   5   4   3   2   1   2   3   4   5
            %   6   5   4   3   2   3   4   5   6
            %   7   6   5   4   3   4   5   6   7
            %   8   7   6   5   4   5   6   7   8
            %
    tleXM   % Duplicate and compute the mode of this matrix (4 in the example above)
    =@*     % Find the locations where the matrix is equal to the mode and
            % replace with the current character. Set all else to 0.
    +       % Add this to the padded version of the previous iteration.
 ]          % End of if...else
 c          % Cast the current matrix as a character array (zeros are spaces)
            % Implicit end of for loop and implicit display

```

# Answer
> 17 votes
# JavaScript (ES6), ~~294~~ ~~288~~ ~~287~~ ~~284~~ ~~256~~ ~~246~~ ~~240~~ ~~238~~ 220 bytes

My first golf on this site. Pass input string to function `f`, e.g. `f('codegolf')`

```
f=s=>{N=n=>(2<<n/2+.5)-3-n%2
D=N(l=s.length)
for(a=[],i=S=D*2+1;i--;)a[i]=a[S+~i]=Array(S).fill` `
for(;l--;)for(o=n=N(l+1),I=0;I<=n;I++,o-=~l&1)a[y=D+I][x=D+o]=a[x][y]=a[y][D-o]=a[x][D-I]=s[l]
return a.map(r=>r.join``)}
```

*-6 bytes thanks to @Sunny Pun: Remove parentheses when passing template strings.*

*-2 bytes thanks to @ETHproductions: Change `S-i-1` to `S+~i`, `l%2||o--` to `o-=~l&1`.<br>*

*-18 bytes per suggestions of @Sunny Pun, @edc65: Remove `prompt()` and `console.log()` in favor of function format, don't `.join()` final array of strings*

# Answer
> 11 votes
# Haskell, ~~138~~ ~~137~~ 136 bytes

```
q 1=0
q x=(mod x 2+1)*(q(x-1)+1)
f x|m<-q$length x,n<-abs<$>[-m..m]=[do j<-n;max" "[c|(k,c)<-zip[1..]x,cycle[max i j,i+j]!!k==q k]|i<-n]

```

Defines a function `f` which returns the result as a list of lines

*-1 byte thanks to @Lynn*

# Answer
> 8 votes
# C++ - 373 366 362 359 bytes

*-1 by @TuukkaX, -6 by @Kevin Cruijssen, -4 by imports, -3 by @Baum mit Augen*

```
#import<string>
#import<vector>
#define A(x) abs(x-r)
using S=std::string;using V=std::vector<S>;int R(int n){return n?(n%2)?R(n-1)+1:2*R(n-1)+2:0;}V f(S w){int l=w.size(),r=R(l-1),s=r*2+1,i,j,k;V x(s);for(i=0;i<s;++i){x[i]=S(s,46);for(j=0;j<s;++j)for(k=0;k<l;++k){if(A(i)<=R(k)&A(j)<=R(k)&k%2?A(i)==R(k)|A(j)==R(k):(A(i)+A(j)==R(k)))x[i][j]=w[k];}}return x;}

```

http://ideone.com/5y54mx

Note: This solution uses the dot ('.') as "space" character to make the empty spaces more visible. To use a space instead, one has to change `S(s,46)` to `S(s,32)`. The score remains the same.

Ungolfed:

```
#import<string>
#import<vector>

#define A(x) abs(x-r) //r will be the center coordinate

using S=std::string;
using V=std::vector<S>;

int R(int n){ //recursive function returning the radius of a square/diamond
    return n?  //if(n!=0)
        (n%2)? //if(n%2 != 0)
            R(n-1)+1 //square -> just increase radius by 1
        :
            2*R(n-1)+2 //diamond -> radius doubles + 2
    :
        0 //n==0 -> end of recursion
    ;
}

V f(S w){ //function taking a string and returning a vector<string>
    int l=w.size(),r=R(l-1),s=r*2+1,i,j,k;  //r is radius (==center coord), s is size
    V x(s);  //vector<string>
    for(i=0;i<s;++i){  //loop over vector
        x[i]=S(s,46); //initialize string with dots. use 32 for spaces
        for(j=0;j<s;++j)
            for(k=0;k<l;++k){ //loop over word
                if(
                    A(i)<=R(k) //check bounds
                    &
                    A(j)<=R(k)
                    &
                    k%2?A(i)==R(k)|A(j)==R(k):(A(i)+A(j)==R(k))
                    //for square: check if distance to center of one coordinate = R
                    //for diamond: check if sum of distances = R
                )
                    x[i][j]=w[k]; //if any is true, replace default char
            }
    }

    return x;
}

```

Try ungolfed online

How to use:

```
include<iostream>

void printSquare(std::string word){
    auto result = f(word);
    for(auto& s:result)
        std::cout << s << std::endl;
    std::cout << std::endl << std::endl;
}

int main() {
    printSquare("a");
    printSquare("ab");
    printSquare("cat");
    printSquare("cats");
    printSquare("meow");
    printSquare("meows");
    printSquare("codegolf");
    return 0;
}

```

Output:

```
a

bbb
bab
bbb

....t....
...t.t...
..t...t..
.t.aaa.t.
t..aca..t
.t.aaa.t.
..t...t..
...t.t...
....t....

sssssssssss
s....t....s
s...t.t...s
s..t...t..s
s.t.aaa.t.s
st..aca..ts
s.t.aaa.t.s
s..t...t..s
s...t.t...s
s....t....s
sssssssssss

wwwwwwwwwww
w....o....w
w...o.o...w
w..o...o..w
w.o.eee.o.w
wo..eme..ow
w.o.eee.o.w
w..o...o..w
w...o.o...w
w....o....w
wwwwwwwwwww

............s............
...........s.s...........
..........s...s..........
.........s.....s.........
........s.......s........
.......s.........s.......
......s...........s......
.....s.wwwwwwwwwww.s.....
....s..w....o....w..s....
...s...w...o.o...w...s...
..s....w..o...o..w....s..
.s.....w.o.eee.o.w.....s.
s......wo..eme..ow......s
.s.....w.o.eee.o.w.....s.
..s....w..o...o..w....s..
...s...w...o.o...w...s...
....s..w....o....w..s....
.....s.wwwwwwwwwww.s.....
......s...........s......
.......s.........s.......
........s.......s........
.........s.....s.........
..........s...s..........
...........s.s...........
............s............

fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
f............................l............................f
f...........................l.l...........................f
f..........................l...l..........................f
f.........................l.....l.........................f
f........................l.......l........................f
f.......................l.........l.......................f
f......................l...........l......................f
f.....................l.............l.....................f
f....................l...............l....................f
f...................l.................l...................f
f..................l...................l..................f
f.................l.....................l.................f
f................l.......................l................f
f...............l.........................l...............f
f..............l...........................l..............f
f.............l.ooooooooooooooooooooooooooo.l.............f
f............l..o............g............o..l............f
f...........l...o...........g.g...........o...l...........f
f..........l....o..........g...g..........o....l..........f
f.........l.....o.........g.....g.........o.....l.........f
f........l......o........g.......g........o......l........f
f.......l.......o.......g.........g.......o.......l.......f
f......l........o......g...........g......o........l......f
f.....l.........o.....g.eeeeeeeeeee.g.....o.........l.....f
f....l..........o....g..e....d....e..g....o..........l....f
f...l...........o...g...e...d.d...e...g...o...........l...f
f..l............o..g....e..d...d..e....g..o............l..f
f.l.............o.g.....e.d.ooo.d.e.....g.o.............l.f
fl..............og......ed..oco..de......go..............lf
f.l.............o.g.....e.d.ooo.d.e.....g.o.............l.f
f..l............o..g....e..d...d..e....g..o............l..f
f...l...........o...g...e...d.d...e...g...o...........l...f
f....l..........o....g..e....d....e..g....o..........l....f
f.....l.........o.....g.eeeeeeeeeee.g.....o.........l.....f
f......l........o......g...........g......o........l......f
f.......l.......o.......g.........g.......o.......l.......f
f........l......o........g.......g........o......l........f
f.........l.....o.........g.....g.........o.....l.........f
f..........l....o..........g...g..........o....l..........f
f...........l...o...........g.g...........o...l...........f
f............l..o............g............o..l............f
f.............l.ooooooooooooooooooooooooooo.l.............f
f..............l...........................l..............f
f...............l.........................l...............f
f................l.......................l................f
f.................l.....................l.................f
f..................l...................l..................f
f...................l.................l...................f
f....................l...............l....................f
f.....................l.............l.....................f
f......................l...........l......................f
f.......................l.........l.......................f
f........................l.......l........................f
f.........................l.....l.........................f
f..........................l...l..........................f
f...........................l.l...........................f
f............................l............................f
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+............................................................+............................................................+
+...........................................................+.+...........................................................+
+..........................................................+...+..........................................................+
+.........................................................+.....+.........................................................+
+........................................................+.......+........................................................+
+.......................................................+.........+.......................................................+
+......................................................+...........+......................................................+
+.....................................................+.............+.....................................................+
+....................................................+...............+....................................................+
+...................................................+.................+...................................................+
+..................................................+...................+..................................................+
+.................................................+.....................+.................................................+
+................................................+.......................+................................................+
+...............................................+.........................+...............................................+
+..............................................+...........................+..............................................+
+.............................................+.............................+.............................................+
+............................................+...............................+............................................+
+...........................................+.................................+...........................................+
+..........................................+...................................+..........................................+
+.........................................+.....................................+.........................................+
+........................................+.......................................+........................................+
+.......................................+.........................................+.......................................+
+......................................+...........................................+......................................+
+.....................................+.............................................+.....................................+
+....................................+...............................................+....................................+
+...................................+.................................................+...................................+
+..................................+...................................................+..................................+
+.................................+.....................................................+.................................+
+................................+.......................................................+................................+
+...............................+.........................................................+...............................+
+..............................+...........................................................+..............................+
+.............................+.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.+.............................+
+............................+..C............................r............................C..+............................+
+...........................+...C...........................r.r...........................C...+...........................+
+..........................+....C..........................r...r..........................C....+..........................+
+.........................+.....C.........................r.....r.........................C.....+.........................+
+........................+......C........................r.......r........................C......+........................+
+.......................+.......C.......................r.........r.......................C.......+.......................+
+......................+........C......................r...........r......................C........+......................+
+.....................+.........C.....................r.............r.....................C.........+.....................+
+....................+..........C....................r...............r....................C..........+....................+
+...................+...........C...................r.................r...................C...........+...................+
+..................+............C..................r...................r..................C............+..................+
+.................+.............C.................r.....................r.................C.............+.................+
+................+..............C................r.......................r................C..............+................+
+...............+...............C...............r.........................r...............C...............+...............+
+..............+................C..............r...........................r..............C................+..............+
+.............+.................C.............r.ooooooooooooooooooooooooooo.r.............C.................+.............+
+............+..................C............r..o............F............o..r............C..................+............+
+...........+...................C...........r...o...........F.F...........o...r...........C...................+...........+
+..........+....................C..........r....o..........F...F..........o....r..........C....................+..........+
+.........+.....................C.........r.....o.........F.....F.........o.....r.........C.....................+.........+
+........+......................C........r......o........F.......F........o......r........C......................+........+
+.......+.......................C.......r.......o.......F.........F.......o.......r.......C.......................+.......+
+......+........................C......r........o......F...........F......o........r......C........................+......+
+.....+.........................C.....r.........o.....F.eeeeeeeeeee.F.....o.........r.....C.........................+.....+
+....+..........................C....r..........o....F..e....t....e..F....o..........r....C..........................+....+
+...+...........................C...r...........o...F...e...t.t...e...F...o...........r...C...........................+...+
+..+............................C..r............o..F....e..t...t..e....F..o............r..C............................+..+
+.+.............................C.r.............o.F.....e.t.ooo.t.e.....F.o.............r.C.............................+.+
++..............................Cr..............oF......et..oVo..te......Fo..............rC..............................++
+.+.............................C.r.............o.F.....e.t.ooo.t.e.....F.o.............r.C.............................+.+
+..+............................C..r............o..F....e..t...t..e....F..o............r..C............................+..+
+...+...........................C...r...........o...F...e...t.t...e...F...o...........r...C...........................+...+
+....+..........................C....r..........o....F..e....t....e..F....o..........r....C..........................+....+
+.....+.........................C.....r.........o.....F.eeeeeeeeeee.F.....o.........r.....C.........................+.....+
+......+........................C......r........o......F...........F......o........r......C........................+......+
+.......+.......................C.......r.......o.......F.........F.......o.......r.......C.......................+.......+
+........+......................C........r......o........F.......F........o......r........C......................+........+
+.........+.....................C.........r.....o.........F.....F.........o.....r.........C.....................+.........+
+..........+....................C..........r....o..........F...F..........o....r..........C....................+..........+
+...........+...................C...........r...o...........F.F...........o...r...........C...................+...........+
+............+..................C............r..o............F............o..r............C..................+............+
+.............+.................C.............r.ooooooooooooooooooooooooooo.r.............C.................+.............+
+..............+................C..............r...........................r..............C................+..............+
+...............+...............C...............r.........................r...............C...............+...............+
+................+..............C................r.......................r................C..............+................+
+.................+.............C.................r.....................r.................C.............+.................+
+..................+............C..................r...................r..................C............+..................+
+...................+...........C...................r.................r...................C...........+...................+
+....................+..........C....................r...............r....................C..........+....................+
+.....................+.........C.....................r.............r.....................C.........+.....................+
+......................+........C......................r...........r......................C........+......................+
+.......................+.......C.......................r.........r.......................C.......+.......................+
+........................+......C........................r.......r........................C......+........................+
+.........................+.....C.........................r.....r.........................C.....+.........................+
+..........................+....C..........................r...r..........................C....+..........................+
+...........................+...C...........................r.r...........................C...+...........................+
+............................+..C............................r............................C..+............................+
+.............................+.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.+.............................+
+..............................+...........................................................+..............................+
+...............................+.........................................................+...............................+
+................................+.......................................................+................................+
+.................................+.....................................................+.................................+
+..................................+...................................................+..................................+
+...................................+.................................................+...................................+
+....................................+...............................................+....................................+
+.....................................+.............................................+.....................................+
+......................................+...........................................+......................................+
+.......................................+.........................................+.......................................+
+........................................+.......................................+........................................+
+.........................................+.....................................+.........................................+
+..........................................+...................................+..........................................+
+...........................................+.................................+...........................................+
+............................................+...............................+............................................+
+.............................................+.............................+.............................................+
+..............................................+...........................+..............................................+
+...............................................+.........................+...............................................+
+................................................+.......................+................................................+
+.................................................+.....................+.................................................+
+..................................................+...................+..................................................+
+...................................................+.................+...................................................+
+....................................................+...............+....................................................+
+.....................................................+.............+.....................................................+
+......................................................+...........+......................................................+
+.......................................................+.........+.......................................................+
+........................................................+.......+........................................................+
+.........................................................+.....+.........................................................+
+..........................................................+...+..........................................................+
+...........................................................+.+...........................................................+
+............................................................+............................................................+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

```

# Answer
> 4 votes
# Mathematica, 167 bytes

```
Grid@Fold[g=Normal@SparseArray[h=f;a_List/;Plus@@Abs[a-#-1]==#->#3,2{#,#}+1]+a[#2,#/2+1]&[Length@#+1,#,#2]&;h=f=(h=g;a=ArrayPad)[#,1,#2]&;h@##&,{{#}},{##2}]/.Rule[0,]&

```

The input must be a list of characters.

e.g.

```
Grid@Fold[ ... ]/.Rule[0,]&["i","n","p","u","t"]

```

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

```
f=([c,...r],a,n,d)=>c?a?d?f(r,[...Array(m=n+n+3)].map((_,i,b)=>b.map((_,j)=>(a[i-g]||[])[j-g]||(i+j-h&&j+h-i&&h+i-j&&i+j-h*3?` `:c)),h=m>>1,g=m-n>>1),m,0):f(r,[b=[...a].fill(c),...a,b].map(b=>[c,...b,c]),n+2,1):f(r,[[c]],1,0):a.map(b=>b.join``).join`\n`
```

```
<input oninput=o.textContent=this.value&&f(this.value)><pre id=o>
```

Where `\n` represents the literal newline character.

# Answer
> 3 votes
# JavaScript (ES6), 204 ~~229 238~~

An anonymous function returning an array of strings

```
s=>[...s].map(v=>{T=(x,y)=>((r=[...c[y+z]||' '.repeat(z+z)])[z+x]=r[z-x]=v,c[z+y]=c[z-y]=r.join``);for(y=o-~o,o*=++i%2+1;y--;i%2?T(q,y):T(o,q,T(q,o)))q=y-o;++o},l=s.length,z=(2<<-~l/2)-3-l%2,c=[i=o=0])&&c

```

*Less golfed*

```
s=>(
  l = s.length,
  z = (2 << l/2 + .5) - 3 - l%2, // zero position, total width and height are z+z+1
  c = [], // output canvas
  o = 0, // base drawing offset from z
  [...s].map( (v, i) => {
    // execute for each char v at position i in input string
    // helper function to put current char v at position (z+y, z+x),(z+y,z-x),(z-y,z+x),(z-y,z-x)
    // as the image has vertical and horizontal symmetry
    T=(x,y) =>(
      r = [...c[y+z]||' '.repeat(z+z)]), // convert string to array to set char at given pos
      r[z+x] = v,
      r[z-x] = v,
      c[z+y] = c[z-y] = r.join`` // array to string again
    );
    // shorter than if(i%2) {for ...}else{for ...}
    // o is doubled at every other step
    //   and incremented (below) at each step
    for(y=o+o, i % 2 ? 0 : o=o*2; y >= 0; y--)
      q = y-o,
      i % 2 // even and odd steps have different shapes
        ? ( T(o,q), T(q,o))
        : T(q,y);
    ++o
  }),
  c
)

```

**Test**

```
f=
s=>[...s].map(v=>{T=(x,y)=>((r=[...c[y+z]||' '.repeat(z+z)])[z+x]=r[z-x]=v,c[z+y]=c[z-y]=r.join``);for(y=o-~o,o*=++i%2+1;y--;i%2?T(q,y):T(o,q,T(q,o)))q=y-o;++o},l=s.length,z=(2<<-~l/2)-3-l%2,c=[i=o=0])&&c

function update()
{
  O.textContent=f(I.value).join`\n`
}

update()
```

```
<input id=I value=CodeGolf oninput='update()'>
<pre id=O></pre>
```

# Answer
> 2 votes
## Java - 429 417 bytes

```
int r,l;int D(int n){return Math.abs(n-r);}int R(int n){return n=(n!=0)?((n%2!=0)?(R(n-1)+1):(2*R(n-1))+2):n;}char[][]C(String a){char[]c=a.toCharArray();l=a.length();r=R(l-1);int s=r*2+1,i,j,k;char[][]x=new char[s][s];for(i=0;i<s;i++){for(j=0;j<s;j++){x[i][j]=' ';for(k=0;k<l;k++){if(D(i)<=R(k)&&D(j)<=R(k)){if(k%2!=0){if(D(i)==R(k)||D(j)==R(k)){x[i][j]=c[k];}}else{if(D(i)+D(j)==R(k)){x[i][j]=c[k];}}}}}}return x;}

```

Credit goes to @Anedar as it was an influence on the structure of this answer

*Ungolfed:*

```
int r, l;

int D(int n) {
    return Math.abs(n - r);
}

int R(int n) {
    return n = (n != 0) ? ((n % 2 != 0) ? (R(n - 1) + 1) : (2 * R(n - 1)) + 2) : n;
}

char[][] C(String a) {
    char[] c = a.toCharArray();
    l = a.length();
    r = R(l - 1);
    int s = r * 2 + 1, i, j, k;
    char[][] x = new char[s][s];
    for (i = 0; i < s; i++) {
        for (j = 0; j < s; j++) {
            x[i][j] = ' ';
            for (k = 0; k < l; k++) {
                if (D(i) <= R(k) && D(j) <= R(k)) {
                    if (k % 2 != 0) {
                        if (D(i) == R(k) || D(j) == R(k)) {
                            x[i][j] = c[k];
                        }
                    } else if (D(i) + D(j) == R(k)) {
                        x[i][j] = c[k];
                    }
                }
            }
        }
    }
    return x;
}

```

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

**Non Competitive**

```
var L=s=>{var A=Array,a,D,c,d=-1,i,k,w,O,Z,P=(u,v)=>{Z=O-(d>>1);a[D?u-v+O:u+Z][D?u+v+O-d+1:v+Z]=c},G=(c,i)=>(D=~i&1)?(d+=2,w=2*d-1):(d+=d+1,w=d);s=[...s];s.map(G);a=A(w).fill(0).map(a=>A(w).fill` `);O=w>>1;d=-1;s.map((C,i)=>{G(0,i);c=C;for(k=d;k--;)P(0,k),P(d-1,k),P(k,0),P(k,d-1)});return a.map(v=>v.join("")).join("\n")}

```

**Less Golphed**

```
var L=s=>{
    var A=Array,a,D,c,d=-1,i,k,w,O,Z
    P=(u,v)=>{
        Z=O-(d>>1)
        a[D?u-v+O:u+Z][D?u+v+O-d+1:v+Z]=c},
    G=(c,i)=>(D=~i&1)?(d+=2,w=2*d-1):(d+=d+1,w=d)
    s=[...s]
    s.map(G)
    a=A(w).fill(0).map( a=>A(w).fill` `)
    O=w>>1
    d=-1
    s.map((C,i)=>{
        G(0,i)
        c=C
        for(k=d;k--;)
            P(0,k),P(d-1,k),P(k,0),P(k,d-1)})
    return a.map(v=>v.join("")).join("\n")
}

```

Test with

```
L("arty*")

```

Easy gains by leaving out the leading `var L=` and `.join("\n")` in the return statement for -17 bytes, but type them back in to test the code **:D**

It's a two pass answer, evaluating the width (`w`) required to plot a square or diamond plot, before plotting points with `P` in the second pass using rotation and translation. `d` is the dimension (height or width) of an unrotated square before translation or rotation.

Rotation and scale by √2 details from Mathematica answer. Use of tagged string template from first answer in this thread. Thanks to both for the learning. Votes for the question and answers.

# Answer
> 1 votes
# Powershell, ~~269~~ ~~245~~ 238 bytes

```
$m,$a=$args
if($a){$a|%{$c=$_
$w=$m[0].Length
$m=&({$i=0
($m|%{$_+'.'*$w+'.'})+(0..$w|%{'..'*$w+'.'})|%{($s=$_|% t*y)[--$i]=$c
-join$s}},{$m|%{$_+$c}
$c*$w+$c})[++$k%2]}
$m=($w=$m[0].Length-1)..1+0..$w|%{$m[$_]|%{-join($_[$w..1]+$_)}}}
$m

```

Ungolfed, explained & test scripted:

```
$f={

# $args is input char array
# $m is canvas.
# This script draws a right-bottom quadrant (axes included) on the canvas.
# If $args contains one char only then $m contains this char and whole image at same time.
$m,$a=$args                             # $a is other chars array
if($a){
    $a|%{
        $c=$_                           # $c is current char
        $w=$m[0].Length                 # $w is width of the canvas
        $m=&({                          # $m is the result of executing one of the two scriptblocks
            # draw Diamond quadrant
            $i=0
            ($m|%{$_+'.'*$w+'.'})+      # expand the canvas
            (0..$w|%{'..'*$w+'.'})|%{   # add new lines
                ($s=$_|% t*y)[--$i]=$c  # take a diamond edge on each line of the canvas
                -join$s
            }
        },{
            # draw Square quadrant
            $m|%{$_+$c}                 # expand the canvas
            $c*$w+$c                    # add new line
        })[++$k%2]                      # get a scriptblock from the array and execute it
    }

    # We have a right-bottom part of drawn AsciiArt now. Flip, flip, paste it.
    $w=$m[0].Length-1                   # width of the canvas
    $m=$w..1+0..$w|%{$m[$_]|%{          # flip vertical
        -join($_[$w..1]+$_)             # flip horizontal
    }}
}
$m

}

@(
,('c',@"
c
"@)
,('ca',@"
aaa
aca
aaa
"@)
,('cat',@"
....t....
...t.t...
..t...t..
.t.aaa.t.
t..aca..t
.t.aaa.t.
..t...t..
...t.t...
....t....
"@)
,('cats',@"
sssssssssss
s....t....s
s...t.t...s
s..t...t..s
s.t.aaa.t.s
st..aca..ts
s.t.aaa.t.s
s..t...t..s
s...t.t...s
s....t....s
sssssssssss
"@)
,('meows',@"
............s............
...........s.s...........
..........s...s..........
.........s.....s.........
........s.......s........
.......s.........s.......
......s...........s......
.....s.wwwwwwwwwww.s.....
....s..w....o....w..s....
...s...w...o.o...w...s...
..s....w..o...o..w....s..
.s.....w.o.eee.o.w.....s.
s......wo..eme..ow......s
.s.....w.o.eee.o.w.....s.
..s....w..o...o..w....s..
...s...w...o.o...w...s...
....s..w....o....w..s....
.....s.wwwwwwwwwww.s.....
......s...........s......
.......s.........s.......
........s.......s........
.........s.....s.........
..........s...s..........
...........s.s...........
............s............
"@)
,('codegolf',@"
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
f............................l............................f
f...........................l.l...........................f
f..........................l...l..........................f
f.........................l.....l.........................f
f........................l.......l........................f
f.......................l.........l.......................f
f......................l...........l......................f
f.....................l.............l.....................f
f....................l...............l....................f
f...................l.................l...................f
f..................l...................l..................f
f.................l.....................l.................f
f................l.......................l................f
f...............l.........................l...............f
f..............l...........................l..............f
f.............l.ooooooooooooooooooooooooooo.l.............f
f............l..o............g............o..l............f
f...........l...o...........g.g...........o...l...........f
f..........l....o..........g...g..........o....l..........f
f.........l.....o.........g.....g.........o.....l.........f
f........l......o........g.......g........o......l........f
f.......l.......o.......g.........g.......o.......l.......f
f......l........o......g...........g......o........l......f
f.....l.........o.....g.eeeeeeeeeee.g.....o.........l.....f
f....l..........o....g..e....d....e..g....o..........l....f
f...l...........o...g...e...d.d...e...g...o...........l...f
f..l............o..g....e..d...d..e....g..o............l..f
f.l.............o.g.....e.d.ooo.d.e.....g.o.............l.f
fl..............og......ed..oco..de......go..............lf
f.l.............o.g.....e.d.ooo.d.e.....g.o.............l.f
f..l............o..g....e..d...d..e....g..o............l..f
f...l...........o...g...e...d.d...e...g...o...........l...f
f....l..........o....g..e....d....e..g....o..........l....f
f.....l.........o.....g.eeeeeeeeeee.g.....o.........l.....f
f......l........o......g...........g......o........l......f
f.......l.......o.......g.........g.......o.......l.......f
f........l......o........g.......g........o......l........f
f.........l.....o.........g.....g.........o.....l.........f
f..........l....o..........g...g..........o....l..........f
f...........l...o...........g.g...........o...l...........f
f............l..o............g............o..l............f
f.............l.ooooooooooooooooooooooooooo.l.............f
f..............l...........................l..............f
f...............l.........................l...............f
f................l.......................l................f
f.................l.....................l.................f
f..................l...................l..................f
f...................l.................l...................f
f....................l...............l....................f
f.....................l.............l.....................f
f......................l...........l......................f
f.......................l.........l.......................f
f........................l.......l........................f
f.........................l.....l.........................f
f..........................l...l..........................f
f...........................l.l...........................f
f............................l............................f
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
"@)
#,('codegolfes',"")
) | % {
    $s, $e = $_
    $c = $s-split''-ne''
    $r = &$f @c
    $r = $r-join"`n"
    "$($e-eq$r): $s`n$r"
}

```

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


title: COBOL Y2K redux

text:
# Question
Title: COBOL Y2K redux
In the 1990s, COBOL computer engineers worked out a way to extend six-digit date fields by converting them to `YYYDDD` where `YYY` is the `year - 1900` and `DDD` is the day of the year `[001 to 366]`. This scheme could extend the maximum date to `2899-12-31`.

In the year 2898, the engineers started panicking because their 900 year old code bases were going to fail. Being from the year 2898, they just used their time machine to send a lone Codeinator to the year 1998 with this algorithm and the task of getting it implemented as widely as possible:

> Use a scheme `PPQQRR` where if `01 ≤ QQ ≤ 12` then it's a standard `YYMMDD` date in the 1900s, but if `QQ > 12` then it represents the days after `2000-01-01` in base 100 for `PP` and `RR` but base 87 for `QQ - 13`.

This scheme extends far beyond year 2899 and is also backwards compatible with standard dates, so no modifications of existing archives are required.

Some examples:

```
PPQQRR  YYYY-MM-DD
000101  1900-01-01  -- minimum conventional date suggested by J. Allen
010101  1901-01-01  -- edge case suggested by J. Allen
681231  1968-12-31  -- as above
991231  1999-12-31  -- maximum conventional date
001300  2000-01-01  -- zero days after 2000-01-01
008059  2018-07-04  -- current date
378118  2899-12-31  -- maximum date using YYYDDD scheme
999999  4381-12-23  -- maximum date using PPQQRR scheme

```

Your challenge is to write a program or function to accept input as `PPQQRR` and output as an ISO date `YYYY-MM-DD`. Input method can be parameter, console or command line, whatever is easiest.

For your amusement, here is a noncompeting solution in COBOL-85:

```
IDENTIFICATION DIVISION.
    PROGRAM-ID. DATE-CONVERSION.
DATA DIVISION.
    WORKING-STORAGE SECTION.
    01 T PIC 9(8).
    01 U PIC 9(8).
    01 D VALUE '999999'.
        05 P PIC 9(2).
        05 Q PIC 9(2).
        05 R PIC 9(2).
    01 F.
        05 Y PIC 9(4).
        05 M PIC 9(2).
        05 D PIC 9(2).
PROCEDURE DIVISION.
    IF Q OF D > 12 THEN
        MOVE FUNCTION INTEGER-OF-DATE(20000101) TO T
        COMPUTE U = R OF D + 100 * ((Q OF D - 13) + 87 * P OF D) + T
        MOVE FUNCTION DATE-OF-INTEGER(U) TO F
        DISPLAY "Date: " Y OF F "-" M OF F "-" D OF F
    ELSE
        DISPLAY "Date: 19" P OF D "-" Q OF D "-" R OF D
    END-IF.
STOP RUN.

```

# Answer
# T-SQL, ~~99~~ 98 bytes

```
SELECT CONVERT(DATE,IIF(ISDATE(i)=1,'19'+i,
       DATEADD(d,8700*LEFT(i,2)+RIGHT(i,4)-935,'1999')))FROM t

```

Line break is for readability only. Thank goodness for implicit casting.

Input is via a pre-existing table **t** with `CHAR` column **i**, per our IO rules.

Goes through the following steps:

1. Initial check is via the SQL function `ISDATE()`. (The behavior of this function changes based on language settings, it works as expected on my `english-us` server). Note this this is just a check for validity, if we tried to parse it directly, it would map `250101` as 2025-01-01, not 1925-01-01.
2. If the string parses correctly as a date, tack `19` on the front (rather than change the server-level year cutoff setting). Final date conversion will come at the end.
3. If the string does *not* parse as a date, convert it to a number instead. The shortest math I could find was `8700*PP + QQRR - 1300`, which avoids the (very long) SQL `SUBSTRING()` function. This math checks out for the provided samples, I'm pretty sure it is right.
4. Use `DATEADD` to add that many days to `2000-01-01`, which can be shorted to `2000`.
5. Take that final result (either a string from step 2, or a DATETIME from step 4), and `CONVERT()` it to a pure `DATE`.

I thought at one point that I found a problematic date: `000229`. This is the only date which parses *differently* for 19xx vs 20xx (since 2000 was a leap year, but 1900 was not, due to weird leap-year exceptions). Because of that, though, `000229` isn't even a valid input (since, as mentioned, 1900 was not a leap year), so doesn't have to be accounted for.
> 6 votes

# Answer
# , 126 bytes

```
function(x,a=x%/%100^(2:0)%%100,d=as.Date)'if'(a[2]<13,d(paste(19e6+x),'%Y%m%d'),d(a[3]+100*((a[2]-13)+87*a[1]),'2000-01-01'))

```

Try it online!

* -5 bytes thanks to @Giuseppe suggestion to take a numeric input instead of string
> 5 votes

# Answer
# JavaScript (SpiderMonkey), 103 bytes

```
s=>new Date(...([a,b,c]=s.match(/../g),b>12?[2e3,0,(b-13+a*87)*100-~c]:[a,b-1,c])).toJSON().split`T`[0]

```

Try it online!

---

`.toJSON` will failed on a UTC+X timezone. This code works, but longer (+11bytes):

```
s=>Intl.DateTimeFormat`ii`.format(new Date(...([a,b,c]=s.match(/../g),b>12?[2e3,0,(b-13+a*87)*100-~c]:[a,b-1,c])))

```
> 4 votes

# Answer
# Python 2, 159 bytes

```
from datetime import*
def f(s):D=datetime;p,q,r=map(int,(s[:2],s[2:4],s[4:]));return str(q>12and D(2000,1,1)+timedelta(100*(q-13+87*p)+r)or D(1900+p,q,r))[:10]

```

Try it online!
> 3 votes

# Answer
## ABAP, ~~173~~ 171 bytes

Saved 2 bytes by further optimizing the output

According to the legends, an SAP customer in the early 21st century once said:

> After a nuclear war of total destruction, the one thing remaining will be SAPGUI.

He was right. Today, in 2980, there is no more C++, no more COBOL. After the war everyone had to rewrite their code in SAP ABAP. To provide backwards compatibility to the leftovers of the 2800's COBOL programs, our scientists rebuilt it as a subroutine in ABAP.

```
FORM x USING s.DATA d TYPE d.IF s+2 < 1300.d ='19'&& s.ELSE.d ='20000101'.d = d + s+4 + 100 * ( ( s+2(2) - 13 ) + 87 * s(2) ).ENDIF.WRITE:d(4),d+4,9 d+6,8'-',5'-'.ENDFORM.

```

It can be called by a program like this:

```
REPORT z.
  PARAMETERS date(6) TYPE c. "Text input parameter
  PERFORM x USING date.      "Calls the subroutine

```

---

Explanation of my code:

```
FORM x USING s.     "Subroutine with input s
  DATA d TYPE d.    "Declare a date variable (internal format: YYYYMMDD)
  IF s+2 < 1300.    "If substring s from index 2 to end is less than 1300
    d ='19'&& s.    "the date is 19YYMMDD
  ELSE.             "a date past 2000
    d ='20000101'.  "Initial d = 2000 01 01 (yyyy mm dd)

    "The true magic. Uses ABAPs implicit chars to number cast
    "and the ability to add days to a date by simple addition.
    "Using PPQQRR as input:
    " s+4 = RR, s+2(2) = QQ, s(2) = PP
    d = d + s+4 + 100 * ( ( s+2(2) - 13 ) + 87 * s(2) ).
  ENDIF.
    "Make it an ISO date by splitting, concatenating and positioning the substrings of our date.
    WRITE:             "Explanation:
      d(4),            "d(4) = YYYY portion. WRITE adds a space after each parameter, so...
      5 '-' && d+4,    "place dash at absolute position 5. Concatenate '-' with MMDD...
      8 '-' && d+6.    "place dash at absolute position 8, overwriting DD. Concatenate with DD again.
ENDFORM.

```

ABAP's Date type has the odd property to be formatted as DDMMYYYY when using `WRITE` \- might be locale dependent even - despite the internal format being YYYYMMDD. But when we use a substring selector like `d(4)` it selects the first 4 characters of the *internal* format, hence giving us YYYY.

**Update**: The output formatting in the explanation is now outdated, I optimized it by 2 bytes in the golfed version:

```
WRITE:  "Write to screen, example for 2000-10-29
 d(4),   "YYYY[space]                =>  2000
 d+4,    "MMDD[space]                =>  2000 1029
 9 d+6,  "Overwrites at position 9   =>  2000 10229
 8'-',   "Place dash at position 8   =>  2000 10-29
 5'-'.   "Place dash at position 5   =>  2000-10-29

```
> 3 votes

# Answer
# Kotlin, 222 bytes

Hard coded Calendar field names constants to save 49 bytes.

```
{d:Int->val p=d/10000
val q=d/100%100
val r=d%100
if(q<13)"19%02d-%02d-%02d".format(p,q,r)
else{val c=Calendar.getInstance()
c.set(2000,0,1)
c.add(5,(p*87+q-13)*100+r)
"%4d-%02d-%02d".format(c.get(1),c.get(2)+1,c.get(5))}}

```

Try it online!
> 2 votes

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


title: Verify Wolstenholme's theorem

text:
# Question
Title: Verify Wolstenholme's theorem
# Definition

Wolstenholme's theorem states that:

where `a` and `b` are positive integers and `p` is prime, and the big parentheses thingy is Binomial coefficient.

# Task

To verify that, you will be given three inputs: `a`, `b`, `p`, where `a` and `b` are positive integers and `p` is prime.

Compute:

where `a` and `b` are positive integers and `p` is prime, and the parentheses thingy is Binomial coefficient.

# Specs

Since:

where and the parentheses thingy is Binomial coefficient.

You can assume that `2b <= a`

# Testcases

```
a b p  output
6 2 5  240360
3 1 13 3697053
7 3 13 37403621741662802118325

```

# Answer
# Haskell, ~~73~~ 71 bytes

Due to the recursion, this implementation is very slow. Unfortunately my definition of the binomial coefficient has the same length as `import Math.Combinatorics.Exact.Binomial`.

```
n#k|k<1||k>=n=1|1>0=(n-1)#(k-1)+(n-1)#k --binomial coefficient
f a b p=div((a*p)#(b*p)-a#b)p^3       --given formula

```

An interesting oddity is that Haskell 98 did allow for *arithmetic patterns* which would have shortened the same code to 64 bytes:

```
g a b p=div((a*p)#(b*p)-a#b)p^3
n+1#k|k<1||k>n=1|1>0=n#(k-1)+n#k

```
> 5 votes

# Answer
# Jelly, ~~12~~ ~~11~~ 10 bytes

```
ż×c/I÷S÷²}

```

Expects `a, b` and `p` as command-line arguments.

Try it online! or verify all test cases.

### How it works

```
ż×c/I÷S÷²}  Main link. Left argument: a, b. Right argument: p

 ×          Multiply; yield [pa, pb].
ż           Zipwith; yield [[a, pa], [b, pb]].
  c/        Reduce columns by combinations, yielding [aCb, (pa)C(pb)].
    I       Increments; yield [(pa)C(pb) - aCb].
     ÷      Divide; yield [((pa)C(pb) - aCb) ÷ p].
      S     Sum; yield ((pa)C(pb) - aCb) ÷ p.
        ²}  Square right; yield p².
       ÷    Divide; yield  ((pa)C(pb) - aCb) ÷ p³.

```
> 4 votes

# Answer
# Python 2, ~~114~~ ~~109~~ ~~85~~ 71 bytes

A simple implementation. Golfing suggestions welcome.

**Edit:** -29 bytes thanks to Leaky Nun and -14 bytes thanks to Dennis.

```
lambda a,b,p,f=lambda n,m:m<1or f(n-1,m-1)*n/m:(f(a*p,b*p)-f(a,b))/p**3

```

A simpler, same-length alternative, with thanks to Dennis, is

```
f=lambda n,m:m<1or f(n-1,m-1)*n/m
lambda a,b,p:(f(a*p,b*p)-f(a,b))/p**3

```
> 4 votes

# Answer
# 05AB1E, 11 bytes

Takes input as:

```
[a, b]
p

```

Code:

```
*`c¹`c-²3m÷

```

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

# Answer
# R, ~~50~~ 48 bytes

```
function(a,b,p)(choose(a*p,b*p)-choose(a,b))/p^3

```

As straightforward as can be... Thanks to @Neil for saving 2 bytes.
> 3 votes

# Answer
# MATL, 13 bytes

```
y*hZ}Xnd2G3^/

```

**Try it online!**

The last test case doesn't produce an exact integer due to numerical precision. MATL's default data type (`double`) can only handle exact integers up to `2^53`.

### Explanation

```
y   % Implicitly input [a; b] (col vector) and p (number). Push another copy of [a; b]
    %   Stack: [a; b], p, [a; b]
*   % Multiply the top two elements from the stack
    %   Stack: [a; b], [a*p; b*p]
h   % Concatenate horizontally
    %   Stack: [a, a*p; b, b*p]
Z}  % Split along first dimension
    %   Stack: [a, a*p], [b, b*p]
Xn  % Vectorize nchoosek
    %   Stack: [nchoosek(a,b), nchoosek(a*p,b*p)]
d   % Consecutive differences of array
    %   Stack: nchoosek(a,b)-nchoosek(a*p,b*p)
2G  % Push second input again
    %   Stack: nchoosek(a,b)-nchoosek(a*p,b*p), p
3^  % Raise to third power
    %   Stack: nchoosek(a,b)-nchoosek(a*p,b*p), p^3
/   % Divide top two elements from the stack
    %   Stack: (nchoosek(a,b)-nchoosek(a*p,b*p))/p^3
    % Implicitly display

```
> 2 votes

# Answer
# J, 17 bytes

```
(!/@:*-!/@[)%]^3:

```

## Usage

```
(b,a) ( (!/@:*-!/@[)%]^3: ) p

```

For example:

```
   2 6 ( (!/@:*-!/@[)%]^3: ) 5
240360

```

This is just a direct implementation of the formula so far.

*Note*: for the 3rd testcase input numbers must be defined as *extended* (to handle big arithmetic):

```
   3x 7x ( (!/@:*-!/@[)%]^3: ) 13x
37403621741662802118325

```
> 2 votes

# Answer
# Brachylog, 52 bytes

```
tT;T P&t^₃D&h↰₁S&h;Pz×₎ᵐ↰₁;S-;D/
hḟF&⟨{-ḟ}×{tḟ}⟩;F↻/

```

Try it online!

Accepts input `[[a, b], p]`.

```
% Predicate 1 - Given [n, r], return binomial(n, r)
hḟF              % Compute n!, set as F
&⟨               % Fork:
  {-ḟ}           % (n - r)!
  ×              % times
  {tḟ}           % r!
⟩
;F↻              % Prepend n! to that
/                % Divide n! by the product and return

% Predicate 0 (Main)
tT;T P           % Set P to the array [p, p]
&t^₃D            % Set D as p^3
&h↰₁S            % Call predicate 1 on [a, b],
                 %  set S as the result binomial(a, b)
&h;Pz×₎ᵐ         % Form array [ap, bp]
↰₁               % Call predicate 1 on that to get binomial(ap, bp)
;S-              % Get binomial(ap, bp) - binomial(a, b)
;D/              % Divide that by the denominator term p^3
                 % Implicit output

```
> 2 votes

# Answer
# Nim, ~~85~~ ~~82~~ ~~75~~ 59 bytes

```
import math,future
(a,b,p)=>(binom(a*p,b*p)-binom(a,b))/p^3

```

This is an anonymous procedure; to use it, it must be passed as an argument to another procedure, which prints it. A full program that can be used for testing is given below

```
import math,future
proc test(x: (int, int, int) -> float) =
 echo x(3, 1, 13) # substitute in your input or read from STDIN
test((a,b,p)=>(binom(a*p,b*p)-binom(a,b))/p^3)

```

Nim's `math` module's `binom` proc computes the binomial coefficient of its two arguments.
> 1 votes

# Answer
# Python 3 with SciPy, 72 bytes

```
from scipy.special import*
lambda a,b,p:(binom(a*p,b*p)-binom(a,b))/p**3

```

An anonymous function that takes input via argument and returns the result.

There's not a lot going on here; this is a direct implementation of the desired computation.

Try it on Ideone (the result is returned in exponential notation for the last test case)
> 1 votes

# Answer
# Python 2, 67 bytes

```
def f(a,b,p):B=2<<a*p;R=(B+1)**a;print(R**p/B**(p*b)-R/B**b)%B/p**3

```

Try it online!

Expresses the binomial coefficients arithmetically using this method.
> 1 votes

# Answer
## JavaScript (ES6), 70 bytes

```
(a,b,p,c=(a,b)=>a==b|!b||c(--a,b)+c(a,--b))=>(c(a*p,b*p)-c(a,b))/p/p/p

```

Save 1 byte by using ES7 (`/p**3` instead of `/p/p/p`).
> 0 votes

# Answer
# APL (Dyalog), 18 bytes

```
{(-/!/¨⍺1×⊂⍵)÷⍺*3}

```

Try it online!
> 0 votes

# Answer
# Pari/GP, 43 bytes

```
(a,b,p)->((c=binomial)(a*p,b*p)-c(a,b))/p^3

```

Try it online!
> 0 votes

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


title: Beatles Songs and Hexagons

text:
# Question
Title: Beatles Songs and Hexagons
Write two triangle (i.e. pyramid) shaped programs.

The first one should be an upwards pointing text triangle with a minimum base width of three characters. So it would have a structure like

```
 X
XXX

```

or

```
  X
 XXX
XXXXX

```

or

```
   X
  XXX
 XXXXX
XXXXXXX

```

or larger. Each of the `X`'s is to be replaced with the characters of your actual code, which may be anything except line terminators (so the `X`'s could be spaces). All the `X`'s must be replaced and the spaces and newlines that help form the triangle shape are required to stay as is.

The second program must have the same size and shape as the first, except that the triangle will be pointing down.

So if your first program looks like

```
  X
 XXX
XXXXX

```

then your second program would look like

```
yyyyy
 yyy
  y

```

where each `y` is a character you need to fill in with your actual code (probably different from your `X` code). The spaces and newlines must stay the same here too.

Your task is to write these programs such that they each output (to stdout or closest alternative) the title of a distinct Beatles song, not taking any input. This Wikipedia article will serve as our official song list for The Beatles. The output should be one of the titles exactly as listed, e.g. `I Want You (She's So Heavy)`.

This is pretty easy, however, even with the weird triangle program requirement. So we're going to form another program from the first two that must output yet another song title.

By combining three copies of each of the two triangular programs we can create a third program shaped like a hexagon.

If the base width of your first program was three it would look like this:

```
 XyyyX
XXXyXXX
yyyXyyy
 yXXXy

```

If the base width was five it would look like this:

```
  XyyyyyX
 XXXyyyXXX
XXXXXyXXXXX
yyyyyXyyyyy
 yyyXXXyyy
  yXXXXXy

```

This program (when run with the spaces and newlines like the others) must output another Beatles song title, just like the first two programs. Also:

* Your three programs must output different song titles.
* **Only song titles eight characters in length or longer are allowed.**
* You can only choose one of `Revolution`, `Revolution 1` and `Revolution 9` because the titles are so similar.
* You must choose your three favorite Beatles songs. (Well, *try* to.)

Note that actual programs are required. Functions are not allowed. Reading your own source code in any program is also not allowed.

# Example

If your first program was

```
  A
 AAA
AAAAA

```

it could output `Across the Universe`.

Then your second program

```
bbbbb
 bbb
  b

```

could output `Revolution`.

Then combined into the hexagon program

```
  AbbbbbA
 AAAbbbAAA
AAAAAbAAAAA
bbbbbAbbbbb
 bbbAAAbbb
  bAAAAAb

```

the output might be `Get Back`.

# Scoring

The submission with the smallest triangle base width wins. In the likely case of ties the submission with the largest summed length of its three song titles wins.

# Answer
# GolfScript, width = 9 chars, titles = 33 chars

## Hexagon

```
    "Let It Be"
   }";"Yeste"}";
  "Twi""rda""Twi"
 "st an""y""st an"
"d Shout"}"d Shout"
Let It Be"Let It Be
 "Yeste"}";"Yeste"
  "rda""Twi""rda"
   "y""st an""y"
    }"d Shout"}

```

Prints **Let It Be**. (9 characters)

Try it online.

### How it works

The token `"Let It Be"` on the first line pushes the string **Let It Be** on the stack.

The second line begins with `}`, an undocumented "super comment" that aborts execution immediately.

Before exiting, GolfScript prints the contents of the stack.

## X triangle

```
    "
   }";
  "Twi"
 "st an"
"d Shout"

```

Prints **Twist and Shout**. (15 characters)

Try it online.

### How it works

The first two lines push the string `"\n }"`, which the command `;` discards from the stack.

The remaining lines contain the tokens `"Twi"`, `"st an"` and `"d Shout"`, which push the string **Twist and Shout** in three pieces.

Before exiting, GolfScript prints the contents of the stack.

## Y triangle

```
Let It Be
 "Yeste"
  "rda"
   "y"
    }

```

Prints **Yesterday**. (9 characters)

Try it online.

### How it works

The tokens `Let`, `It` and `Be` on the first line are undefined, so they do nothing.

The three following lines contain the tokens `"Yeste"`, `"rda"` and `"y"`, which push the string **Yesterday** in three pieces.

The `}` on the last line does nothing; the program would have finished anyway.

Once more, GolfScript prints the contents of the stack before exiting.
> 18 votes

# Answer
# Befunge-93, width = 13 ~~15~~, titles = 31 ~~24~~ chars

A power outage last night prevented me from updating this when I figured it out, but I managed to reduce the triangle width **and** increase the song lengths!

## Pointing-up program: "Dig a Pony", 10 characters:

```
      v
     v>
    v#  >
   "<
  v <>"y"v>
 <v"Dig a P"
"^>:#,_@.>"no

```

### Explanation

I REALLY took advantage of Befunge's wrap-around trick and I picked "Dig a Pony" specifically because it had a space at the 6th position. This allows program flow to move *through* the song name. Try it in the online interpreter to see how it works.

## Pointing-down program: "If I Fell", 9 characters:

```
< v"f I Fell"
 v>"I">:#,_@
  "raC yM "
   v"Drive

       .

```

(Period is extraneous and only included to make the other lines show up.)

### Explanation

The only relevant lines here are the first two. I used the wrap-around trick (the instruction pointer is sent left immediately) to squeeze in one more character. The second line prints out the song name.

## Combined: "Drive My Car", 12 characters:

```
      v< v"f I Fell"v
     v> v>"I">:#,_@v>
    v#  >"raC yM "v#  >
   "<     v"Drive"<
  v <>"y"v>     v <>"y"v>
 <v"Dig a P"   <v"Dig a P"
"^>:#,_@.>"no "^>:#,_@.>"no
< v"f I Fell"v< v"f I Fell"
 v>"I">:#,_@v> v>"I">:#,_@
  "raC yM "v#  >"raC yM "
   v"Drive"<     v"Drive
         v <>"y"v>
        <v"Dig a P"
       "^>:#,_@.>"no

```

Here's the same thing, but with lines added to show the hexagon and triangles.

```
       -----------------
      /v\< v"f I Fell"/v\
     /v> \v>"I">:#,_@/v> \
    /v#  >\"raC yM "/v#  >\
   /"<     \v"Drive/"<     \
  /v <>"y"v>\     /v <>"y"v>\
 /<v"Dig a P"\   /<v"Dig a P"\
/"^>:#,_@.>"no\ /"^>:#,_@.>"no\
-------------------------------
\< v"f I Fell"/v\< v"f I Fell"/
 \v>"I">:#,_@/v> \v>"I">:#,_@/
  \"raC yM "/v#  >\"raC yM "/
   \v"Drive/"<     \v"Drive/
    \     /v <>"y"v>\     /
     \   /<v"Dig a P"\   /
      \ /"^>:#,_@.>"no\ /
       -----------------

```

### Explanation

This is where the third and fourth lines of the pointing-down triangle come into play. There are several redirects at the edge of both triangles that serve to move the instruction pointer through those two lines and push "Drive My Car" onto the stack. Then it is printed out using the `>:#,_@` bit in the pointing-up triangle. Incidentally, both the left *and* the right pointing-up triangles are used.

There *might* be a way to use more of the empty space, but I think my time is better spent on other questions. :P
> 21 votes

# Answer
# Python 2, width = 51

```
                         #print "Yellow Submarine" if id else "(Reprise)"   ##
                        #.##...............................................##.#
                       #...##.............................................##...#
                      #.....##...........................................##.....#
                     #.......##.........................................##.......#
                    #.........##.......................................##.........#
                   #...........##.....................................##...........#
                  #.............##...................................##.............#
                 #...............##.................................##...............#
                #.................##...............................##.................#
               #...................##.............................##...................#
              #.....................##...........................##.....................#
             #.......................##.........................##.......................#
            #.........................##.......................##.........................#
           #...........................##.....................##...........................#
          #.............................##...................##.............................#
         #...............................##.................##...............................#
        #.................................##...............##.................................#
       #...................................##.............##...................................#
      #.....................................##...........##.....................................#
     #.......................................##.........##.......................................#
    #.........................................##.......##.........................................#
   #...........................................##.....##...........................................#
  #.............................................##...##.............................................#
 #...............................................##.##...............................................#
print "Sgt. Pepper's Lonely Hearts Club Band",;id=0#print "Sgt. Pepper's Lonely Hearts Club Band",;id=0
print "Yellow Submarine" if id else "(Reprise)"   ##print "Yellow Submarine" if id else "(Reprise)"   #
 #...............................................##.##...............................................#
  #.............................................##...##.............................................#
   #...........................................##.....##...........................................#
    #.........................................##.......##.........................................#
     #.......................................##.........##.......................................#
      #.....................................##...........##.....................................#
       #...................................##.............##...................................#
        #.................................##...............##.................................#
         #...............................##.................##...............................#
          #.............................##...................##.............................#
           #...........................##.....................##...........................#
            #.........................##.......................##.........................#
             #.......................##.........................##.......................#
              #.....................##...........................##.....................#
               #...................##.............................##...................#
                #.................##...............................##.................#
                 #...............##.................................##...............#
                  #.............##...................................##.............#
                   #...........##.....................................##...........#
                    #.........##.......................................##.........#
                     #.......##.........................................##.......#
                      #.....##...........................................##.....#
                       #...##.............................................##...#
                        #.##...............................................##.#
                         #print "Sgt. Pepper's Lonely Hearts Club Band",;id=0#

```

Yeah, well... Python.

Python comments begin with `#`, so the majority of lines is just comments. For the upwards facing triangle, the only thing that executes is

```
print "Sgt. Pepper's Lonely Hearts Club Band",;id=0

```

which prints `Sgt. Pepper's Lonely Hearts Club Band`.

For the downwards facing triangle, we execute

```
print "Yellow Submarine" if id else "(Reprise)"

```

which prints `Yellow Submarine`, since the function `id` is truthy.

When we combine the programs however, all that happens is the above two lines in sequence. Since the end of the first line sets `id=0`, which is now falsy, the end result is that we tack a `(Reprise)` to the end, getting `Sgt. Pepper's Lonely Hearts Club Band (Reprise)` as our output (Calvin said this is okay).
> 18 votes

# Answer
## Snowman 1.0.2, width = 13

```
      }?}///////////}
     ///"Get Back"////
    ///////////////////
   /////////////////////
  "Sun King//"[["Sun King
 "*"BirthdaysP/"*"Birthday
"]]8AaLsP[[///"]]8AaLsP[[//
?}///////////}?}///////////
 "Get Back"////"Get Back"/
  ///////////////////////
   /////////////////////
    //"[["Sun King//"[[
     sP/"*"BirthdaysP/
      /"]]8AaLsP[[///

```

**Finally!** A challenge where Snowman can thrive! :D :D

The slashes are mostly for aesthetic purposes, and the majority of them can be replaced with spaces (but that would make it look a whole lot more boring). Some slashes are necessary, for comments.

### Program A (output: `Birthday`):

```
      }
     ///
    /////
   ///////
  "Sun King
 "*"Birthday
"]]8AaLsP[[//

```

This one's pretty simple. The first character (`}`) sets up our active variables, then there's a bunch of comments / no-ops. It then stores the string `"Sun King\n "` and immediately discards it (via `*`, storing it in a permavar which we never use). Then it stores `"Birthday\n"`.

`]]` is a no-op here, since `[[ foo ]]` is a block comment in Snowman, but since there's no matching `[[` before this `]]` (within program A itself), it simply does nothing. Then `8AaL` grabs the first 8 characters of the string, `sP` prints it, and `[[` comments out the rest of the program (because again, there's no matching `]]`.

### Program B (output: `Get Back`):

```
?}///////////
 "Get Back"/
  /////////
   ///////
    //"[[
     sP/
      /

```

This one's also pretty straightforward. `?}` is equivalent to `}` (`?` simply sets all variables to inactive, which is a no-op here but again, important later). Then it stores the string `"Get Back"`, does a bunch of no-ops (`//` to end of line is always a comment), and prints via `sP`.

### Full program

Output is, you guessed it, `Sun King`1.

Let's look at this line by line:

* Line 1

```
      }?}///////////}

```

This sets our active variables, just like the previous programs (we can see now that the `?` is needed so as to not simply toggle them on and then back off with `}}`). The rest of the line is commented out.
* Lines 2-4

```
     ///"Get Back"////
    ///////////////////
   /////////////////////

```

Comments...
* Line 5

```
  "Sun King//"[["Sun King

```

Here we store the string `"Sun King//"`, and then start a block comment. This essentially skips everything until the next `]]`.
* Line 6

```
 "*"BirthdaysP/"*"Birthday

```

Still inside the block comment...
* Line 7

```
"]]8AaLsP[[///"]]8AaLsP[[//

```

Here we break out of the block comment for a short period of time, to execute the code `8AaLsP`. This is actually reused from program A. Since I chose all songs that are 8 letters long, I can simply use the same code for the combined program.

Then it gets a little tricky. The next time we emerge from the block comment, we see `8AaLsP` again. This time, however, all variables are undefined (we called `sp`, print, in consume mode, which gets rid of the variables). Since `aal` requires two arguments, and this time it only has one (`8`), it errors and leaves the variables unchanged.

Similarly, `sp` encounters the `8`, realizes it's the wrong type to be printed, and leaves the variables as is.
* Lines 8-13

```
?}///////////}?}///////////
 "Get Back"////"Get Back"/
  ///////////////////////
   /////////////////////
    //"[["Sun King//"[[
     sP/"*"BirthdaysP/

```

Still stuck in that block comment...
* Line 14

```
      /"]]8AaLsP[[///

```

Finally, we try calling that same print-first-8-chars sequence once again, and it fails once again, producing another two errors. (The `8` means that the variables are now `8 8`, which is the correct *number* of variables for `aal` now, but still not the right types.)

---

1: as well as four runtime errors (`SnowmanException`s) to STDERR, but as per meta that doesn't matter.
> 17 votes

# Answer
# \>\<\>, width = 11

```
     /"yadhtri"\ /
           v"B"/
        ?!;>ol
  duJ yeH" /"eduJ yeH
 o   >l?!;   o   >l?!;
staC"/"klaw staC"/"klaw
"yadhtri"\ /"yadhtri"\
     v"B"/       v"B"/
  ?!;>ol      ?!;>ol
   " /"eduJ yeH" /"e
       o   >l?!;
      staC"/"klaw

```

2D languages have a pretty good time with this challenge.

### Upwards arrow

```
     /

  duJ yeH
 o   >l?!;
staC"/"klaw

```

Program flow starts from the top-left, moving rightward. The `/` reflects up, and since \>\<\> is toroidal we reappear from the bottom. We then hit another `/` and reflect again, and push the characters `klawstaC` one-by-one to the stack in string `""` mode. Finally, we reflect upwards and hit a `>l?!;o` loop, which is the idiomatic way of printing the entire stack in \>\<\>.

This prints `Catswalk`.

### Downwards arrow

```
"yadhtri"\
     v"B"/
  ?!;>ol
   " /"e

```

Basically the same thing, pushing the characters from the get go and using mirrors and arrows to direct program flow. This prints `Birthday`.

### Combined

```
     /

  ?!;>ol      ?!;>ol
     /"eduJ yeH" /

```

The relevant parts are above (I've cut out a lot of lines in the middle). Using the `/` from the upwards arrow, we reflect upwards and wrap around, but since we now have the downwards arrow underneath, part of that code is executed instead. We then push the relevant characters to the stack, and reuse the output loop from the downwards arrow.

This prints `Hey Jude`.
> 14 votes

# Answer
# Python 2, size 21

This program requires an ANSI-compatible terminal (DOS ANSI.SYS to be specific), since I use `\x1b[2J` to clear the console AND move the cursor to top-left. To make this compatible with other ANSI terminals, print `\x1b[1J\x1b[H` (this can still fit in a size 21 hexagon). I wasn't able to test this part, because I don't have a terminal that prints ANSI escape codes.

I think the program looks pretty cool, similar to the radioactive symbol (though the ASCII shading implies the colors are backwards) or the icon of the sniper weapon from Metroid Prime: Hunters.

It *did* fit in size 17, but I'd forgotten `id=0` in the up arrow. I don't think I can shrink it back down, since that has to all be on one line...

Also, credit goes to Sp3000 for the idea to use `id`.

```
          #exec('print"'       ##
         ###'\x1b[2J"+(id '   ####
        #####'and"Hey Ju'    ######
       #######'de"or"Ca'    ########
      #########'tswalk'    ##########
     ###########'")')     ############
    ##############       ##############
   ################     ################
  ##################   ##################
 #################### ####################
id=0;print"Birthday"##id=0;print"Birthday"#
exec('print"'       ##exec('print"'       #
 '\x1b[2J"+(id '   ####'\x1b[2J"+(id '   #
  'and"Hey Ju'    ######'and"Hey Ju'    #
   'de"or"Ca'    ########'de"or"Ca'    #
    'tswalk'    ##########'tswalk'    #
     '")')     ############'")')     #
      #       ###############       #
       #     #################     #
        #   ###################   #
         # ##################### #
          #id=0;print"Birthday"##

```

### Up Arrow:

```
          #
         ###
        #####
       #######
      #########
     ###########
    #############
   ###############
  #################
 ###################
id=0;print"Birthday",

```

### Down Arrow:

```
exec('print"'       #
 '\x1b[2J"+(id '   #
  'and"Hey Ju'    #
   'de"or"Ca'    #
    'tswalk'    #
     '")')     #
      #       #
       #     #
        #   #
         # #
          #

```

"Hey Jude" is one of my favorite Beatles songs, but I really don't know that many. I've never heard the other two songs I'm using. It's not a genre I listen to often.
> 5 votes

# Answer
# C (gcc), base width = 17

## Top, "Hey Jude"

```
        s
       ;//
      s;///
     main(//
    ){puts(//
   #define T//
  s?"Michell"//
 "e":"Hey Jud"//
"e");}///////////

```

Try it online!

## Bottom, "Matchbox"

```
s=1;/////////////
 #ifndef T//////
  main(){puts//
   ("Matchb"//
    "ox");}//
     # endif
      /////
       //\
        ;

```

Try it online!

## Hexagon, "Michelle"

```
        ss=1;/////////////s
       ;//#ifndef T//////;//
      s;///main(){puts//s;///
     main(//("Matchb"//main(//
    ){puts(//"ox");}//){puts(//
   #define T//# endif#define T//
  s?"Michell"///////s?"Michell"//
 "e":"Hey Jud"////\"e":"Hey Jud"//
"e");}///////////;"e");}///////////
s=1;/////////////ss=1;/////////////
 #ifndef T//////;//#ifndef T//////
  main(){puts//s;///main(){puts//
   ("Matchb"//main(//("Matchb"//
    "ox");}//){puts(//"ox");}//
     # endif#define T//# endif
      /////s?"Michell"///////
       //\"e":"Hey Jud"////\
        ;"e");}///////////;

```

Try it online!
> 2 votes

# Answer
# gawk, base length 15

*Just found out it doesn't work with mawk* :/

It's not too tricky, but being grown up in the 70s, with The Beatles still omnipresent on air, I had to answer this. First I thought awk wasn't suited, but then it came to me.

Since these scripts contain BEGIN- and/or END-blocks, they need to be told that there will be no input to execute the END-block. This can be achieved by either pressing Ctrl-D after starting them, or starting them like this:

```
awk -f script.awk </dev/null

```

which I think is more convenient. `echo | awk -f script.awk` will also work, but if I would have used an empty line as input I would have done this completely different.

### Pointing up, prints For No One (Youtube link)

```
       #
      # #
     #   #
    BEGIN {
   print n?#
  #         #
 n"So Tired":#
n="For No One"}

```

The essential code without comments is this. Since `n` isn't defined it prints "For No One" if called by itself.

```
    BEGIN {
   print n?

 n"So Tired":
n="For No One"}

```

### Pointing down, prints Blackbird

```
END{a="Blackb"#
 a=n?_:a"ird"#
  printf a  #
   n="I'm "#
    if(a) #
     print
      } #
       #

```

The essential code is this. If `n` was defined before it doesn't print anything. I enforced the nice output with a newline after every track name, because I had the room to do that and it looks nicer in the console. `n` is defined in the process; that's needed for the Hexagon.

```
END{a="Blackb"
 a=n?_:a"ird"
  printf a
   n="I'm "
    if(a)
     print
      }

```

### Hexagon, prints I'm So Tired

```
       #END{a="Blackb"##
      # #a=n?_:a"ird"## #
     #   #printf a  ##   #
    BEGIN {n="I'm "#BEGIN {
   print n?#if(a) #print n?#
  #         #print#         #
 n"So Tired":#} #n"So Tired":#
n="For No One"}#n="For No One"}
END{a="Blackb"##END{a="Blackb"#
 a=n?_:a"ird"## #a=n?_:a"ird"#
  printf a  ##   #printf a  #
   n="I'm "#BEGIN {n="I'm "#
    if(a) #print n?#if(a) #
     print#         #print
      } #n"So Tired":#} #
       #n="For No One"}#

```

The essential code. Now finally that mysterious `n` is used. Because `n` is defined in the first line, the upwards pointing triangle prints the alternative output, and the downwards pointing triangle prints emptiness.

```
    BEGIN {n="I'm "
   print n?

 n"So Tired":
n="For No One"}
END{a="Blackb"
 a=n?_:a"ird"
  printf a
   n="I'm "
    if(a)
     print
      }

```
> 1 votes

---
Tags: code-challenge, geometry, source-layout
---


title: Howdy! I'm the sheriff of code golf!

text:
# Question
Title: Howdy! I'm the sheriff of code golf!
It's likely that anyone who used Twitter a couple of months ago would know about the 'Howdy! I'm the sheriff of X" meme. Where a simple image of a sheriff is drawn with emoji, and changes to fit a theme. So I thought it was time for the Sheriff of Code Golf. Here he is:

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

```

This one in particular has 'pixels' which are one character wide, and one character high. To generate him, the arguments will be 1 and 1.

What if he is to be wider than he is tall?

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

```

He's got a height of 1, but a width of 2.

---

# Rules:

* The challenge is to write code to draw your own Sheriff of Code Golf, in the fewest characters possible.
* Use any programming language your heart desires.
* Your code should take two arguments, both of which are integers, for the height and width of the Sheriff.
* The output should be composed of single white spaces for the background, and any other character(s) you choose for the Sheriff. (I've used hashes for the test cases, but it doesn't matter what you use).
* It should be possible for the height to be a negative integer, inverting the image.
* The width can be a negative integer, but because the image is symmetrical, it will be identical to it's positive value.
* Trailing white-spaces are irrelevant.
* If either argument is 0, that dimension is 'flattened' to a single row or column. The length of this line is the other argument multiplied by the height, or width of the Sheriff, respectively.
* If both arguments are 0, both lines are 'flattened', leaving a single positive character.
* Not essential, but please include a link to an online interpreter such as tio.run
* The output should be a string, over multiple lines, or output to the console.

---

# Test Cases

1 high, 1 wide

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

```

2 high, 1 wide

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

```

1 high, 2 wide

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

```

2 high, 2 wide

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

```

-1 high, 1 wide

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

```

1 high, -1 wide

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

```

0 high, 0 wide

```
#

```

1 high, 0 wide

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

```

0 high, 2 wide

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

```

---

Have fun, y'all!

# Answer
# JavaScript (ES6), 171 bytes

Takes input in currying syntax `(width)(height)`. Returns an array of strings.

```
w=>h=>[...Array((h>0?h:-h)*16||1)].map((_,y)=>'012345678'.replace(/./g,x=>' #'[((c=+'3733317900134444'[(h<0?16-~y/h:y/h)|0]||17)>>4-x|c>>x-4)&1|!h].repeat(w>0?w:-w))||'#')

```

Try it online!

### How?

Only the left half of the sheriff is encoded as binary bitmasks, including the middle column:

```
    ##.         00011     3
   ###..        00111     7
    ##.         00011     3
    ##.         00011     3
    ##.         00011     3
     #          00001     1
   ###..        00111     7
  #  #  .       01001     9
 #   #   .  --> 10001 --> 17
 #   #   .      10001     17
     #          00001     1
    ##.         00011     3
   #   .        00100     4
   #   .        00100     4
   #   .        00100     4
   #   .        00100     4

```

Because there are only two values greater than \\$9\\$ and they're both equal to \\$17\\$, we can replace them with \\$0\\$ in order to have one character per row and still have a rather straightforward decoding process. Hence the packed string:

```
'3733317900134444'

```

For \\$0 \le x \le 8\\$ and \\$0 \le y \le 15\\$, the 'pixel' at \\$(x,y)\\$ is given by:

```
' #'[                                  // character lookup:
  (                                    //   0 = space
    (                                  //   1 = '#'
      c = +'3733317900134444'[y] || 17 // extract the bitmask for this row; 0 -> 17
    )   >> 4 - x                       // test the left part, middle column included
    | c >> x - 4                       // test the right part, middle column also included
  ) & 1                                // isolate the least significant bit
]                                      // end of character lookup

```
> 40 votes

# Answer
# Python 2, ~~228~~ ~~218~~ ~~202~~ ~~189~~ 173 bytes

```
lambda h,w:sum(([''.join('# '[int(n)]*abs(w)for n in bin([62,120,224,238,438,750][int(l)])[2:])or'#']*abs(h)for l in'1211102455013333'),[])[::1-(h<0)*2]or['#'*9*abs(w)or'#']

```

Try it online!

---

Alternatives:

# Python 2, 173 bytes

```
lambda h,w:sum(([''.join('# '[int(n)]*abs(w)for n in bin(ord(' >w(8\x96I'[l])*l)[2:])or'#']*abs(h)for l in map(int,'3433314655132222')),[])[::1-(h<0)*2]or['#'*9*abs(w)or'#']

```

```
lambda h,w:sum(([''.join('# '[int(n)]*abs(w)for n in bin(ord(' >w(8\x96I'[int(l)])*int(l))[2:])or'#']*abs(h)for l in'3433314655132222'),[])[::1-(h<0)*2]or['#'*9*abs(w)or'#']

```
> 16 votes

# Answer
# Perl 5, ~~169~~ ~~166~~ 157 bytes

```
@a=map"$_\n",(split 1,'  #####1   ###1    #1 #  #  #1#   #   #1  #   #')
[1011120344215555=~/./g];
print s/./$&x abs"@F"/ger x abs$F[1]for$F[1]<0?reverse@a:@a;

```

Try it online!

Maybe more could be gained by bit fiddling.
> 8 votes

# Answer
# Charcoal, 61 bytes

```
ＮθＮη¿θＦ⪪”{“↷Ｃ¿2t´⁴Ｑ19·“*Ｔy”!Ｅ↔θ∨⭆ι×μ↔η#×#∨×⁵↔η¹‖ＯＯ←∨↔η¹¿‹θ⁰‖↓

```

Try it online! Link is to verbose version of code. Explanation:

```
ＮθＮη

```

Input the dimensions.

```
¿θＦ⪪”{“↷Ｃ¿2t´⁴Ｑ19·“*Ｔy”!

```

If the height is nonzero, loop over the the right half of the sheriff...

```
Ｅ↔θ

```

... repeating the absolute height number of times...

```
∨⭆ι×μ↔η#

```

... if the width is nonzero then repeating each character the absolute number of times, otherwise a `#`.

```
×#∨×⁵↔η¹

```

But if the height is zero, then repeat `#` 5 times the absolute width, but at least 1 `#`.

```
‖ＯＯ←∨↔η¹

```

Reflect to produce the left half of the sheriff.

```
¿‹θ⁰‖↓

```

If the height is negative, flip the sheriff.
> 7 votes

# Answer
# Python 2, ~~217~~ 216 bytes

```
h,w=input();t=[];w=abs(w)
for i in range(16):c=bin(32+int('37333179HH134444'[i],26))[-5:];t+=[[''.join(abs(w)*' #'[d>'0']for d in c+c[3::-1]),'#'][w==0]]*abs(h)
print['\n'.join(t[::[1,-1][h<0]]),'#'*(w*16or 1)][h==0]

```

Try it online!

A Pythonic riff on Arnauld's approach.

Ugh! Now works for all edge conditions...
> 4 votes

# Answer
# Clean, ~~299~~ ~~275~~ 272 bytes

```
import StdEnv,Data.List
f=flatlines
r=repeatn
$0 0=['#']
$h w#w=abs w
|h==0=r(w*9)'#'
|w<1=f(r(abs h*16)['#'])
=f(if(h<0)reverse id[cjustify(w*9)(intercalate(spaces((0xde35945rem n)*10/n*w))(r((0xc8d88154f8fberem n)*10/n)(r w'#')))\\n<-map((^)10o~)[-16..0],_<-[1..abs h]])

```

Try it online!
> 3 votes

# Answer
# Powershell, ~~174~~ 170 bytes

Inspired by Arnauld's Javascript

```
param($w,$h)('CGCCCAGIQQACDDDD'[((0..15),(15..0))[$h-lt0]],31)[!$h]|%{$n=+$_
,(-join(4..0+1..4|%{,' #'[($n-shr$_)%2]*[Math]::Abs($w)}),'#')[!$w]*[Math]::Abs(($h,1)[!$h])}

```

Ungolfed, explained and test scripted:

```
<#

Script uses 5 bits of integer as 5 left chars of a line of a sheriff
Script ignores other bits in this integer, so we can use 6 bit to take a ASCII letter
    ##.         1 00011     C
   ###..        1 00111     G
    ##.         1 00011     C
    ##.         1 00011     C
    ##.         1 00011     C
     #          1 00001     A
   ###..        1 00111     G
  #  #  .       1 01001     I
 #   #   .  --> 1 10001 --> Q
 #   #   .      1 10001     Q
     #          1 00001     A
    ##.         1 00011     C
   #   .        1 00100     D
   #   .        1 00100     D
   #   .        1 00100     D
   #   .        1 00100     D

#>

$f = {

param($w,$h)
(
    'CGCCCAGIQQACDDDD'[             # 5 bits of each char correspond to 5 left symbols of line of sheriff.
        ((0..15),(15..0))[$h-lt0]], # forward or reverse sequence of chars
    31                              # or sequence of one element = 11111
)[!$h]|%{                           # choose a sequence and for each
    $n=+$_                          # integer or ASCII code
    ,(  -join(
            4..0+1..4|%{            # loop on bit range 4..0 and append fliped range 1..4
                ,' #'[($n-shr$_)%2]*[Math]::Abs($w)
            }                       # returns space or # depend on bit, repeat $w times
        ),
        '#'                         # returns # for $w equal 0
    )[!$w]*[Math]::Abs(($h,1)[!$h]) # choose a sheriff line, repeat $h times
}

}

@(
    ,(1,0)
    ,(0,1)
    ,(1,-1)
    ,(0,0)
    ,(1,1)
    ,(0,0)
    ,(-2,-1)
    ,(0,0)
    ,(2,2)
) | % {
    $w,$h = $_
    $r = &$f $w $h
    $r
}

```
> 2 votes

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


# Question
Title: Figure out the maximum amount of candy a child can collect
The city of Poughkeepsie celebrates Halloween every year. Geographically, the city is a rectangle that is 30 miles long and 45 miles wide. On a map, it looks like a grid, with its east-west roads horizontally dividing the city into 1-mile-long rectangles and its north-south roads vertically dividing the city likewise. There is one house at each road intersection.

The city's residents tend to be more generous with their candy as one moves toward the center of the rectangle. The resident at the lower-left corner of the city - whom we'll call Bob - gives out 10 candies per child. If a child starts at Bob's house and proceeds eastward, each resident they come across will give them 5 more candies than the last one (In other words, Bob's nearest eastern neighbor will give 15 candies. If a child walks another mile to the next eastern neighbor, they get another 20 candies.) After they reach the horizontal center street, that number decreases by 5. If that same child instead proceeds northward of Bob's house - which is located at (0,0) - each resident they meet will give them 10 more candies than the previous resident. After they reach the relevant center street, each resident they meet will give 10 less.

The number of candies given out by residents who do not live on the edges of the city is the sum of the number of candies given out by the two neighbors who live on the nearest borders of the city. So, a resident who lives at (44,29) will give out the number of candies given by the resident at (45,29) + the number of candies given by the resident at (30,44).

**Important note:** The only way to access each house is by walking along roads or adjacent paths. One is not allowed to, for example, bee-line from Bob's house to (1,1) - s/he must first either walk along the y-axis for 1 mile, turn right and walk for another mile; or walk along the x-axis for 1 mile, turn left and walk for another mile. Also, once a child has received candy from a house, they will receive no more candy from that same house.

**Objective:** Your program is to figure out how much candy a child can receive if s/he starts at Bob's house and is to walk no more than a given distance "d".

**Scoring** Programs will be scored based on the size (in bytes) of the source code.

# Answer
# Jelly, 58 bytes

```
Ø+0r;U$ṗµØ1W;⁸+\Q%“.þ‘)ẎẠ$Ƈµ20Ḋ×©5Ḋ+þ14Ḋ×⁵¤⁺;"Wɼ;ŒBm0⁸œị§Ṁ

```

Try it online!

Very slow (brute force), TIO can handle up to `8`. Test cases in \\$\[0,8\]\\$: Try it online!
> 1 votes

---
Tags: code-golf
---