title: Measuring Rectangles

text:
# Question
Title: Measuring Rectangles
### Challenge

Your goal is to write a program which will output the 8 measurements of a rectangle, with only some measurements in the input. Your program should throw an error if it cant be done.

Here is what each measurement means:

```
|          left
|          |      centerX
|          |      |      right
|          |      |      |
|          v      v      v
|           _____________
|       ^  |             |  <---top
|       |  |             |
|       |  |             |
|height |  |             |  <---centerY
|       |  |             |
|       |  |             |
|       v  |_____________|  <---bottom
|
|          <----width---->
|________________________________________

```

### Input/Output Formats:

Input is in the form of some measurements of a box, one on each line. Output should be all 8 measurements of the corresponding box (or an error if the given measurements can not be used to find the other measurements).

For example, an input of

```
left 6
centerX 10
top 40
height 20

```

should print out

```
left 6
right 14
top 40
bottom 20
centerX 10
centerY 30
width 8
height 20

```

This is code-golf, so the shortest code wins.

# Answer
### Python 2 with SWI Prolog ('typical' install), on Windows, 595 565 bytes.

```
import sys,subprocess as w;o='left right top bottom centerX centerY width height'
g={k:v for k,v in [l.strip().split() for l in sys.stdin.readlines()]};s='L,R,T,B,C,D,W,H';
open('t','w').write(
":-use_module(library(clpfd)).\nr(%s):-L#=R-2*(R-C),L#=R-W,L#=C-W//2,B#=T-2*(T-D),B#=T-H,B#=D-H//2,%s."%
(s,','.join('writeln(%s)'%x for x in s.split(','))));r='\n'.join([a+' '+b for (
a,b) in zip(o.split(),w.check_output("swipl -q -f t -t r(%s)."%(','.join(g.get(
x,x[0].replace('centerY','d').upper()) for x in o.split()))).split('\r\n'))])
print '!' if '_' in r else r

```

e.g. with a text file for input, containing:

```
right 14
centerX 10
top 40
height 20

```

it does this:

```
D:\>type rectin.txt|c:\python27\python.exe d:\rect.py
left 6
right 14
top 40
bottom 20
centerX 10
centerY 30
width 8
height 20

```

And in the error condition if the contents of the stdin file are not enough to calculate the other values, it does this:

```
D:\>type rectin.txt|c:\python27\python.exe d:\rect.py
!

```

*NB. It relies on swipl.exe being in the PATH*

### Explanation

I started writing in Python, got bored of expressing all the possible combinations of relationship (each one can be derived from three different combinations). I thought "must be a job for Prolog". So I installed a Prolog, headed for a tutorial, and got something that just about works. It's this:

```
:-use_module(library(clpfd)).

r(L,R,T,B,C,D,W,H):-
    L#=R-2*(R-C),
    L#=R-W,
    L#=C-W//2,
    B#=T-2*(T-D),
    B#=T-H,
    B#=D-H//2,

    writeln(L),
    writeln(R),
    writeln(T),
    writeln(B),
    writeln(C),
    writeln(D),
    writeln(W),
    writeln(H).

```

It uses the clpfd library (part of the 'typical install' requirement), which provides 'declarative integer arithmetic'. This gives the big advantage that I only need to define Left in terms of (Right and CenterX), (Right and Width), (CenterX and Width). From that, it can derive Right, Center and Width. (Same with the vertical set Top/Bottom/CenterY/Height).

This also means I don't have to check which specific values are provided; I give all the available values and placeholders for the rest, and it either calculates the answers, or outputs some unknown variable placeholders.

Being extremely novice at Prolog, handling STDIN was too much for me right now, so I wrapped it with Python. I don't have an ungolfed version of the Python, but it's not doing anything too amazing; it reads STDIN into a dictionary of {measurement:value} pairs, then puts them in the preset order the Prolog code is expecting, merged with the uppercase first letter of the unknowns.

(There's an annoyance where all the measurements are unique by first letter, except centerX and centerY, so it replaces centerY with D).

Then it writes the Prolog script out to a file, shells out to Prolog to run it and read the result, parses the number output and pairs them up with the measurements in order.

Then checks if any of the outputs were uncomputable and throws an error (`!`), otherwise prints the result.
> 6 votes

# Answer
# MFC, 212

```
void P(int l,int t,int r,int b){CRect R(l,t,r,b);POINT c=R.CenterPoint();TRACE("Left:%d Top:%d Right:%d Bottom:%d CenterX:%d CenterY:%d Width:%d H:%d",R.left,R.top,R.right,R.bottom,c.x,c.y,R.Width(),R.Height());}

```
~~MFC, 213
```
void P(int l,int t,int r,int b){CRect R(l,t,r,b);CPoint c=R.CenterPoint();TRACE("Left:%d Top:%d Right:%d Bottom:%d CenterX:%d CenterY:%d Width:%d H:%d",R.left,R.top,R.right,R.bottom,c.x,c.y,R.Width(),R.Height());}

```~~

Outputs the result to Visual Studio's Debug Output Window.

Example:

```
P(12,7,23,30);

```

outputs

```
Left:12 Top:7 Right:23 Bottom:30 CenterX:17 CenterY:18 Width:11

```

Uncondensed format:

```
void P(int l, int t, int r, int b)
{
    CRect R(l, t, r, b);
    CPoint c= R.CenterPoint();
    TRACE("Left %d Top:%d Right:%d Bottom:%d CenterX:%d CenterY:%d Width:%d H:%d", R.left, R.top, R.right, R.bottom, c.x, c.y, R.Width(), R.Height());
}

```
> 0 votes

---
Tags: code-golf, geometry
---


title: Can you loop without crashing?

text:
# Question
Title: Can you loop without crashing?
Many of us are familiar with the game Tron. You control a "lightcycle" placed on a grid. The lightcycle always moves forward (though you control the direction) and leaves a permanent trail behind it. If you run into a trail, you crash!

The goal here is to determine if a given path is a valid loop, that is, it returns to its starting point without "crashing". To do this, we assume we start at the point `(0,0)`. An input is given in the form `N2E1S2W1`, with a series of cardinal directions (`N` is `north`, `E` is `east`, and so on), each followed by the distance to travel that direction. In this example, you would travel

```
N2 : North 2 to (0,2)
E1 : East 1  to (1,2)
S2 : South 2 to (1,0)
W1 : West 1  to (0,0)

```

A path is considered valid if it ends at `(0,0)` without visiting any other coordinate more than once (it visits `(0,0)` exactly twice. Once at the start, and once at the end). Keep in mind than in the above example, to get from `(0,0)` to `(0,2)`, we necessarily visit `(0,1)` as well.

Other examples:

```
input        -> output
N1E1S1W1     -> true
N1E1N1E1S2W2 -> true
N1S1E1W1     -> false     // Visits (0,0) 3 times
N4E2S2W4S2E2 -> false     // Visits (0,2) twice
N3E2S3       -> false     // Does not return to (0,0)
N1S1         -> anything  //I don't care how you evaluate this case

```

Your output can be in any form so long as it gives the same output for any truthy or falsey value.

The input can be taken as a string or as a list of characters, either in the form `S1N2E3`... or `SNNEEE`... There's is also no hard limit on the grid size, but assume the input isn't going to overflow anything. As long as the code is fundamentally sound, It's not crucial to handle cases like `N99999999999999`.

NOTE: You may evaluate the cases `N1S1`, `E1W1`, `S1N1`, and `W1E1` however you would like. They're technically valid paths, but they go against the "Tron" spirit of the challenge.

# Scoring

This is , so the shortest answer wins!

# Answer
> 8 votes
# Pyth, ~~44~~ 39 bytes

```
&!eJsM._smm^.j)x"NESW"hdstd:z".\d+"1{IJ

```

Test suite.

# Answer
> 6 votes
# JavaScript, 247 200 bytes

```
n=s=>{r=s.match(/\w\d+/g)
x=y=z=0
e=""
for(d of r){a=d[0]
b=d.slice(1)
while(b--){
y+=a=="N"
y-=a=="S"
x+=a=="E"
x-=a=="W"
p=[x,y]+";"
if(~e.indexOf(p))if(!x&!y)z++
else return 0
e+=p}}return!x&!y&!z}

```

`n` is a function of input string `s` that returns `1` for true and `0` for false

Here's an ungolfed version for reference/explanation:

```
function n(s)
{
    var dir = s.match(/\w\d+/g);
    var x = y = z = 0;
    var been = "";
    for (d of dir)
    {
        var a = d[0];
        var b = 1*d.substring(1);
        while(b-- > 0)
        {
            if (a == "N") y++;
            if (a == "S") y--;
            if (a == "E") x++;
            if (a == "W") x--;
            var pt = [x,y] + ";";
            if (~been.indexOf(pt))
                if (x==0 && y==0)
                    z++;
                else
                    return false;
            been += pt;
        }
    }
    return (x == 0 && y==0 && z == 0);
}

```

```
n=s=>{r=s.match(/\w\d+/g)
x=y=z=0
e=""
for(d of r){a=d[0]
b=d.slice(1)
while(b--){
y+=a=="N"
y-=a=="S"
x+=a=="E"
x-=a=="W"
p=[x,y]+";"
if(~e.indexOf(p))if(!x&!y)z++
else return 0
e+=p}}return!x&!y&!z}

console.log(n("N1E1S1W1"))
console.log(n("N1E1N1E1S2W2"))
console.log(n("N1S1E1W1"))
console.log(n("N4E2S2W4S2E2"))
console.log(n("N3E2S3"))
```

# Answer
> 5 votes
# Python 3, ~~236~~ ~~161~~ 150 bytes

```
import re
p=0
a=[]
for i in''.join(s[0]*int(s[1:])for s in re.findall(r".\d+",input())):p+=1j**"NESW".find(i);a+=[p]
print(len({*a})-len(a)==0==a[-1])

```

Try it online!

-75 bytes thanks to Leaky Nun
-11 bytes thanks to Leaky Nun Or, if we're allowed to take input as a list of run length decoded complex numbers:

# Python 2, ~~85~~ 73 bytes

```
c=0;k=[]
for i in input():c+=i;k+=[c]
print(k[-1]==0==len(set(k))-len(k))

```

Try it online!

-12 bytes thanks to Mr. Xcoder / -9 bytes thanks to Leaky Nun (merged into one edit)

This feels too long to me lol

# Answer
> 3 votes
## Jelly, ~~14~~ 12 bytes

```
Œṙ+\µQ⁼ȧṛ/¬$

```

This is my first time golfing in Jelly. Suggestions are welcome.

Input is as an array of `[direction, distance]` pairs, where the direction is given as a complex number.

## Explanation:

```
Œṙ+\µÇȧṛ/¬$   Main link. Argument: n     = [[i, 3], [1, 2], [-i, 3]]
Œṙ            Run-length decode          = [i, i, i, 1, 1, -i, -i, -i]
  +\          Cumulative sum             = [i, 2i, 3i, 3i+1, 3i+2, 2i+2, i+2, i]
    µ         Begin a new monadic chain
     Q        Remove duplicates          = [i, 2i, 3i, 3i+1, 3i+2, 2i+2, i+2]
      ⁼       Equal to original?         = 0
           $  Make a monadic link:
        ṛ/      Reduce by right argument   = i
                (Gets the last element)
          ¬     Logical NOT:               = 0
       ȧ      Logical AND the two values = 0

```

# Answer
> 0 votes
# Retina, 86 bytes

```
\d+
$*
1(1*)
$1
+`(.)1
$1$1
.
 $`$&¶
%O`.
+`NS|E(.*)W
$1
M`\w$|(?m)(^.+$)(?s).+^\1$
^0

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert the numbers to unary.

```
1(1*)
$1
+`(.)1
$1$1

```

Run-length decode the letters. `N111` needs to turn into `NNN`, so one is subtracted from each unary number and then each 1 duplicates the previous letter.

```
.
 $`$&¶

```

Generate all the prefixes (i.e. points on the path) as separate lines. A space is prefixed to avoid issues with empty lines.

```
%O`.
+`NS|E(.*)W
$1

```

Sort all the letters in each line into order and then delete matching pairs. We end up with a unique code for any given point on the grid.

```
M`\w$|(?m)(^.+$)(?s).+^\1$

```

Check for one of two things: a) the last point doesn't end in a space (i.e. the loop didn't close), or two duplicate points in the path. If the path is valid, all checks fail and the result is zero.

```
^0

```

Invert the result.

# Answer
> 0 votes
## Perl, 140

Works with string input. Perhaps I can shorten with array,but I doubt it. Happy for any further golfing help :)

```
sub w{$i=$_[0];%d=(E,[0],S,[1,-1],W,[0,-1]);$i=~s/(.)(.)/($d,$o)=(@{$d{$1}},1,1);for(1..$2){$s[$d]+=$o;$r+=$d{"@s"}++}/eg;!($s[0]+$s[1]+$r)}

```

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


# Question
Title: Solving variants of the blue-eyes puzzle
The original "Blue Eyes" puzzle is given here (and below).

> A group of people with assorted eye colors live on an island. They are all perfect logicians -- if a conclusion can be logically deduced, they will do it instantly. No one knows the color of their eyes. Every night at midnight, a ferry stops at the island. Any islanders who have figured out the color of their own eyes then leave the island, and the rest stay. Everyone can see everyone else at all times and keeps a count of the number of people they see with each eye color (excluding themselves), but they cannot otherwise communicate. Everyone on the island knows all the rules in this paragraph.
>
> On this island there are 100 blue-eyed people, 100 brown-eyed people, and the Guru (she happens to have green eyes). So any given blue-eyed person can see 100 people with brown eyes and 99 people with blue eyes (and one with green), but that does not tell him his own eye color; as far as he knows the totals could be 101 brown and 99 blue. Or 100 brown, 99 blue, and he could have red eyes.
>
> The Guru is allowed to speak once (let's say at noon), on one day in all their endless years on the island. Standing before the islanders, she says the following:
>
> "I can see someone who has blue eyes."
>
> Who leaves the island, and on what night?

The answer is that they all leave on the hundredth day. This is due to the following logic:

> If there is one blue-eyed person only, he will leave on day 1. If there are two-blue-eyed people only, nobody leaves on day 1. Following this, they both leave on day 2. Now if there are 3 blue-eyed people, nobody leaves on day 1. Nobody leaves on day 2 either. Now everyone knows that there are 3 blue-eyed people, because if there were only one, he would have left on day 1 and if there are two, they both would have left on day 2. Hence all 3 leave on day 3.
>
> We can now write an inductive proof that if n blue-eyed people require n days to figure out their eye colours and leave, then n+1 blue-eyed people require n+1 days to do the same.

However, the code you write should be capable of solving not just the original puzzle, but also some variants that require slightly different inductive steps.

You will be told how many of the islanders have blue eyes and how many don't. You will also be given a statement by the oracle (a system of equations/inequations) that everyone on the island hears. You need to determine when the island will be free of the blue-eyed people.

The oracle's statements will use `b` for the number of blue-eyed people and `r` for the number of non-blue-eyed people. The equations can include `< > <= >= = + -` and any whole numbers.

## Test cases

Based on this set of variants

```
50 50
b>=1
b<b+r

```

Output: `50`

The second equation gives no new information, hence this problem becomes exactly the same as the original puzzle.

```
100 50
b+3>=r+4

```

Output: `25`

```
100 0
b-2>8+1-1

```

Output: `90`

```
50 50
b>=10
b<=75

```

Output: `41`

# Answer
# Python 2, ~~60~~ 48 bytes

```
f=lambda b,r,c:all(map(eval,c))and-~f(b-1,r+1,c)

```

Try it online!

# How it works

By induction:

* If the island composition is (*b*, *r*) and it is known that (*b* − 1, *r* \+ 1) is not possible, then on day 1, the blue-eyed islanders, seeing (*b* − 1, *r*), will conclude that they are blue-eyed and leave.
* If the island composition is (*b*, *r*) and it is known that the blue-eyed islanders would have left on day *n* if the composition were (*b* − 1, *r* \+ 1), then on day *n* \+ 1, the blue-eyed islanders, seeing (*b* − 1, *r*), will conclude that they are blue-eyed and leave.

This second inference fails if *b* = 1, but in that case, the blue-eyed islander would never leave if they hadn’t already, and the test case would be invalid.

Note that non-blue-eyed islanders will never leave, in this version of the puzzle, because even if they use similar logic to conclude that they are not blue-eyed, they still don’t know which non-blue color their eyes are.
> 1 votes

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


title: Use letters to make numbers shorter

text:
# Question
Title: Use letters to make numbers shorter
### Challenge

Take a number and output it with 4 digits or less using letters and numbers. For example; `270,030` would turn into `270K`.

### Key

Billion -\> `B`

Million -\> `M`

Thousand -\> `K`

### Rules

* You may choose to accept input numbers that include commas delimiting every three decimal places (such as `123,456,789`).
* Round to nearest, half-up.
* Numbers will only go up to `999,499,999,999` .
* The mantissa part of the answer should be at least 1.
* All letters must be uppercase and as specified above.
* Outputs must be 4 or less digits. (including letters such as `B`, `K`, and `M`)
* Outputs must be as mathematically precise as possible. Example:
    + `15,480` -\> `20K` **NOT OK**
    + `15,480` -\> `15.5K` **GOOD**
* If there are multiple outputs with the same mathematical precision, return either one. Example:
    + `1000` -\> `1000` **GOOD**
    + `1000` -\> `1K` **GOOD**

### Examples:

```
1,234,567 -> 1.23M
999,500 -> 1M
999,499 -> 999K
102 -> 102
1000 -> 1K
1001 -> 1001
100,000 -> 100K
12,345,678,912 -> 12.3B
1,452,815,612 -> 1.45B

```

### Submissions

# Answer
> 3 votes
# JavaScript, ~~84~~ 79 bytes

```
i=>{I=i;for(x=-1;i>=999.5;x++)i/=1e3;return I<1e4?I:+i.toPrecision(3)+'KMB'[x]}

```

Try it online!

(Takes inputs as numbers)

Special cases the first one where if `i < 1000`, the number itself is always one of the shortest ways, if not the only shortest way.

Otherwise, it divides it by 1000 until dividing it would make it have no sigificant figures above 1, and chooses a suffix based on how many divisions were done.

# Answer
> 1 votes
# Python 3, 127 bytes

```
def f(n):s=str(n);l=len(s)-4;return f"{round(n,~l):,}"[:4].replace(*",.").rstrip('.')+"KMBT"[l//3+(int(s[3])>4)]if n>9999else n

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES7), 74 bytes

```
n=>n<1e4?n:(c=n.toExponential(2).split`e`).shift()*10**(c%3)+' KMB'[c/3|0]

```

```
let f=

n=>n<1e4?n:(c=n.toExponential(2).split`e`).shift()*10**(c%3)+' KMB'[c/3|0]

console.log(f(1234567)); // 1.23M
console.log(f(999500)); // 1M
console.log(f(999499)); // 999K
console.log(f(102)); // 102
console.log(f(1000)); // 1000
console.log(f(1001)); // 1001
console.log(f(100000)); // 100K
console.log(f(12345678912)); // 12.3B
console.log(f(1452815612)); // 1.45B
```

# JavaScript (ES6), 80 bytes

```
n=>n<1e4?n:(c=n.toExponential(2).split`e`).shift()*[1,10,100][c%3]+' KMB'[c/3|0]

```

```
let f=

n=>n<1e4?n:(c=n.toExponential(2).split`e`).shift()*[1,10,100][c%3]+' KMB'[c/3|0]

console.log(f(1234567)); // 1.23M
console.log(f(999500)); // 1M
console.log(f(999499)); // 999K
console.log(f(102)); // 102
console.log(f(1000)); // 1000
console.log(f(1001)); // 1001
console.log(f(100000)); // 100K
console.log(f(12345678912)); // 12.3B
console.log(f(1452815612)); // 1.45B
```

---
Tags: code-golf
---


title: ASCII 2D game-map

text:
# Question
Title: ASCII 2D game-map
# Problem

Given input `a` where a is a grid of characters in any input format as long as it has only one element for each 'block' of the output.

And input `b` where b is a grid of numbers the same size as input `a`.

There are two types of road, a 1 represents a stone road marked by `@` and a 2 represents a dirt road marked by `#`

* A `@` road is centered in the block and is size 6x6, if a road is adjacent, that side is extended to grid cell border
* A `#` road is centered in the block is size 4x4, if a road is adjacent, that side is extended to grid cell border

Output a grid offset by line number of 8x8 of the ASCII character in input `a` and overlay a 'road' from input `b` e.g.

Input `a=[[a,b,a],[b,a,b],[a,b,a]] b=[[1,1,1],[2,0,1],[2,0,0]]`

Output:

Step 1: the grid (8x8 representation of input `a`)

```
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa

```

Step 2: Overlay with roads represented by `b`:

```
aaaaaaaabbbbbbbbaaaaaaaa
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@abbbbbbbba@@@@@@a
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaabbbbbbbb
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa

```

Step 3: Offset each line with linenumber:

```
aaaaaaaabbbbbbbbaaaaaaaa
 a@@@@@@@@@@@@@@@@@@@@@@a
  a@@@@@@@@@@@@@@@@@@@@@@a
   a@@@@@@@@@@@@@@@@@@@@@@a
    a@@@@@@@@@@@@@@@@@@@@@@a
     a@@@@@@@@@@@@@@@@@@@@@@a
      a@@@@@@@@@@@@@@@@@@@@@@a
       a@@@@@@abbbbbbbba@@@@@@a
        bb####bbaaaaaaaab@@@@@@b
         bb####bbaaaaaaaab@@@@@@b
          bb####bbaaaaaaaab@@@@@@b
           bb####bbaaaaaaaab@@@@@@b
            bb####bbaaaaaaaab@@@@@@b
             bb####bbaaaaaaaab@@@@@@b
              bb####bbaaaaaaaab@@@@@@b
               bb####bbaaaaaaaabbbbbbbb
                aa####aabbbbbbbbaaaaaaaa
                 aa####aabbbbbbbbaaaaaaaa
                  aa####aabbbbbbbbaaaaaaaa
                   aa####aabbbbbbbbaaaaaaaa
                    aa####aabbbbbbbbaaaaaaaa
                     aa####aabbbbbbbbaaaaaaaa
                      aaaaaaaabbbbbbbbaaaaaaaa
                       aaaaaaaabbbbbbbbaaaaaaaa

```

### Rules:

* Leading whitespace or newlines allowed.
* Trailing whitespace and newlines allowed.
* This is code-golf so shortest code wins

Here is an extra test case with all edge cases in I can think of.

# Answer
# JavaScript (ES6), 250 ~~207~~ bytes

*Edit* Bug fix :(

A function taking inputs in currying syntax (a)(b).

```
a=>b=>a.map((r,i)=>k.map(y=>(h+=' ')+r.map((c,j)=>k.map(x=>(t=x<v,s=x>7-v,!v|t&(!q[j-1]|w|u)|s&(!q[j+1]|w|u)|u&(!p[j]|t|s)|w&(!(b[i+1]||[])[j]|t|s)?c:'-@#'[v]),v=q[j],w=y>7-v,u=y<v).join``).join``,p=q,q=b[i]).join`
`,h=q=[],k=[...'01234567']).join`
`

```

*Less golfed*

```
a=>b=>a.map((r,i)=>
  [0,1,2,3,4,5,6,7].map(y=>
    (h+=' ') + r.map((c,j)=>
      [0,1,2,3,4,5,6,7].map(x=> (
        t=x<v, s=x>7-v,
        v == 0
        || t && (!B[i][j-1] | w|u)
        || s && (!B[i][j+1] | w|u)
        || u && (!(B[i-1]||[])[j] | t|s)
        || w && (!(B[i+1]||[])[j] | t|s)
        ? c : '-@#'[v] )
      , v = B[i][j], w=y>7-v,u=y<v).join``
    ).join``
  ).join`\n`
,h = '').join`\n`

```

**Test**

```
F=
a=>b=>a.map((r,i)=>k.map(y=>(h+=' ')+r.map((c,j)=>k.map(x=>(t=x<v,s=x>7-v,!v|t&(!q[j-1]|w|u)|s&(!q[j+1]|w|u)|u&(!p[j]|t|s)|w&(!(b[i+1]||[])[j]|t|s)?c:'-@#'[v]),v=q[j],w=y>7-v,u=y<v).join``).join``,p=q,q=b[i]).join`
`,h=q=[],k=[...'01234567']).join`
`

A=[['a','b','a'],['b','a','b'],['a','b','a']]
B=[[1,1,1],[2,0,1],[2,0,0]]

O.textContent = F(A)(B)+'\n'
A=[['.', ',', '.', ',', '.', ',', '.'],['.', ',', '.', ',', '.', ',', '.'],['.', ',', '.', ',', '.', ',', '1']]
B=[[0,1,0,0,1,2,0],[1,1,1,2,2,2,2],[0,2,0,0,0,1,0]]

O.textContent += F(A)(B)
```

```
<pre id=O></pre>
```
> 3 votes

# Answer
# PHP 857 bytes

Not really what anyone could call "golfed" but since nobody else seems to have entered anything at all, I figured this was a start. It's massive, but it seems to work. Will make an effort to golf it tomorrow if I get the time.

```
function a($a,$b){$c=sizeof($a);$d=sizeof($a[0]);for($e=0;$e<$c;$e++){for($f=0;$f<$d;$f++){$A=$GLOBALS['h']=$a[$e][$f];$i=$GLOBALS['i']=$b[$e][$f];$B=j($i==1&&$b[$e-1][$f]>0);$C=j($i==1&&$b[$e][$f+1]>0);$D=j($i==1&&$b[$e+1][$f]>0);$E=j($i==1&&$b[$e][$f-1]>0);$F=j($i>0&&$b[$e-1][$f]>0);$G=j($i>0&&$b[$e][$f+1]>0);$H=j($i>0&&$b[$e+1][$f]>0);$I=j($i>0&&$b[$e][$f-1]>0);$J=j($i==1);$K=j($i==1||($i>1&&$b[$e-1][$f]>0));$L=j($i==1||($i>1&&$b[$e][$f+1]>0));$M=j($i==1||($i>1&&$b[$e+1][$f]>0));$N=j($i==1||($i>1&&$b[$e][$f-1]>0));$O=j($i>0);$P=$e*8;$g[$P].="$A$B$F$F$F$F$B$A";$g[$P+1].="$E$J$K$K$K$K$J$C";$l="$I$N$O$O$O$O$L$G";$g[$P+2].=$l;$g[$P+3].=$l;$g[$P+4].=$l;$g[$P+5].=$l;$g[$P+6].="$E$J$M$M$M$M$J$C";$g[$P+7].="$A$D$H$H$H$H$D$A";}}foreach($g as$h){echo str_repeat(' ', $i++)."$h\n";}}function j($k){return($k)?strtr($GLOBALS['i'],'12','@#'):$GLOBALS['h'];}

```

Test case

```
error_reporting(0);
$a=[[a,b,a],[b,a,b],[a,b,a]];
$b=[[1,1,1],[2,0,1],[2,0,0]];
a($a,$b);

```

Output

```
aaaaaaaabbbbbbbbaaaaaaaa
 a@@@@@@@@@@@@@@@@@@@@@@a
  a@@@@@@@@@@@@@@@@@@@@@@a
   a@@@@@@@@@@@@@@@@@@@@@@a
    a@@@@@@@@@@@@@@@@@@@@@@a
     a@@@@@@@@@@@@@@@@@@@@@@a
      a@@@@@@@@@@@@@@@@@@@@@@a
       a@@@@@@abbbbbbbba@@@@@@a
        bb####bbaaaaaaaab@@@@@@b
         bb####bbaaaaaaaab@@@@@@b
          bb####bbaaaaaaaab@@@@@@b
           bb####bbaaaaaaaab@@@@@@b
            bb####bbaaaaaaaab@@@@@@b
             bb####bbaaaaaaaab@@@@@@b
              bb####bbaaaaaaaab@@@@@@b
               bb####bbaaaaaaaabbbbbbbb
                aa####aabbbbbbbbaaaaaaaa
                 aa####aabbbbbbbbaaaaaaaa
                  aa####aabbbbbbbbaaaaaaaa
                   aa####aabbbbbbbbaaaaaaaa
                    aa####aabbbbbbbbaaaaaaaa
                     aa####aabbbbbbbbaaaaaaaa
                      aaaaaaaabbbbbbbbaaaaaaaa
                       aaaaaaaabbbbbbbbaaaaaaaa

```

Test case

```
error_reporting(0);
$a=[['.', ',', '.', ',', '.', ',', '.'],['.', ',', '.', ',', '.', ',', '.'],['.', ',', '.', ',', '.', ',', '1']];
$b=[[0,1,0,0,1,2,0],[1,1,1,2,2,2,2],[0,2,0,0,0,1,0]];
a($a,$b);

```

Output

```
........,,,,,,,,........,,,,,,,,........,,,,,,,,........
 ........,@@@@@@,........,,,,,,,,.@@@@@@@,,,,,,,,........
  ........,@@@@@@,........,,,,,,,,.@@@@@@@######,,........
   ........,@@@@@@,........,,,,,,,,.@@@@@@@######,,........
    ........,@@@@@@,........,,,,,,,,.@@@@@@@######,,........
     ........,@@@@@@,........,,,,,,,,.@@@@@@@######,,........
      ........,@@@@@@,........,,,,,,,,.@@@@@@@,,####,,........
       ........,@@@@@@,........,,,,,,,,.@@@@@@.,,####,,........
        ........,@@@@@@,........,,,,,,,,..####..,,####,,........
         .@@@@@@@@@@@@@@@@@@@@@@@,,,,,,,,..####..,,####,,........
          .@@@@@@@@@@@@@@@@@@@@@@@##############################..
           .@@@@@@@@@@@@@@@@@@@@@@@##############################..
            .@@@@@@@@@@@@@@@@@@@@@@@##############################..
             .@@@@@@@@@@@@@@@@@@@@@@@##############################..
              .@@@@@@@@@@@@@@@@@@@@@@@,,,,,,,,........,,####,,........
               ........,@@@@@@,........,,,,,,,,........,,####,,........
                ........,,####,,........,,,,,,,,........,@@@@@@,11111111
                 ........,,####,,........,,,,,,,,........,@@@@@@,11111111
                  ........,,####,,........,,,,,,,,........,@@@@@@,11111111
                   ........,,####,,........,,,,,,,,........,@@@@@@,11111111
                    ........,,####,,........,,,,,,,,........,@@@@@@,11111111
                     ........,,####,,........,,,,,,,,........,@@@@@@,11111111
                      ........,,,,,,,,........,,,,,,,,........,@@@@@@,11111111
                       ........,,,,,,,,........,,,,,,,,........,,,,,,,,11111111

```

Test case

```
error_reporting(0);
$a=[[p,p,p,p,h,h,h,p,p,p,p],[p,p,p,p,h,h,h,p,p,p,p],[p,p,p,p,h,h,h,p,p,p,p],[p,p,p,p,h,h,h,p,p,p,p],[p,p,p,p,h,h,h,p,p,p,p]];
$b=[[1,1,1,0,1,0,1,0,1,1,1],[1,0,1,0,1,0,1,0,1,0,1],[1,1,1,0,1,1,1,0,1,1,1],[1,0,0,0,1,0,1,0,1,0,0],[1,0,0,0,1,0,1,0,1,0,0]];
a($a,$b);

```

Output

```
pppppppppppppppppppppppppppppppphhhhhhhhhhhhhhhhhhhhhhhhpppppppppppppppppppppppppppppppp
 p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
  p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
   p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
    p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
     p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
      p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
       p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
        p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
         p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
          p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
           p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
            p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
             p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
              p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
               p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
                p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
                 p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
                  p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
                   p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
                    p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
                     p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
                      p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
                       p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                        p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                         p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                          p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                           p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                            p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                             p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                              p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                               p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                                p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                                 p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                                  p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                                   p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                                    p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                                     p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                                      p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
                                       pppppppppppppppppppppppppppppppphhhhhhhhhhhhhhhhhhhhhhhhpppppppppppppppppppppppppppppppp

```
> 4 votes

# Answer
# Java - 661 bytes

Hi! This is my first submission here. If I did something wrong please tell me.

```
static void m(char[][]b,int[][]t){String z="";int w=b[0].length;int h=b.length;char[][]r=new char[h*8][w*8];for(int j=0;j<h;j++){for(int i=0;i<w;i++){for(int x=0;x<8;x++)for(int y=0;y<8;y++){r[j*8+y][i*8+x]=b[j][i];int n=t[j][i];if(n!=0){char c;int d,e;if(n==1){c='@';e=0;d=7;}else{c='#';e=1;d=6;}if(x>e&&y>e&&x<d&&y<d)r[j*8+y][i*8+x]=c;if(x>e&&x<d){if(j>0&&y<2&&t[j-1][i]!=0)r[j*8+y][i*8+x]=c;if(j<h-1&&y>5&&t[j+1][i]!=0)r[j*8+y][i*8+x]=c;}if(y>e&&y<d){if(i>0&&x<2&&t[j][i-1]!=0)r[j*8+y][i*8+x]=c;if(i<w-1&&x>5&&t[j][i+1]!=0)r[j*8+y][i*8+x]=c;}}}}for(int l=0;l<8;l++){System.out.println(z+Arrays.toString(r[j*8+l]).replaceAll("[\\[\\]]|[, ]\\s",""));z+=" ";}}}

```

You can try it here :)

Unminified:

```
static void m(char[][] b, int[][] t) {
    String z="";
    int w=b[0].length;int h=b.length;
    char[][]r=new char[h*8][w*8];
    for(int j=0;j<h;j++){
        for(int i=0;i<w;i++){
            for(int x=0;x<8;x++)for(int y=0;y<8;y++){
                r[j*8+y][i*8+x] = b[j][i];
                int n=t[j][i];
                if(n!=0){
                    char c;int d,e;
                    if(n==1){c='@';e=0;d=7;}
                    else{c='#';e=1;d=6;}
                    if(x>e&&y>e&&x<d&&y<d)r[j*8+y][i*8+x]=c;

                    if(x>e&&x<d){
                        if(j>0&&y<2&&t[j-1][i]!=0)r[j*8+y][i*8+x]=c;
                        if(j<h-1&&y>5&&t[j+1][i]!=0)r[j*8+y][i*8+x]=c;
                    }
                    if(y>e&&y<d){
                        if(i>0&&x<2&&t[j][i-1]!=0)r[j*8+y][i*8+x]=c;
                        if(i<w-1&&x>5&&t[j][i+1]!=0)r[j*8+y][i*8+x]=c;
                    }
                }
            }
        }
        for(int l=0;l<8;l++){System.out.println(z+Arrays.toString(r[j*8+l]).replaceAll("[\\[\\]]|[, ]\\s",""));z+=" ";}
    }
}

```
> 2 votes

# Answer
# JavaScript - 299 bytes

```
(a,b,g=(x,y)=>!(b[y]||0)[x],u=s=r='',L='length',R='repeat')=>{for(y=v=-1;++y<a[L];)for(i=v;++i<8;)for(x=v,s+=`
`+r,r+=' ';m=b[y][++x],W=Q=a[y][x],W+=(Z=~m&1)?Q:u,D=(A=i<m)|(B=i>7-m)?W:u,p=g(x-1,y)?W:D,q=g(x+1,y)?W:D,x<a[0][L];)s+=p+(A&&g(x,y-1)||B&&g(x,y+1)||!m?Q:'@#'[Z])[R](8-(p+q)[L])+q;return s}

```

# Try it here
> 0 votes

# Answer
# PHP, ~~275 268 266 264~~ 252 bytes

```
<?foreach($_GET[a]as$y=>$r)for($z=8;$z--;)for($x=-print"
".$f.=" ";$w--||$c=$r[++$x+!$w=7];)echo[$a=($s=($m=$_GET[b])[$y])[$x+1],$a|$b=2>$n=$s[$x],1,1,1,1,$b|$a=$s[$x-1],$a][$w]*[$a=$m[$y+1][$x],$a|$b,1,1,1,1,$b|$a=$m[$y-1][$x],$a][$z]*$n?" @#"[$n]:$c;

```

takes input from GET parameters `a` and `b`, prints to STDOUT. Try it online.

**breakdown**

```
foreach($_GET[a]as$y=>$r)   # loop 1: through rows of first array
    for($z=8;$z--;)             # loop 2: $z from 7 to 0 (line = 8*$y+7-$z)
        for($x=-print"\n".$f.=" ";  # print newline and padding
            $w--                        # loop 4: loop $w from 7 to 0 (column = 8*$x+7-$w)
            ||$c=$r[++$x+!$w=7];)   # loop 3: loop $c through characters in row
                echo
                [                               # vertical test
                    $a=($s=($m=$_GET[b])[$y])[$x+1],    # $m=2nd array, $s=current row
                                                        # $a=block to the right has road
                    $a|$b=2>$n=$s[$x],                  # $b=current block has brick road
                    1,1,1,1,
                    $b|$a=$s[$x-1],                     # $a=block to the left has road
                    $a
                ][$w]                               # index tests
                *
                [                               # horizontal test
                    $a=$m[$y+1][$x],                    # $a=block below has road
                    $a|$b,
                    1,1,1,1,
                    $b|$a=$m[$y-1][$x],                 # $a=block above has road
                    $a
                ][$z]                               # index tests
                *$n                             # is a road in this block?
                ?" @#"[$n]:$c;                  # if block&v-test&h-test then print road
                                                # else print character from 1st array

```
> 0 votes

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


title: ASCII Doodling: Laser in a Box

text:
# Question
Title: ASCII Doodling: Laser in a Box
Sometimes when I'm doodling, I draw a rectangle, start with a diagonal from one of the corners, and then just trace out a line by "reflecting" it whenever I hit a side of the rectangle. I continue with this until I hit another corner of the rectangle (and hope that the aspect ratio of my rectangle was not irrational ;)). This is like tracing out the path of a laser shone into a box. You're to produce the result of that with ASCII art.

As an example, consider a box of width `5` and height `3`. We'll always start in the top left corner. The `#` marks the boundary of the box. Note that the width and height refer to the inner dimensions.

```
#######    #######    #######    #######    #######    #######    #######
#\    #    #\    #    #\   \#    #\  /\#    #\  /\#    #\/ /\#    #\/\/\#
# \   #    # \  /#    # \  /#    # \/ /#    # \/ /#    #/\/ /#    #/\/\/#
#  \  #    #  \/ #    #  \/ #    # /\/ #    #\/\/ #    #\/\/ #    #\/\/\#
#######    #######    #######    #######    #######    #######    #######

```

## The Challenge

Given the (positive) width and height of the box, you should produce the final result of tracing out the laser. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument, function argument and output the result via STDOUT (or closest alternative), or via function return values or arguments.

You may use any convenient list, string or number format for input. The output must be a single string (unless you print it to STDOUT, which you may of course do gradually). This also means you can take the height first and the width second - just specify the exact input format in your answer.

There must be neither leading nor trailing whitespace on any line of the output. You may optionally output a single trailing newline.

You must use space, `/`, `\` and `#` and reproduce the test cases exactly as shown.

## Test Cases

```
2 2
####
#\ #
# \#
####

3 2
#####
#\/\#
#/\/#
#####

6 3
########
#\    /#
# \  / #
#  \/  #
########

7 1
#########
#\/\/\/\#
#########

1 3
###
#\#
#/#
#\#
###

7 5
#########
#\/\/\/\#
#/\/\/\/#
#\/\/\/\#
#/\/\/\/#
#\/\/\/\#
#########

22 6
########################
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
# /\  /\  /\  /\  /\  /#
#/  \/  \/  \/  \/  \/ #
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
########################

```

# Answer
> 20 votes
# Pyth, ~~43~~ ~~41~~ 39 bytes

```
K*\#+2QKVvzp<*QXX*dyivzQN\\_hN\/Q\#\#)K

```

Try it online: Pyth Compiler/Executor. Input the numbers in the following order: height first line, width second line.

Thanks to isaacg, who helped saving two bytes.

## Explanation:

My solution doesn't trace the laser, it uses a simple pattern that includes the gcd. If `m, n` are the dimensions of the box, let `d = gcd(m, n)`. The size of the pattern is exactly `2*d x 2*d`.

E.g. the repeating pattern for `7 5`

```
#########
#\/\/\/\#
#/\/\/\/#
#\/\/\/\#
#/\/\/\/#
#\/\/\/\#
#########

```

is

```
\/
/\

```

(`gcd(7, 5) = 1`, size of pattern is `2 x 2`)

And the repeating pattern for `22 6`

```
########################
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
# /\  /\  /\  /\  /\  /#
#/  \/  \/  \/  \/  \/ #
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
########################

```

is

```
\  /
 \/
 /\
/  \

```

(`gcd(22, 6) = 2`, size of pattern is `4 x 4`)

My solution does the following thing for each of the lines: it simply generates one line of the pattern, repeats it a few times and cut's it at the end so that it fit's into the box.

```
K*\#+2QK   implicit: Q is the second input number (=width)
K          K =
 *\#+2Q        "#" * (2 + Q)
       K   print K (first line)

Vvzp<*QXX*dyivzQN\\_hN\/Q\#\#)K  implicit: vz is the first input number (=height)
VQ                               for N in [0, 1, ..., vz-1]:
           ivzQ                             gcd(vz,Q)
          y                               2*gcd(vz,Q)
        *d                           string with 2*gcd(vz,Q) space chars
       X       N\\                   replace the Nth char with \
      X           _hN\/              replace the -(N+1)th char with /
    *Q                               repeat Q times
   <                   Q           only use the first Q chars
  p                     \#\#       print "#" + ... + "#"
                            )    end for
                             K   print K

```

# Answer
> 11 votes
# C, 256 bytes

```
f(w,h){int i,j,x=1,y=1,v=1,u=1;char b[h+2][w+3];for(i=0;i<w+3;i++)for(j=0;j<h+2;j++)b[j][i]=!i||!j||i>w||j>h?i>w+1?0:35:32;while((x||y)&&(x<=w||y<=h))v=x&&w+1-x?v:(x-=v,-v),u=y&&h+1-y?u:(y-=u,-u),b[y][x]=v/u<0?47:92,x+=v,y+=u;for(i=0;i<h+2;i++)puts(b[i]);}

```

I can probably get this under 200, and I'll add an explanation later, but I *might* have a paper due in a few hours I should be doing instead.

# Answer
> 5 votes
# J, 85 bytes

Let `g = gcd(w,h)`. The function fills the elements of a `w/g by h/g` matrix with `g by g` tiles, having `/`'s and `\`'s in their diagonal and anti-diagonal. The resulting 4D array is raveled into a 2D one (the inside of the box) then surrounded with `#`'s. (The numbers `0 1 2 3` are used instead of `[space] / \ #` and the numbers are changed to characters at the end.)

A direct position based computation of inside coordinate could maybe yield a bit shorter solution.

```
' \/#'echo@:{~3,.~3,.3,~3,,$[:,[:,"%.0 2 1 3|:((,:2*|.)@=@i.@+.){~[:(2&|@+/&:i.)/,%+.

```

Usage:

```
   6 (' \/#'echo@:{~3,.~3,.3,~3,,$[:,[:,"%.0 2 1 3|:((,:2*|.)@=@i.@+.){~[:(2&|@+/&:i.)/,%+.) 22
########################
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
# /\  /\  /\  /\  /\  /#
#/  \/  \/  \/  \/  \/ #
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
########################

```

Try it online here.

# Answer
> 0 votes
# Desmos Calculator - Non Competing to Help Further Knowledge

Try it online!

**Inputs:**

```
h as height of box, with 0-indexing
w as width of box, with 0-indexing

```

**Intermediates:**

```
Let b = gcd(h,w),
Let c = |b-h%2b| Or |b-mod(h,2b)|

```

**Formula, abbreviated:**

```
(|b-(x+y)%2b|-c)(|b-(x-y)%2b|-c)=0

```

**Outputs:**

```
x as x position, 0-indexed, where the ball will land when released
y as y position, 0-indexed, where the ball will land when released

```

**How it Works:**

```
(|b-(x+y)%2b|-c)*(|b-(x-y)%2b|-c)=0
                ^ OR operation - |b-(x+y)%2b|-c=0 or |b-(x-y)%2b|-c=0
|b-(x+/-y)%2b|-c = 0
|b-(x+/-y)%2b| = c
|b-(x+/-y)%2b| = c means (b-(x+/-y))%2b = + or -c
b-(x+/-y)%2b = +/- c -> b +/- c = (x+/-y)%2b -> (x+/-y) = n*2*b + b +/- c
Where n is integer.  This will force patterns to repeat every 2b steps in x and y.
Initial pattern n=0: (x +/- y) = b +/- c -> y = +/- x + b +/- c
In the x positive and y positive plane only, these correspond to lines of positive and
negative slope, set at intercept b, offset by c on either side.

```

Program fails to meet final criterion - generating ASCII art of box and lines, so I'm submitting as non-competitive for information to help others complete the challenge. Note that to get Desmos to work when c = 0 or c=b, a small offset factor of 0.01 was introduced, as Desmos seems to have bounds of Mod(A,B) of (0,B) instead of \[0,B)

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


title: Let's divide a lattice

text:
# Question
Title: Let's divide a lattice
Let's say we have a **n × n** lattice; we can then divide the lattice into two sections by drawing a line through the lattice. Everything to one side of the line is in one set and everything else in another.

How many ways can we divide the lattice in the manner?

For example lets take a **2 × 2** lattice:

```
. .
. .

```

We can make 2 partitions dividing the lattice in half like so:

```
× ×    × o
o o    × o

```

We can also partition off each of the corners:

```
× o    o ×    o o    o o
o o    o o    × o    o ×

```

Lastly we can put all of the points in one partition by missing the lattice entirely:

```
× ×
× ×

```

This makes for a total of 7 partitions. Note that the following partition is *not* valid because it cannot be made with a single straight line.

```
× o
o ×

```

Here is a **3 × 3** lattice

```
. . .
. . .
. . .

```

There are 4 purely horizontal or vertical partitions

```
× × ×    × × ×    × o o    × × o
× × ×    o o o    × o o    × × o
o o o    o o o    × o o    × × o

```

There are 4 corner partitions

```
× o o    o o ×    o o o    o o o
o o o    o o o    o o o    o o o
o o o    o o o    o o ×    × o o

```

There are 4 larger corner partitions

```
× × o    o × ×    o o o    o o o
× o o    o o ×    o o ×    × o o
o o o    o o o    o × ×    × × o

```

There are 8 partitions of partial corners

```
× × o    o × ×    o o ×    o o o    o o o    o o o    o o o    × o o
o o o    o o o    o o ×    o o ×    o o o    o o o    × o o    × o o
o o o    o o o    o o o    o o ×    o × ×    × × o    × o o    o o o

```

There are 8 knights move partitions

```
× × o    o × ×    × × ×    o o o    o o ×    × o o    o o o    × × ×
× o o    o o ×    o o ×    o o ×    o o ×    × o o    × o o    × o o
× o o    o o ×    o o o    × × ×    o × ×    × × o    × × ×    o o o

```

And there is one whole partition

```
× × ×
× × ×
× × ×

```

That makes for 29 partitions in total.

## Task

Given a number **n** as input, output the number of partitions that can be made in this fashion of an **n × n** lattice.

This is a question so answers will be scored in bytes, with less bytes being better.

## Test Cases

Here are the first 34 courtesy of the OEIS:

```
1, 7, 29, 87, 201, 419, 749, 1283, 2041, 3107, 4493, 6395, 8745, 11823, 15557, 20075, 25457, 32087, 39725, 48935, 59457, 71555, 85253, 101251, 119041, 139351, 161933, 187255, 215137, 246691, 280917, 319347, 361329, 407303

```

OEIS A114043

# Answer
> 2 votes
## JavaScript (ES6), ~~113~~ 111 bytes

*Saved 2 bytes thanks to guest44851*

0-indexed.

```
n=>[...Array(n)].map((_,i,a)=>a.map((_,j)=>x+=(g=(a,b)=>b?g(b,a%b):a<2&&(n-i-1)*(n-j))(i+1,++j)),x=n*++n)|x+x+1

```

Based on the formula mentioned on OEIS:

> Let V(m,n) = Sum\_{i=1..m, j=1..n, gcd(i,j)=1} (m+1-i)(n+1-j)
> a(n+1) = 2(n2 \+ n + V(n,n)) + 1

### Demo

```
let f =

n=>[...Array(n)].map((_,i,a)=>a.map((_,j)=>x+=(g=(a,b)=>b?g(b,a%b):a<2&&(n-i-1)*(n-j))(i+1,++j)),x=n*++n)|x+x+1

for(n = 0; n < 50; n++) {
  console.log('f(' + n + ') = ' + f(n));
}
```

# Answer
> 1 votes
# Mathematica, 59 bytes

```
2Sum[(#-i)(#-j)Boole[i~GCD~j<2],{i,#-1},{j,#-1}]+2#^2-2#+1&

```

courtesy of the OEIS (just like the question)

-1 byte from @ovs

Try it online!

# Answer
> 1 votes
# Python 2, 116 bytes

```
lambda n:2*(~-n*n+sum((n-i)*(n-j)*g(i,j)for i in range(1,n)for j in range(1,n)))+1
g=lambda x,y:y and g(y,x%y)or x<2

```

Try it online!

# Answer
> 1 votes
# Jelly, 14 bytes

```
ạþ`Fgþ`FỊS_²H‘

```

Try it online!

## Explanation

```
ạþ`Fgþ`FỊS_²H‘  Input: integer n
ạþ`             Form the table of absolute differences on [1, 2, ..., n]
   F            Flatten
    gþ`         Form a GCD table on that
       F        Flatten
        Ị       Test if the absolute value of each is <= 1
         S      Sum (Count the number of true's)
          _     Subtract
           ²    Square of n
            H   Halve
             ‘  Increment

```

# Answer
> 0 votes
# Python 2, 90 bytes

```
lambda n:4*n*n-6*n+3+4*sum((n-i)*(n-k/i)for i in range(n)for k in range(i*i)if k/i*k%i==1)

```

---
Tags: code-golf, sequence, set-partitions
---


title: Ninjas in a Chat Log

text:
# Question
Title: Ninjas in a Chat Log
*Thanks to HyperNeutrino for making more test cases*

Often in chat, someone will ask a question, and multiple people will answer it at the same time. Usually, the person who was beaten to the gun will say "ninja'd", creating even more unnecessary chat.

Given a chat log similar to the following:

```
Community: Hi
Test: Hi
Rando: What is 4 times 4?
Test: @Rando 16
Community: @Rando 16
Community: ninja'd

```

You are looking for the number of extraneous lines, which in the above exchange is 2. Two users both replied to another user with the same text, although he only wanted one answer, and then the second user said "ninja'd".

# Extraneous Messages

Note that for the following statement, a message is only the content left of the `:<space>`. However, if an extraneous message is removed, the `<username>:<space>` is also removed.

Your only task is finding extraneous messages in the input, and counting them. The first type of extraneous message is a message **starting with `@`** that is basically (spaces and case differences are ignored) the same as the message before it. The second type of extraneous message is a message reading exactly `ninja'd` (case insensitive) immediately after an extraneous message of the first type **by the same user** (there will never be users with the same name in different cases, and the same user will always be in the same case).

# Input

Your input is the chat log, including the user's names, followed by a colon and a space, followed by their message. You may take the input as a newline-separated string, a list of strings, or another appropriate input format.

# Output

Your output is the number of extraneous messages.

# Test Cases

```
Community: Hi
Test: Hi
Rando: What is 4 times 4?
Test: @Rando 16
Community: @Rando 16
Community: NINJA'D

2

```

```
A: how is everyone doing today
B: good
C: good
C: this doesn't work: `print5`
A: @C add a space
B: @C add aSpace
B: ninja'd
C: ninja'd

2

```

```
A: test
B: @A hi
C: @Ahi
C: ninja'd

2

```

```
A: test
B: @A hi
B: @A hi
B: ninja'd

2

```

```
A:
B: @
B: @
B: ninja'd
B: ninja'd

2

```

```
A: ninja'd
B: ninja'd
C: @B ninja'd
B: @B ninja'd
B: ninja'd
C: ninja'd
C: ninja'd

2

```

```
Test: test
Testie: @Test TESTIE
Test: @Testie TESTIE
Test: ninja'd
Testie: TESTIE
Test: TESTIE

0

```

```
A: @B hi
C: @B hi
C: ninja'd
B: @C no
A: @CNO
A: ninja'd

4

```

# Answer
> 3 votes
# Retina, 50 bytes

```
T`l`L

(:@.*)¶(.+)\1
b$2a
b(.*)a¶\1:NINJA'D
aa
a

```

Try it online!

# Answer
> 2 votes
# Python 2, 237 bytes

```
l=lambda s:s[1].lower().replace(' ','')
m=[x.split(': ')for x in input()]
i=[0]
for j in range(1,len(m)):i+=[[m[j][1].lower()=="ninja'd"and i[-1]>1and m[j-1][0]==m[j][0],2][l(m[j-1])==l(m[j])and'@'==m[j][1][0]]]
c=i.count
print c(1)+c(2)

```

Try it online!

-19 bytes thanks to Zacharý

# Answer
> 1 votes
# Python 3, 122 bytes

```
lambda s:sub(r"b(.*)a\n\1:NINJA'D",'aa',sub(r'.+(:@.*)\n(.+)\1',r'b\2a',sub(' ','',s.upper()))).count('a')
from re import*

```

Try it online!

Port of my Retina answer

---
Tags: code-golf, string, text-processing
---


title: Create a shifter

text:
# Question
Title: Create a shifter
To "shift" over a number `n` places, do the following:

* Remove the last `n` digits
* Add `n` copies of the first digit to the beginning of the number

For example, to shift the number `31415` three places, take out the last three digits to get `31`, and then add three more copies of the first digit, `3`, to the end, giving `33331`.

If the number is negative, digits should be taken from the left instead, and the first digit should be "filled in" from the right. For example, the string `31415` shifted over -3 places gives `15555`.

If the number is 0, no change should be made.

If the shift is more than the length of the program, then digits that were filled in might start to be removed. This means that if the number given is more than the length of the string, no further changes will be made after the entire string becomes a single digit.

## The challenge

Given two numbers, `n` and `s`, return `n` shifted over `s` places.

## Test cases

```
   n,  s -> result
7243,  1 -> 7724
 452, -1 -> 522
  12,  1 -> 11
 153,  4 -> 111

```

This is , so the shortest valid submission (measured in bytes) wins.

# Answer
> 2 votes
# APL (Dyalog), 32 bytes

Anonymous function which takes the sift as left argument and the number (as a string) as right argument.

```
{a←|⍺⋄(≢⍵)↑(a-⍺)↓(a⍴⊃⍵),⍵,a⍴⊃⌽⍵}

```

Try it online!

`{` anonymous function where  and  are left and right arguments

`|⍺` the absolute value of the shift

`a←` store in *a*

then

`⌽⍵` reverse the number

pick the first (i.e. last) digit

`a⍴`**r**eshape it to length *a*

`⍵,` prepend the number

`(``),` prepend the following:

`⊃⍵` the first digit

`a⍴`**r**eshape it to length *a*

`(``)↓` drop the following number of characters:

`a-⍺`*a* minus the shift

`(``)↑` take the following number of characters:

`≢⍵` the length of the original number

# Answer
> 2 votes
# Python 2, 50 bytes

```
lambda n,s:(n[0]*s+n+n[-1]*-s)[-s*(s<0):][:len(n)]

```

Try it online!

# Answer
> 2 votes
# MATL, 12 bytes

```
tn:i-yn1&Xl)

```

Inputs are: number to be shifted as a string; amount of shifting as a number.

Try it online! Or verify all test cases.

Consisder inputs `'452` and `'-1'`.

```
t     % Implicitly input string. Duplicate
      % STACK: '452', '452'
n     % Number of elements
      % STACK: '452', 3
:     % Range
      % STACK: '452', [1 2 3]
i     % Input number
      % STACK: '452', [1 2 3], -1
-     % Subtract, element-wise
      % STACK: '452', [2 3 4]
y     % Duplicate from below
      % STACK: '452', [2 3 4], '452'
n     % Number of elements
      % STACK: '452', [2 3 4], 3
1     % Push 1
      % STACK: '452', [2 3 4], 3, 1
&Xl   % Clamp, with three inputs. Applies min function, then max
      % STACK: '452', [2 3 3]
)     % Reference indexing. Implicitly display
      % STACK: '522'

```

# Answer
> 2 votes
## Haskell, 69 bytes

```
s#n|l<-[1..abs n]=take(length s)$drop(-2*n)$(s!!0<$l)++s++(last s<$l)

```

Takes the number as a string. Try it online!

How it works:

```
s#n                         -- s: input number as a string
                            -- n: shift amount

(s!!0<$l)++s++(last s<$l)   -- make a string:
                            -- n times the first digit, the whole number, n times the last digit
                            -- e.g. "567" 2 -> 5556777
drop(-2*n)                  -- drop the first (-2 * n) chars, i.e. 0 if n>0
take(length s)              -- take as may chars as there are in s

```

# Answer
> 1 votes
# J, 37 bytes

This was one of those situations in J where an explicit verb seemed like the right (the only?) choice, but I would love to know if there's a tacit rewrite of this:

```
4 :'(-x)(|.!.((x>0)&{({:,{.)":y))":y'

```

J's built in shift verb allows you to configure the "fill" character:

```
|.!.f  NB. f is the fill character

```

The logic to determine whether to use the first or last char as the fill character is straightforward

```
(x>0)&{ ({: , {.)

```

Try it online!

# Answer
> 1 votes
# , 23 bytes

```
(_&(]{.,],{:)~|)}.~_2*]

```

Input *n* and the output are strings containing the numbers.

Try it online!

## Explanation

```
(_&(]{.,],{:)~|)}.~_2*]  Input: 'integer n' as a string (LHS), integer s (RHS)
(              )         Extend 'n' by copying its head and tail 's' times
              |            Abs(s)
 _&(]       )~             Nest 'Abs(s)' times on 'n'
          {:                 Tail
        ],                   Append the tail to itself
     {.                      Head
       ,                     Prepend the head to the previous
                   _2*]  Multiply 's' by -2
                }.~      Drop abs(-2*s) from the head if 's' < 0 else from the tail

```

# Answer
> 1 votes
# Retina, 61 bytes

```
\d+¶
$*1¶
+`(?<!-).¶(.)(.*).
¶$1$1$2
-

+`.¶.(.*)(.)$
¶$1$2$2

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 16 bytes

```
0‹©iR}¹ÄF¨¬ì}®iR

```

Try it online!

**Explanation**

```
0‹                 # input_1 is negative
  ©                # store a copy in register
   iR}             # if true (input_1 is negative), reverse input_2
      ¹ÄF          # abs(input_1) times do
         ¨         # remove the last element
          ¬ì       # prepend the head
            }      # end loop
             ®iR   # if input_1 was negative, reverse result

```

# Answer
> 0 votes
# Python 2, 87 bytes

```
f=lambda n,s:s<0and f(n[::-1],-s)[::-1]or n[0]*min(len(n),s)+n[:[0,len(n)-s][len(n)>s]]

```

Try it online!

Takes the number as a string, and the shift as an integer. Returns a string.

I tried embedding the reversal inside the function rather than making a recursive call, but I couldn't seem to get it right.

# Answer
> 0 votes
# Python 3, 73 bytes

```
f=lambda s,i:(f(s+1,i[1:]+i[-1])if s<0else f(s-1,i[0]+i[:-1]))if s else i

```

Try it online!

# Answer
> 0 votes
# Haskell, 108 bytes

Oh well, this went worse than I thought..

```
n#s=print$show n&s
r=reverse
n&s|s<0=r$r n&abs s|(a:b,c)<-splitAt s n=take(length n)$(a<$[0..s])++b++c|1>0=n

```

Try it online!

### Ungolfed

```
n # s = print $ show n & s
n & s
  | s < 0                = reverse (reverse n & abs s)
  | (a:b,c)<-splitAt s n = take (length n) (replicate s a ++ b ++ c)
  | otherwise            = n

```

# Answer
> 0 votes
## Clojure, 121 bytes

```
#(let[T(if(pos? %2)reverse vec)](apply str(concat(repeat %2(first %))(T(drop(Math/abs %2)(T %)))(repeat(- %2)(last %)))))

```

Ouch, nasty to deal with negative inputs as well.

# Answer
> 0 votes
# Pyth, 28 bytes

```
AQ=Y<+*hJ?K<0H`G_`GHJlJ?KY_Y

```

Try it online or test some inputs

Explanation

```
AQ=Y<+*hJ?K<0H`G_`GHJlJ?KY_Y
AQ                           | Split Q into 2 parts, G and H.
        J?K<0H`G_`G          | If 0 < H, J = str(G). Else, J = reverse(str(G)). Return J
       h                     | Find 1st element
      *            H         | Repeat H times
     +              J        | Concatenate with J
    <                lJ      | Find 1st length(J) elements
  =Y                         | Assign to Y.
                       ?KY_Y | If K, implicit print Y. Else implicit print reverse(Y).

```

# Answer
> 0 votes
# 05AB1E, 33 bytes

```
ÄF¹0‹©i¨ë¦}}²®i¤ë¬}sg¹Ä‚Ws\×®i«ëì

```

Try it online!

---

05AB1E is not so hot with conditionals.

# Answer
> 0 votes
# JavaScript, 80 bytes

```
(n,s,k=n.length,p=s<=0)=>n.slice(p*-s,p?k:-s)[p?"padEnd":"padStart"](k--,n[p*k])

```

Takes input as a string representation of the number and a numerical "shift" amount. Returns a string.

## Test Snippet

```
let f=
(n,s,k=n.length,p=s<=0)=>n.slice(p*-s,p?k:-s)[p?"padEnd":"padStart"](k--,n[p*k])

I.value="31415";J.value="3";D.oninput()
```

```
<div id=D oninput="O.value=I.value.length&J.value.length?f(I.value,+J.value):''">n: <input id=I size=10> s: <input id=J size=2><br><input id=O disabled>
```

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


title: Make a Word Art

text:
# Question
Title: Make a Word Art
> *No, not that thing in powerpoint*

You will be given a string, and a 2D array of boolean values. The 2D array will represent a picture.

You will be creating art out of it.

Let me show you how.

# The steps to art

First, you create a square which fits the 2d array, with the string.

Like if the string is 'PPCG', and the picture is 4x3, the square should be like this.

```
PPCG
PCGP
CGPP
GPPC

```

Now in the square, erase all characters which the corresponding boolean is 0, or the corresponding boolean doesn't exist.

Let me show you. If the 2D array is

```
1001
0110
1001

```

And the square is same to the above (above this one), the result should be like:

```
P  G
 CG
C  P

```

Now output the result.

# Test data is not made yet. Will add ASAP.

# Rules

* General rules apply, including loopholes.

# Answer
# C#, 168 bytes

```
s=>a=>{var r=new string[a.Length];for(int i=0,j;i<a.Length;++i)for(j=0;j<a[i].Length;++j)r[i]+=a[i][j]>48?(s.Substring(i,s.Length-i)+s.Substring(0,i))[j]:' ';return r;}

```

Works for the example in the question, not entirely sure how it will hold up against future test cases as the spec isn't fully clear.

Try it online!
> 0 votes

# Answer
# Mathematica, 74 bytes

```
(z=Characters@#;Grid[Table[RotateLeft[z,i],{i,0,Length@#2-1}]#2/.0->" "])&

```

**input**

> \["PPCG", {{1, 0, 0, 1}, {0, 1, 1, 0}, {1, 0, 0, 1}}\]

works for test case.will update if things get "clearer"...
> 0 votes

# Answer
# Python 3, ~~95~~ ~~79~~ 74 bytes

*-2 bytes thanks to @Mr.Xcoder*

```
lambda s,b,e=enumerate:[[b*(2*s)[k+i]or' 'for k,b in e(v)]for i,v in e(b)]

```

Try it online!
> 0 votes

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


title: Mortarboard Challenge

text:
# Question
Title: Mortarboard Challenge
# Challenge

Given a user's ID, determine how many times they have hit the repcap.

# Specs

On a given day, let's a user has hit the repcap if they had reputation that wasn't gained due to the repcap. Essentially, on any given day, if the user's net reputation change as calculated without any cap was different from their actual observed reputation change, then they hit the repcap.

# Input/Output

Input will be a single integer, the user's ID.
Output will be a single integer, indicating the number of days for which they had reputation that was "lost".
I/O can be in any reasonable format.

# Test Cases

Feel free to add your own ID and stats here. The brackets indicate which user it is, but that isn't part of the output. Don't include it.

```
input -> output (username)
42649 -> 0 (HyperNeutrino)
41723 -> 7 (Fatalize)
46271 -> 0 (Riker) (This user has obtained 200 rep twice, but never over)

```

# Answer
# JS ES6, 360 bytes

```
f=(i,p=1,d=[])=>fetch(`https://api.stackexchange.com/2.2/users/${i}/reputation?site=codegolf&pagesize=100&page=${p}`).then(x=>x.json()).then(j=>(q=d.concat(j.items),j.has_more?f(i,p+1,q):(r=[],q.map(s=>(r[d=new Date(s.on_date*1000),i=d.getDate()+d.getMonth()*32+d.getYear()*365]?r[i]+=s.reputation_change:r[i]=s.reputation_change)),r.filter(x=>x>200).length)))

```

Call it like `f(user id)`. Returns a promise that resolves with the number of days that rep was lost.

Ungolfed:

```
f=(i,p=1,d=[])=>fetch(`https://api.stackexchange.com/2.2/users/${i}/reputation?site=codegolf&pagesize=100&page=${p}&key=kAc8QIHB*IqJDUFcjEF1KA((`).then(x=>x.json()).then(j=>{
    return (q=d.concat(j.items),
    j.has_more?
        f(i,p+1,q)

        :(r=[],
            q.map(s=>(r[d=new Date(s.on_date*1000),
                i=d.getDate()+d.getMonth()*32+d.getYear()*365]?
                    r[i]+=s.reputation_change

                    :r[i]=s.reputation_change)),
            r.filter(x=>x>200).length
        )
    )
});

```
> 1 votes

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