title: Count all binary relations

text:
# Question
Title: Count all binary relations
A binary relation on a set \\$X\\$ is simply a subset \\$S \subseteq X \times X\\$; in other words, a relation is a collection of pairs \\$(x,y)\\$ such that both \\$x\\$ and \\$y\\$ are in \\$X\\$. The number of different relations grows quickly with the size of the set: if \\$X\\$ contains \\$n\\$ elements, there are \\$2^{n^2}\\$ binary relations on \\$X\\$.

This challenge will have you computing the number of binary relations subject to certain constraints, listed here:

* A binary relation is called "reflexive" if \\$(x,x) \in S\\$ for all \\$x \in X\\$.
* A binary relation is called "irreflexive" if \\$(x,x) \not\in S\\$ for all \\$x \in X\\$.
* A binary relation is called "symmetric" if whenever \\$(x,y) \in S\\$, then \\$(y,x) \in S\\$.
* A binary relation is called "asymmetric" if whenever \\$(x,y) \in S\\$, then \\$(y,x) \not\in S\\$.
* A binary relation is called "transitive" if whenever \\$(x,y) \in S\\$ and \\$(y,z) \in S\\$ then \\$(x,z) \in S\\$.
* A binary relation is called "antitransitive" if whenever \\$(x,y) \in S\\$ and \\$(y,z) \in S\\$ then \\$(x,z) \not\in S\\$.

# Challenge

The goal of this challenge is to write a function that takes in a nonnegative integer \\$n\\$, and some subset of the six conditions above in any reasonable format\*, and returns the number of binary relations on the set \\$\\{1,2,\dots,n\\}\\$ satisfying all of the conditions in the aforementioned subset.

Brute-force strategies are okay, but your code should be able to handle all \\$n \leq 4\\$ on TIO.

# Test Data

```
n | conditions                         | number of binary relations
--+------------------------------------+-------------------------
0 | {reflexive, antitransitive}        | 1
3 | {reflexive, antitransitive}        | 0
3 | {}                                 | 512
3 | {antitransitive}                   | 39
4 | {antitransitive}                   | 921
4 | {reflexive, irreflexive}           | 0
4 | {symmetric, asymmetric}            | 1
4 | {transitive, antitransitive}       | 87
4 | {reflexive, symmetric, transitive} | 15
4 | {symmetric, transitive}            | 52
4 | {asymmetric, antitransitive}       | 317

```

# Example

For \\$n = 3\\$, there are \\$39\\$ antitransitive relations, as shown by the illustration below. (Strictly speaking, the illustration shows *unlabeled* relations.)

0. There is \\$1\\$ empty relation.
1. There are \\$6\\$ relations consisting of just one pair.
2. There are \\$3 + 3 + 6 + 3\\$ relations consisting of two pairs.
3. There are \\$6 + 6 + 2\\$ relations consisting of three pairs.
4. There are \\$3\\$ relations consisting of four pairs.

---

* For example, you could take the conditions as a list like `[False, False, True, False, False, True]`, with each position referring to the particular condition. As another example, you could take a set of strings like `{"transitive", "asymmetric"}`.

# Answer
> 11 votes
# APL (Dyalog Extended), <sup>~~99~~</sup> 93 bytes

```
r←0∊0 0⍉⊢
R←r~
s←⊢≢⍉
S←1∊⊢∧⍉
t←0∊⊢≥∨.∧⍨
T←1∊⊢∧∨.∧⍨
{×⍵:+/∧⌿~(⍺,'0'){(⍎⍺)⊣⍵}\⍵-⍛↑∘⊤¨,⍳⍵⍴2*⍵⋄1}

```

Try it online!

-5 bytes thanks to @ovs for spotting `R←r~`, and -1 by taking the boolean negation of the intermediate results.

Takes the condition as a string, using the abbreviation as follows:

```
r: reflexive
R: irreflexive
s: symmetric
S: asymmetric
t: transitive
T: antitransitive

```

For example, reflexive + symmetric + transitive is given as `'rst'` and "no condition" is given as `''`.

### How it works (before golfing)

```
⍝ Each of rRsStT takes an adjacency matrix and determines if the condition is met

⍝ reflexive: the diagonal is all ones
r←∧/0 0⍉⊢
⍝ irreflexive: the diagonal is all zeros
R←∧/0 0⍉~
⍝ symmetric: transpose is equal to self
s←⊢≡⍉
⍝ antisymmetric: each position in self and transpose cannot be both ones
S←~1∊⊢∧⍉
⍝ transitive: self includes the transitive square of self
t←~0∊⊢≥∨.∧⍨
⍝ antitransitive: each position in self and transitive square cannot be both ones
T←~1∊⊢∧∨.∧⍨

⍝ main function
{×⍵:+/∧⌿(⍺,'≡'){(⍎⍺)⍵}\⍵-⍛↑∘⊤¨,⍳⍵⍴2*⍵⋄1}  ⍝ ⍵: n, ⍺: conditions
{×⍵: ... ⋄1}  ⍝ Take 0 as a special case, always returning 1
,⍳⍵⍴2*⍵       ⍝ Generate all length-n vectors of 0..2^n-1
⍵-⍛↑∘⊤¨       ⍝ Convert them to n×n binary matrices
(⍺,'≡')       ⍝ Add a default function that always returns 1 to the list of conditions
{...}\        ⍝ Take outer product of conditions and matrices...
 (⍎⍺)⍵        ⍝ Eval the condition function and apply it to the matrix
+/∧⌿          ⍝ Count the matrices which satisfy all the conditions

```

# Answer
> 8 votes
# JavaScript (Node.js), 182 bytes

A slower but significantly shorter version suggested by @tsh.

Expects `(n)(m)`, where **n** is a BigInt and **m** is a list of constraints among:

```
IRREFLEXIVE = 0, REFLEXIVE = 1, ANTISYMMETRIC = 2,
SYMMETRIC = 3, ANTITRANSITIVE = 4, TRANSITIVE = 5

```

```
n=>m=>eval("g=(c,x=n)=>x?c(--x)&g(c,x):1;h=(x,y)=>!(k>>x+n*y&1n);for(t=0,k=1n<<n*n;k--;)t+=m.every(q=>g(x=>g(y=>g(z=>[h(x,x)^q,h(x,y)|h(y,x)^q%2,h(x,y)|h(y,z)|h(x,z)^q%2][q>>1]))))")

```

Try it online! (part 1)
Try it online! (part 2)

---

# JavaScript (Node.js), 215 bytes

Expects `(n)(m)`, where **n** is a BigInt and **m** is a bit-mask describing which constraints are enabled, using a combination of:

```
IRREFLEXIVE    = 1
REFLEXIVE      = 2
ANTISYMMETRIC  = 4
SYMMETRIC      = 8
ANTITRANSITIVE = 16
TRANSITIVE     = 32

```

```
n=>m=>{g=(c,x=n)=>x?c(--x)&g(c,x):1;h=(x,y)=>!(k>>x+n*y&1n);for(t=0,k=1n<<n*n;k--;)t+=![x=>h(x,x)^q,0,x=>g(y=>h(x,y)|h(y,x)^q),0,x=>g(y=>g(z=>h(x,y)|h(y,z)|h(x,z)^q)),0].some((c,j)=>m>>j&!g((q=j&1)?C:C=c));return t}

```

Try it online!

Notes:

* To get a much faster version, replace the first bitwise `&` with `&&`.
* Using BigInts is slower and slightly longer, but allows this code to work for any **n** in theory.

### Formatted and commented

```
n => m => {
  // helper function to test whether c(x) is true for all x in [0 .. n - 1]
  g = (c, x = n) => x ? c(--x) & g(c, x) : 1;

  // helper function to test if (x, y) is *not* in S
  h = (x, y) => !(k >> x + n * y & 1n);

  // we use k = 2 ** n² - 1 to k = 0 to describe all possible binary relations
  // (k is essentially a flatten binary matrix of size n x n)
  for(t = 0, k = 1n << n * n; k--;)
    // increment t if ...
    t +=
      // ... the following tests are all falsy
      ![
        // irreflexive (q = 0) / reflexive (q = 1)
        x => h(x, x) ^ q, 0,

        // antisymmetric (q = 0) / symmetric (q = 1)
        x => g(y => h(x, y) | h(y, x) ^ q), 0,

        // antitransitive (q = 0) / transitive (q = 1)
        x => g(y => g(z => h(x, y) | h(y, z) | h(x, z) ^ q)), 0
      ]
      .some((c, j) =>
        // return true if the constraint is set ...
        m >> j &
        // ... and the test fails
        !g((q = j & 1) ? C : C = c)
      );
  return t
}

```

# Answer
> 6 votes
# Python 3, 319 bytes

Expects to be called as `f(n, m)`, where m is a bitmask of which conditions are required, in the same order as the question.

```
r=lambda x:x and r(x[1:])+[x[:1]+a for a in r(x[1:])]or[[]]
f=lambda n,c:(lambda z:n==0 or sum(1for a in map(set,r([(x,y)for x in z for y in z]))if not(lambda g,h,i:(g<=a)+(a-g==a)*2+(h==a)*4+(a-h==a)*8+(i|a==a)*16+(a-i==a)*32)(set(zip(z,z)),{(q,b)for(b,q)in a},{(d,c)for(d,b)in a for(l,c)in a if l==b})&c^c))(range(n))

```

Try it online!

# Answer
> 4 votes
# Python 3.8 (pre-release), 188 bytes

```
lambda n,Q:sum(all([m[x*n+x]^q,(b:=m[x*n+y])+m[y*n+x]^q-1,b*m[y*n+z]<=m[x*n+z]^q%2][q//2]for q in Q for x,y,z in p(*3*[range(n)]))for m in p(*n*n*[[0,1]]))
from itertools import*;p=product

```

Try it online!

Function receives two arguments. The first one is the size of set \\$X\\$. The second one is a list describe properties all relations should fit. while use 0~5 for reflexive, irreflexive, symmetric, antisymmetric, transitive, antitransitive. For example, `f(4, [0, 2, 4])` find the number of relations on set with 4 elements which is reflexive, symmetric, and transitive.

```
for matrix in itertools.product([0,1], repeat=n*n) # all possible relations
for arguments in itertools.product(range(n), repeat=3) # all x, y, z combinations
for q in Q # all properties need to follow

```

---

# Python 3.8 (pre-release), 205 bytes

```
lambda n,Q:sum(all([x:=k%n,m[x*n+x]^q,y:=k//n%n,(b:=m[x*n+y])+m[y*n+x]^q-1,z:=k//n//n,b*m[y*n+z]<=m[x*n+z]^q%2][q|1]for q in Q for k in R(n**3))for m in[[i>>j&1for j in R(n*n)]for i in R(2**n**2)])
R=range

```

Try it online!

Here is another version without `import itertools`.

Save 2 bytes, thanks to caird coinheringaahing

# Answer
> 2 votes
# Charcoal, 121 bytes

```
ＩＬΦＥＸ²×θθ⎇θ⪪﹪÷ιＸ²…⁰×θθ²θυ∧∨§η⁰⬤ι§λμ∧∨§η¹¬⊙ι§λμ∧∨§η²⬤ι⬤λ⁼ν§§ιξμ∧∨§η³¬⊙ι⊙λ∧ν§§ιξμ∧∨§η⁴⬤ι⬤⌕Ａλ¹⬤⌕Ａ§ιν¹§λπ∨§η⁵¬⊙ι⊙λ∧ν⊙§ιξ∧π§λρ

```

Try it online! Link is to verbose version of code, which contains 17 consecutive `)`s, which might be a record for me in Charcoal. Takes input as `n` and an array of six integers where `0` means that the constraint is to be enforced. This is technically a 1-liner, but at 121 bytes it's too wide for me to format the explanation that way, so I'll pretend it isn't. Explanation:

```
ＩＬΦ

```

Print the length of matching values...

```
ＥＸ²×θθ⎇θ⪪﹪÷ιＸ²…⁰×θθ²θυ

```

... generated by iterating over all \\$ 2^{n^2} \\$ relations and turning them into an \\$ n \\$ by \\$ n \\$ binary matrix (except when \\$ n \\$ is 0, in which case just iterate the predefined empty array), where...

```
∧∨§η⁰⬤ι§λμ

```

... if the first constraint is to be enforced then check that the main diagonal only contains `1`s; and...

```
∧∨§η¹¬⊙ι§λμ

```

... if the second constraint is to be enforced then check that the main diagonal does not contain a `1`; and...

```
∧∨§η²⬤ι⬤λ⁼ν§§ιξμ

```

... if the third constraint is to be enforced then check that the matrix equals its transpose; and...

```
∧∨§η³¬⊙ι⊙λ∧ν§§ιξμ

```

... if the fourth constraint is to be enforced then check that the matrix does not contain a `1` where its transpose does; and...

```
∧∨§η⁴⬤ι⬤⌕Ａλ¹⬤⌕Ａ§ιν¹§λπ

```

... if the fifth constraint is to be enforced then check that wherever the matrix contains a `1` and the row of that `1`s column contains a `1` then the original row also contains a `1` in the second `1`'s column, and...

```
∨§η⁵¬⊙ι⊙λ∧ν⊙§ιξ∧π§λρ

```

... if the sixth constraint is to be enforced then check that that the matrix does not contain three `1`s where two are in the same row, two are in the same column and the other row and column index are the same.

---
Tags: code-golf, math, combinatorics, graph-theory
---


title: Create a scissors animation!

text:
# Question
Title: Create a scissors animation!
Try to create a simple ASCII art scissors animation!

# Challenge

All inputs will be integers -31 through 31.

The output will be an animation (To be outputted *somewhere*, as long as the previous frame is replaced. GIFs are allowed.), separated by (approximately) 1 quarter of a second.

If the input (`n`) is positive:

* The animation should start with `8<`, AKA open scissors.
* The next frame is `8=`. This shows the scissors "cutting".
* A dash (cut mark) is added behind the scissors, and the animation repeats until there are `n` dashes.

If the input is negative:

* The scissors start open and facing towards the left (Like this: `>8`), with `n` spaces in front of it.
* The scissors close and remain facing towards the left (`=8`).
* The scissors re-open, as space is removed, and a dash is added behind the scissors.

If the input is zero:

* Output just the scissors opening and closing, for 10 frames. They can be facing either direction, as long as it is consistent.

This is , so the shortest submission in bytes wins. (Even if your entry clearly won't win because of some sort of newfangled "golfing language", we'd still like to see it.)

Error messages are allowed, as long as the error message itself does not interfere with the animation.

# Example Input and Output Pairs:

(I separated the frames for clarity, but there should be approximately .25 seconds between each frame)

```
Input: 1
Output:
8<
8=
-8<

Input: 2
Output:
8<
8=
-8<
-8=
--8<

Input: 5
Output:
8<
8=
-8<
-8=
--8<
--8=
---8<
---8=
----8<
----8=
-----8<

Input: 0
Output:
8<
8=
8<
8=
8<
8=
8<
8=
8<
8=

Input: -2
Output:
  >8
  =8
 >8-
 =8-
>8--

Input: -3
Output:
   >8
   =8
  >8-
  =8-
 >8--
 =8--
>8---

```

Enjoy!

# Answer
# SOGL V0.12, 53 bytes

```
LA0≠?.θ«IA}a∫H.¡*»:B┌* 8+Ƨ<=F2%W+a»b-@*+.0<?↔±}1¼UU░P

```

Try it Here!
> 5 votes

# Answer
# MATL, ~~59~~ ~~58~~ 57 bytes

```
|EQG~10*+:"&FXx45@q2/kGg*XHY"8Vh61@oGO<Eq*+h4M?G|H-Z"hP]D

```

Try it at MATL Online! Or see an example run from the offline compiler:
> 5 votes

# Answer
# JavaScript (ES2017) + HTML, 165 + 10 bytes

**-16 bytes by @Shaggy**

```
n=>(g=i=>i<-~(n?2*m:9)&&setTimeout(g,250,i+1,s=8+"<>="[i%2?2:n<0|0],o=("-".repeat(i/2)+s).padEnd(m+2),e.innerHTML=(n?n<0?[...o].reverse().join``:o:s)))(0,m=n<0?-n:n)

```

```
<pre id=e>

```

Try it in the below snippet:

```
let globalTimeout;
const _setTimeout = setTimeout;
window.setTimeout = function(){ globalTimeout = _setTimeout.apply(this, arguments); }
// Code above is to support user input

f=
n=>(g=i=>i<-~(n?2*m:9)&&setTimeout(g,250,i+1,s=8+"<>="[i%2?2:n<0|0],o=("-".repeat(i/2)+s).padEnd(m+2),e.textContent=(n?n<0?[...o].reverse().join``:o:s)))(0,m=n<0?-n:n)

// Code below is to support user input
f(10)
const $inp = document.getElementById("inp");
inp.addEventListener("change", ()=>{
  clearTimeout(globalTimeout);
  f(+inp.value);
});
```

```
<input type="number" id="inp" min="-31" max="31" value="10" />

<pre id=e>
```
> 4 votes

# Answer
# Octave, ~~190~~ 186 bytes

```
k=32+~e((a=abs(n=(z=input(''))+~z*10))+1,1);for i=1:a
clc
k(i:i+1)=[56,61-(s=sign(n))];q=@(m)fprintf(rot90([m ''],s));q(k)
if(i-a)pause(.25)
clc
k(i+1)+=s;q(k)
pause(.25);k(i)=45;end
end

```

Try it online! (note: `clc` does not work in TIO, so it's just all the animation frames outputted sequentially). Thanks for @LuisMendo for making me aware of the function `e(...)` in Octave, which is equal to `exp(1)*ones(...)`.

It turns out that inline assignments return only the changed array entries, not the entire array. This means that constructions like `q(k(i+1)+=s)` are not possible, so the program is almost like MATLAB. In fact, the MATLAB entry is only slightly longer,

# MATLAB, ~~198~~ 195 bytes

```
n=input('');n=n+~n*10;a=abs(n);s=sign(n);k=zeros(a+1,1);q=@(k)fprintf(rot90([k ''],s));for i=1:a
k(i:i+1)=[56 61-s];clc
q(k)
if(i-a)pause(.25);
k(i+1)=k(i+1)+s;clc
q(k)
pause(.25)
k(i)=45;end
end

```
> 2 votes

# Answer
# TI-BASIC, 173 bytes

```
:"-
:For(X,1,5
:Ans+Ans
:End
:For(X,1,32
:" "+Ans+" →Str1
:End
:ClrHome
:Input N
:N<0→X
:For(A,not(N),abs(N+5not(N
:For(B,4-3X,6-3X-(A=abs(N)),2
:33X-Anot(not(N
:Output(1,16,sub(Str1,33X+32,abs(Ans-1)-NX-31X)+sub(">8=8<8=",B,2)+sub(Str1,Ans+32,1
:rand(11
:End
:End

```

Having the 0 input terminate in a different frame from the others was a very interesting obstacle!

Since TI-BASIC doesn't like empty strings, this maintains at least one dummy character to the left of the scissors, the first of which is constantly a space; to hopefully avoid counting this as part of the *n* spaces for negative inputs, this program begins printing from the rightmost column of the first row, then wraps the remainder of the string downward in order to begin the actual field of animation there, fresh off the first column.

Some notes for an exotic device: TI-BASIC code size is measured in tokens, not characters. For consistent cross-calculator comparisons, we usually ignore byte counts dealing with header lengths (e.g., we subtract 8 from PROGRAM:SCISSORS). Additionally, for routines which are fully well-behaved on the home screen (those lacking in control structures, for the most part), we further eliminate the size of an empty program to "save" on 9 bytes as well. This program in particular is not typable on the home screen, so that liberty won't be taken.
> 2 votes

# Answer
# PowerShell, 281 bytes

```
$n=$args[0];$o="8<";$c="8=";function x{sleep .25};if($n-le0){$n=[math]::abs($n);$o=">8";$c="=8";$p=' '*$n;$p+$o;$x;$p+$c;1..$n|%{$p=$p-replace"\s$","";$p+$o+('-'*$_);if($_-eq$n){break};$x;$p+$c+('-'*$_)};$x}else{$o;x;$c;1..$n|%{
$y='-'*$_;$y+"8<";if($n-eq$_){break};$x;$y+"8=";$x}}

```

Try it online!
> 2 votes

# Answer
# Clean, 294 bytes

```
import StdEnv,System.Time,ArgEnv,System._Unsafe
Start#n=toInt(select(getCommandLine)1)
=[?k l\\k<-[1..]&l<-if(n==0)(flatten o$5)(init)[$(abs n+2)'\b'++if(n<0)(rjustify(abs n+2))reverse[c,'8': $i'-']\\i<-[0..abs n],c<-[if(n<0)'>''<','=']]]
?t#(Clock n)=accUnsafe clock
|n>t*250=id= ?t
$ =repeatn

```

Try it online!

Note that this doesn't work on TIO, the link is just for presentation purposes.

Your results may vary if you have a `CLOCK_PER_TICK` constant other than `1000`, the default for x86 Windows Clean.
> 1 votes

# Answer
# Python 2, 170 bytes

```
import time
n=input()
a=abs(n);s=a and n/a
for i in range([a-~a,10][a<1]):print'\n'*30+(a-i/2)*-s*' '+i/2*s*'-'+'>='[i%2]*(s<1)+'8'+'<='[i%2]*s+i/2*-s*'-';time.sleep(.25)

```

Try it online!
> 1 votes

# Answer
# Ruby, 169 bytes

```
->x{i="";o=?=;(x!=0&&x.abs*2+1||10).times{|l|o=o[?=]?x>0?"8<":">8":x>0?"8=":"=8";f=?\s*(x<0&&-x-l/2||0);system"cls";puts x>0?i+o:f+o+i;i+=?-if(l).odd?&&x!=0;sleep 0.25}}

```

Pretty much self explainatory when you dig into it, atleast in my opinion. Program has to be running on a computer with the cls command/alias.

Try it online! ( Had to overwrite the system() method, just for this script, due to the limitations mentioned above. )

I did try to use

```
puts `cls`, ...

```

But it just printed an invisible character, anyone know why?
> 1 votes

# Answer
# Stax, <sup>~~46~~</sup> 41 bytes

```
üîφL↑≥ª⌡↨ÄA ¡`╢Σ·TmÄ↕=≈─Xí♫αF²M☻8]▒2±(═[3

```

Run and debug it

`|,` was included in a recent release, which is great for this challenge!

Uses JS `requestAnimationFrame` for pausing between snips.

Each testcase happens continuously after the other, so if you want a more clear version, try this!.

-5 bytes from recursive. (`:R`)

## Explanation

`c|a^5?rFxs0?.<={n'-*'8+s+x|a^^(x0<{:R}M{|,}9*|:pF`

`c|a^5?` initial zero check:

`?` if the input is truthy

`|a^`  take abs(n) and increment

`5` otherwise push 5

`r` range 0..n-1

`F` for each value in the range,

`xs0?` **r:** if input is 0, then push 0, otherwise push loop iteration no.

`.<={...F`for each value in "\<=",

`n'_*` repeat "\_" r times

`'8+` add 8 to that

`s+` add current loop iteration to that

`x|a^^` take abs(input) and increment twice

`(` pad on right to that length

`x0<{...}M` if input is less than 0

`:R` reflect the string (`<``>`)

`{|,}9*` delay 9 frames

`|:` output a form feed (clear screen)

`p` print the string without newline
> 1 votes

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


title: How many weekdays?

text:
# Question
Title: How many weekdays?
This a simple question.

The start day is a Saturday and let the input be a non-negative number `x`.

The output should be the number of weekdays (Mon-Fri) in the next `x` days inclusive.

For example, if `x = 3` then the output should be 2. For `x` from 0 onwards the output should be:

```
0,0,1,2,3,4,5,5,5,6,7,8,9,10,10,10,11,...

```

—-—

Now I am regretting not having asked the question for a user specified day of the week instead of just Saturday. It’s too late to change the question now and a new question would probably be marked as a duplicate. If anyone wanted to add an answer for this extension, I would love to see it.

# Answer
# Python 2, 18 bytes

```
lambda x:x*6/7-x/7

```

Try it online!

Found by brute-forcing. `x*6/7` counts non-Sundays, and `-x/7` subtracts the number of Saturdays.

```
all          x       0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 ...

all - Sun  = x*6/7   0  0  1  2  3  4  5  6  6  7  8  9 10 11 12 12 13 ...
Sat        = x/7     0  0  0  0  0  0  0  1  1  1  1  1  1  1  2  2  2 ...
all - Sun - Sat      0  0  1  2  3  4  5  5  5  6  7  8  9 10 10 10 11 ...

```

Brute-forcing suggests that this is the unique arithmetical solution of this length or shorter, subject to some limitations like not using parens, using only single-digit constants, and not having too-large intermediate results.

---

**19 bytes**

```
lambda x:x-x/7+-x/7

```

Try it online!

Found by brute-forcing. But, it has a nice interpretation. `x` counts all `x` days. Then `-x/7` subtracts the number of Sundays in those `x` days, and `+-x/7` subtracts the number of Saturdays. Note that there's a difference in Python between subtracting `x/7` and adding `-x/7` aka `(-x)/7`, because floor-div is not symmetric around zero since it always round down.

```
all =   x        0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 ...
Sun =   x/7      0  0  0  0  0  0  0  1  1  1  1  1  1  1  2  2  2 ...
Sat = -(-x/7)    0  1  1  1  1  1  1  1  2  2  2  2  2  2  2  3  3 ...

all - Sun - Sat  0  0  1  2  3  4  5  5  5  6  7  8  9 10 10 10 11 ...

```

---

**20 bytes**

```
lambda x:x*5/7+x%7/4

```

Try it online!

I found this by hand, noting that `f(x)` increases asymptotically with slope `5/7` and seeing that the difference to `x*5/7` (with floor-division) has a nice period-7 form.
> 16 votes

# Answer
# APL (Dyalog Unicode), 7 bytes

```
+/2≤7|⍳

```

Try it online!

1-based range is a big win here.

### How it works

```
+/2≤7|⍳
      ⍳  ⍝ 1-based range
    7|   ⍝ modulo 7; 1 2 3 4 5 6 0 ...
  2≤     ⍝ is at least 2; 0 1 1 1 1 1 0 ...
+/       ⍝ sum the booleans

```

---

For the bonus question (let the user provide the day of the week to start):

# APL (Dyalog Unicode), 11 bytes

```
+/⎕⍴⎕⌽7↑5⍴1

```

Try it online!

We don't need any fancy arithmetic. Just create a bit vector, rotate it to match the requested day of week to start with, cycle it and count ones (i.e. sum).

Accepts `Sun, Mon, ..., Sat` as the number `0, 1, ..., 6` as the first input, and the number of days as the second (both from stdin). (It actually works for any integers (for the first input) and gives the result as if it was modulo 7.)

### How it works

```
+/⎕⍴⎕⌽7↑5⍴1
      7↑5⍴1  ⍝ 1 repeated 5 times and then overtaken to length 7
             ⍝ i.e. 1 1 1 1 1 0 0
    ⎕⌽  ⍝ Take the starting weekday and rotate ^ that many units to the left
  ⎕⍴    ⍝ Take the number of days and cycle ^ to that length
+/      ⍝ Sum

```
> 8 votes

# Answer
# 05AB1E, ~~8~~ 6 bytes

```
Ý7%1›O

```

Try it online!

Very similar to the APL answer

## Explained

```
Ý    | Generate a list between 0 and input
7%   | Mod each number by 7
1›   | Determine if each number is greater than 1
O    | Summate the list and output it

```
> 8 votes

# Answer
# JavaScript (ES6), 16 bytes

```
n=>n*20/7+n%7>>2

```

Try it online!

### How?

The expression \\$\lfloor 5n/7\rfloor\\$ gives the correct answer when \\$n\bmod 7\\$ is less than or equal to \\$3\\$ but is off by \\$1\\$ otherwise.

```
 n           | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
-------------+---+---+---+---+---+---+---+---+---+---+----+----+----+----+----+----+----
 floor(5n/7) | 0 | 0 | 1 | 2 | 2 | 3 | 4 | 5 | 5 | 6 |  7 |  7 |  8 |  9 | 10 | 10 | 11
 expected    | 0 | 0 | 1 | 2 | 3 | 4 | 5 | 5 | 5 | 6 |  7 |  8 |  9 | 10 | 10 | 10 | 11
 difference  | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 |  0 |  1 |  1 |  1 |  0 |  0 |  0
 n mod 7     | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 0 | 1 | 2 |  3 |  4 |  5 |  6 |  0 |  1 |  2

```

This can be adjusted with:

$$f(n)= \left\lfloor\frac{5n}{7}\right\rfloor+\left\lfloor\frac{n\bmod 7}{4}\right\rfloor$$

which may also be expressed as:

$$f(n)= \left\lfloor\frac{20n/7+(n\bmod 7)}{4}\right\rfloor$$

---

# JavaScript (Node.js), 15 bytes

In order to use @xnor's formula without adding explicit floor operations, we have to work with BigInts. So this version expects a BigInt as input.

```
n=>n*6n/7n-n/7n

```

Try it online!
> 4 votes

# Answer
# Japt, 7 bytes

Port of Bubbler's APL solution so be sure to `+1` them, too.

```
õu7 x¨2

```

Try it \- Includes all test cases
> 3 votes

# Answer
# bc, 29 bytes

```
define f(n){return n*6/7-n/7}

```

Try it online!
> 3 votes

# Answer
# Jelly, 6 bytes

```
R%7>1S

```

Try it online!

Interestingly equal-length in all regards to Lyxal's 05AB1E answer, so I've copy-pasted the explanation, swapping out the commands.

```
R    | Generate a list between 0 and input
%7   | Mod each number by 7
>1   | Determine if each number is greater than 1
S    | Summate the list and output it

```
> 2 votes

# Answer
# C (gcc), 18 bytes

```
f(n){n=n*6/7-n/7;}

```

Try it online!

Port of xnor's formula from his Python 2 answer.
> 2 votes

# Answer
# Java, 12 bytes

```
x->x*6/7-x/7

```
> 2 votes

# Answer
# perl -Minteger -lp, 14 bytes

```
$_=$_*6/7-$_/7

```

Try it online!

Uses the same algorithm as the Python 2 solution from @xnor. The `-Minteger` switch makes perl use integer division.
> 2 votes

# Answer
# x86-16 machine code, 16 bytes

```
33 DB       XOR  BX, BX         ; clear BX sum
        MLOOP:
E3 0B       JCXZ DONE           ; handle x = 0
8A C1       MOV  AL, CL         ; loop counter to AL
D4 07       AAM  7              ; AL = AL mod 7
3C 01       CMP  AL, 1          ; AL <= 1 ?
7E 01       JLE  IS_WEEKEND     ; if so, is a weekend
43          INC  BX             ; otherwise increment count
        IS_WEEKEND:
E2 F3       LOOP MLOOP          ; loop until 0
        DONE:
C3          RET                 ; return to caller

```

Callable function, input in `CL` (unsigned byte) output to `BX`.

Or **22 bytes** to operate on 16 bit unsigned WORD in `CX`:

```
33 DB       XOR  BX, BX         ; clear BX sum
        MLOOP:
E3 11       JCXZ DONE           ; handle x = 0
8B C1       MOV  AX, CX
33 D2       XOR  DX, DX         ; clear DX (high word of quotient)
BF 0007     MOV  DI, 7          ; set up WORD divisor
F7 F7       DIV  DI             ; DX = DX:AX mod DI
80 FA 01    CMP  DL, 1          ; DL <= 1 ?
7E 01       JLE  IS_WEEKEND     ; if so, is a weekend
43          INC  BX             ; otherwise increment count
        IS_WEEKEND:
E2 ED       LOOP MLOOP
        DONE:
C3          RET                 ; return to caller

```
> 2 votes

# Answer
# Julia, 143 Bytes

```
function weekdays(days)
    r = mod(days, 7)
    if r <= 2 r=0
    else r -= 2
    end
    wd::Int64 = floor(days/7)
    return(5 * wd + r)
end

```

Try it online!

To use a custom start date, I add an offset argument, and `days += offset` at the start of the function
> 2 votes

# Answer
# Retina 0.8.2, 22 bytes

```
.+
$*
.(.{0,5}).?
$1
.

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
.(.{0,5}).?

```

For each week, match Sunday, then up to five weekdays, then optionally match Saturday.

```
$1

```

Keep just the weekdays.

```
.

```

Count the resulting weekdays.
> 1 votes

# Answer
# Charcoal, 10 bytes

```
ＩΣ…⪫00×⁵1Ｎ

```

Try it online! Link is to verbose version of code. This is actually 3 bytes shorter than trying to calculate the result arithmetically. Explanation:

```
        1   Literal string `1`
      ×⁵    Repeated 5 times i.e. `11111`
    00      Literal string `00`
   ⪫        Join its characters giving `0111110`
  …      Ｎ  Cyclically extend to the input number of days
 Σ          Sum the digits
Ｉ           Cast to string
            Implicitly print

```
> 1 votes

# Answer
# Pyth, 8 bytes

```
lf<1%T7S

```

Try it online!

Port of Bubbler's APL solution.

## Explanation

```
lf<1%T7S
l         : length of
 f        : filter on
       S  : 1-based range to input
  <1%T7   : where mod 7 is greater than 1

```
> 1 votes

# Answer
# AWK, 29 bytes

```
{print int($0*6/7)-int($0/7)}

```

Try it online!

Port of @xnor's Python 2 answer.
> 1 votes

# Answer
# Befunge-93, 12 bytes

```
&:6*7/\7/-.@

```

Try it online!

Another port of xnor's algorithm.
> 1 votes

# Answer
# Pyth, 7 bytes

```
sm<1%d7

```

Try it online!

Port of Lyxal's 05AB1E answer.

```
sm<1%d7
 m        For each number from 0-input:
    %d7     Mod 7
  <1        Greater than 1
s         Take the sum, implicit print

```
> 1 votes

# Answer
# Io, 44 bytes

It seems like ranging is too costly here.

```
f :=method(x,if(x>0,if(x%7>1,1,0)+f(x-1),0))

```

Try it online!

# Io, 46 bytes

```
method(x,Range 0 to(x)map(i,if(i%7>1,1,0))sum)

```

Try it online!
> 1 votes

# Answer
# brainfuck, 142 bytes

(Due to number-wrapping problems) The maximum supported input is 255.

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

```

Try it online!

If you are not sure whether this output is correct, try this link.

## Explanation

```
>,

```

Read input

```
[

```

While the input is nonzero:

```
[>+>+<<-]>[-<+>]

```

`>x 0 0` -\> `x 0 >x`

```
<->>>+++++++<[>->+<[>]>[<+>-]<<[<]>-]>[-]

```

Modulo by 7

```
>>+<[<<<+>>>>[-<<<<[-]>+>>>]<<<<[->>+<<]>[->>>+<<<]>>>-<-]>[-]<<

```

Check if this number is greater than 1

```
[-<<<<+>>>>]<<<

```

Add it to the accumulator (at the first item of the tape)

```
]

```

End while

```
<.

```

Move to the accumulator, print the value.
> 1 votes

# Answer
# Keg, 10 bytes

```
0&1ɧ⑷7%1>⑼

```

Try it online!

Total not a port of ~~Lyxal's~~ my 05AB1E answer... (spoiler, it is). ;P

## Explained

```
0&1ɧ⑷7%1>⑼
0&              # Store 0 in the register, as this will be used to keep track of the number of weekdays
  1ɧ            # Create a range between 1 and the implicit input
    ⑷           # Map the following to each item in the stack:
      7%1>⑼     # Increment the register by whether or not ((item % 7) > 1)

```
> 0 votes

# Answer
# Vyxal, `s`, 5 bytes

```
ʀ7%1>

```

Try it Online!

Another port of my 05AB1E answer
> 0 votes

# Answer
# x86-16 machine code, ~~18~~ 16 bytes (No Loop):

Bytecode: `"\xD4\x07\x88\xC1\xC1\xE8\x08\x6B\xC0\x05\x49\x78\x02\x01\xC8\xC3"`

```
0:  d4 07                   aam    0x7          ; eax contains n, with aam 0x7 -> al = n % 7 and ah = n / 7
2:  88 c1                   mov    cl,al        ; keep result of n%7 in ecx
4:  c1 e8 08                shr    ax,0x8       ; by shifting 8 times ax, ax=al=n/7;
7:  6b c0 05                imul   ax,ax,0x5    ; we multiply by 5
a:  49                      dec    ecx          ; ecx = ecx - 1 -> give 65535 if n was power of 7
b:  78 02                   js     11 <end>     ; if it happened we don't care about the remainder so we can just return n/7*5, the Signed Flag will be set so we can jump 2 bytes forward.
d:  01 c8                   add    eax,ecx      ; if not then we add (n%7)-1 to n/7*5
00000011 <end>:
f:  c3                      ret

```

~~obtained from assembling~~ thanks to `objdump -d -mi8086 dayofweek.s`

```
global dayofweek

bits 16

section .text

dayofweek:
    aam  7
    mov  cl, al
    shr  ax, 8
    imul ax,5
    dec  ecx
    js   end
    add  eax,ecx
end:
    ret

```

Test: main.c

```
int main() {
    for (short i = 0; i < 50; i++)
        printf("%2d %2d\n", dayofweek(i), (i*20/7+i%7)/4);
    return 0;
}

```

output:

```
0  0
0  0
1  1
2  2
3  3
...
33 33
34 34
35 35
35 35

```

~~It is not as short as @640KB (16 bytes) but~~ I believe it is still an interesting answer as it provides a better performance (no loop)

edit: Thanks to Peter -2 bits

NB (Peter): Do note that aam only divides AL, not AX, so you might as well declare the arg in C as **uint8\_t**, as well as specifying the gcc -mregparm=3 calling convention to put it in the reg you want.
> 0 votes

# Answer
# PowerShell, 42 bytes

```
function x($y){[math]::floor($y*6/7-$y/7)}

```

Try it online!

Fork of Python 2 answer
> 0 votes

---
Tags: code-golf
---


title: Making octogonal words

text:
# Question
Title: Making octogonal words
Last Thursday user @SpookyGengar delighted us with his/her first challenge about Making Squared Words. What if we double the number of sides?

### The challenge

Take a string as input in any reasonable format you need (`string`, `char` array...) and output an octogonal representation of the input (also in any reasonable format: `string`, list of `string`s, `char` matrix...) as in the next examples:

```
Input: golf
Output:

   golf
  o    l
 l      o
f        g
l        o
o        l
g        f
 o      l
  l    o
   flog

Input: HelloWorld
Output:

         HelloWorld
        e          l
       l            r
      l              o
     o                W
    W                  o
   o                    l
  r                      l
 l                        e
d                          H
l                          e
r                          l
o                          l
W                          o
o                          W
l                          o
l                          r
e                          l
H                          d
 e                        l
  l                      r
   l                    o
    o                  W
     W                o
      o              l
       r            l
        l          e
         dlroWolleH

Input: a
Output:

a

Input: ab
Output:

 ab
b  a
a  b
 ba

Input: code golf
Output:

        code golf
       o         l
      d           o
     e             g

   g                 e
  o                   d
 l                     o
f                       c
l                       o
o                       d
g                       e

e                       g
d                       o
o                       l
c                       f
 o                     l
  d                   o
   e                 g

     g             e
      o           d
       l         o
        flog edoc

```

### Notes

* Input will consist only of printable ASCII characters.
* Leading and/or trailing whitespaces and newlines allowed as long as the octogonal shape is maintained.
* This is , so may the sortest program/function for each language win!

# Answer
# Charcoal, 16 bytes (10 bytes noncompeting)

```
Ｆ⁸«✂θ⁰±¹↷¹Ａ⮌θθ»θ

```

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

```
Ｆ⁸«                 Repeat for each side of the octagon
   ✂θ⁰±    ¹        Print the input except the last character
        ↷¹          Rotate 45° clockwise
          Ａ⮌θθ      Reverse the input string
              »θ    Print the input again, to handle the length 1 case

```

Alternative length 1 fix, also 16 bytes: Verbose version.

```
ＰθＦ⁸«✂θ⁰±¹↷¹Ａ⮌θθ

```

A Charcoal bugfix means that the following 10-byte code now works: Verbose version.

```
Ｆ⁴«θ←↘⮌θ↖⟲

```
> 10 votes

# Answer
## JavaScript (ES6), 156 bytes

```
f=
s=>[...Array((l=s.length-1)*3+1)].map((_,i,a)=>a.map((_,j)=>s[i+j-l?l*5-i-j?i+l*2-j?j+l*2-i?i%(l*3)?j%(l*3)?-1:j?i-l:l+l-i:i?l+l-j:j-l:j:l-i:l*3-i:i]||` `))
```

```
<input oninput=o.textContent=this.value?f(this.value).map(function(a){return(a.join``)}).join`\n`:``><pre id=o>
```

Returns a character array.
> 5 votes

# Answer
# Mathematica, 247 bytes

```
(T=Table;k=Length[s=Characters@#];If[k==1,#,Column[Flatten@{#,T[""<>{s[[i]],T["  ",k/2-2+i],s[[-i]]},{i,2,k}],T[""<>{s[[-i]],T["  ",k+k/2-2],s[[i]]},{i,2,k}],T[""<>{s[[i]],T["  ",3k/2-1-i],s[[-i]]},{i,2,k-1}],StringReverse@#},Alignment->Center]])&

```
> 3 votes

# Answer
# Pyth, ~~79~~ ~~69~~ 65 bytes

```
j++K+]+*dJtlzzm+++*;-Jd@zd*;+ytdlz@z_hdSJjL*;t*3tlztC_B_zt__MC.tK

```

Test suite.
> 2 votes

# Answer
# Japt, ~~84~~ 79 bytes

*-5 bytes thanks to @ETHproductions.*

```

Ål
VoA{A?(UÅw +Uê)£Y¥V*2+AªY¥V-A?X:SÃ:Vç +U+Vç
Wf cU¬£V?(V*3 ç hUg~Y)+X:XÃcWz2

```

Leading newline is part of program. Takes a string as input and returns an array of strings.

Try it online! with the `-R` flag to join the resulting array with newlines.

Not my proudest work, but I got it down from ~100 bytes, at least. My idea here was to create the top and middle parts, then append the top portion, rotated 180°.
> 2 votes

# Answer
# Python 2, ~~220~~ 213 bytes

* Surprisingly longer than I had imagined.

```
a=input()
l=len(a)
r=range(l)
print'\n'.join(p.center(l*3-2)for p in[a]+(l>1)*([a[i]+(2*i-2+l)*' '+a[~i]for i in r[1:-1]]+[a[~i]+(l*3-4)*' '+a[i]for i in r]+[a[i]+(3*l-2*i-4)*' '+a[~i]for i in r[1:-1]]+[a[::-1]]))

```

Try it online!
> 1 votes

# Answer
# Mathematica, ~~168~~ ~~166~~ ~~147~~ 127 bytes

```
(n=Length@#;b=Array[" "&,3{n,n}-2];Do[l={{1,n+k-1},{k,n-k+1}};l=Join[l,Cross/@l];b=ReplacePart[b,Join[l,-l]->#[[k]]],{k,n}];b)&

```

This takes a list of one-character strings and outputs a matrix of one-character strings.

I saved 18 bytes by exploiting the symmetry to use `-l` and `Cross/@l` which takes something like a cross-product of each of the two single 2D vectors to take `{x,y}` to `{-y,x}`. Basically, the two initial directions are East (top edge) and Southwest (top right edge). Then we add in 90-degree counterclockwise rotations of them with `Cross`: North for left edge and Southeast for bottom left edge. Then we add in the other four pieces using `-l` to flip the four we covered.

You can test it out on the sandbox with something like:

```
(n=Length@#;b=Array[" "&,3{n,n}-2];Do[l={{1,n+k-1},{k,n-k+1}};l=Join[l,Cross/@l];b=ReplacePart[b,Join[l,-l]->#[[k]]],{k,n}];b)&[{"H","e","l","l","o"," ","G","o","l","f"}]//MatrixForm

```
> 1 votes

# Answer
# PHP 7.1, ~~230 156~~ 155 bytes

```
for($x=$e=strlen($s=$argn)-1;$n<9;$r[$y][$x+=$n+1&3?$n&4?-1:1:0]=$s[$i],$i+=($n+=!$i||$i==$e)&1?:-1)$r[$y+=$n-1&3?$n<6?:-1:0]=$r[$y]?:"";echo join("
",$r);

```

Run as pipe with `-nR` or try it online.

**breakdown**

```
for($x=$e=strlen($s=$argn)-1;   # import to $s, set $e to length-1, init $x
    $n<9;                       # loop through 8 repetitions of string
    $r[$y][
        $x+=$n+1&3?$n&4?-1:1:0      # 3. increment/decrement $x depending on $n
    ]=$s[$i],                       # 4. copy character to current position
    $i+=(
        $n+=!$i||$i==$e             # 5. if first or last character of string, increment $n
    )&1?:-1                         # 6. if odd repetition next, else previous character
)
    $r[
        $y+=$n-1&3?$n<6?:-1:0       # 1. increment/decrement $y depending on $n
    ]=$r[$y]?:"";                   # 2. if empty, init row to string
echo join("\n",$r);             # output

```
> 1 votes

# Answer
# Canvas, 14 bytes

```
４Ｈ┐⁸ｋ⁸±＼＋⁸Ｌ１╋↶

```

Try it here!
> 1 votes

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


title: Illustrate the Least Common Multiple

text:
# Question
Title: Illustrate the Least Common Multiple
Given two positive integers, \\$A\\$ and \\$B\\$, illustrate their least common multiple by outputting two lines of dashes (`-`) with length \\$\text{lcm}\\$\\$(A, B)\\$ after replacing every \\$A\\$th dash in the first line and every \\$B\\$th dash in the second line with vertical bars (`|`).

In this way, the end of each line will be the only place two `|`'s line up.

> For example, if \\$A = 6\\$ and \\$B = 4\\$, \\$\text{lcm}(6, 4) = 12\\$, so:
>
> ```
> two lines of 12 dashes:
> ------------
> ------------
>
> replace every 6th dash in the first line with a vertical bar:
> -----|-----|
> ------------
>
> replace every 4th dash in the second line with a vertical bar:
> -----|-----|
> ---|---|---|
>
> ```
>
> Thus the final output would be
>
> ```
> -----|-----|
> ---|---|---|
>
> ```

The order of the input numbers should correspond to the order of the lines.

**The shortest code in bytes wins.**

# Testcases

```
A B
line for A
line for B

1 1
|
|

1 2
||
-|

2 1
-|
||

2 2
-|
-|

6 4
-----|-----|
---|---|---|

4 6
---|---|---|
-----|-----|

2 3
-|-|-|
--|--|

3 2
--|--|
-|-|-|

3 6
--|--|
-----|

2 5
-|-|-|-|-|
----|----|

4 3
---|---|---|
--|--|--|--|

10 10
---------|
---------|

10 5
---------|
----|----|

10 6
---------|---------|---------|
-----|-----|-----|-----|-----|

24 8
-----------------------|
-------|-------|-------|

7 8
------|------|------|------|------|------|------|------|
-------|-------|-------|-------|-------|-------|-------|

6 8
-----|-----|-----|-----|
-------|-------|-------|

13 11
------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|
----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|

```

# Answer
# Python 3, 80 bytes

Saved 1 byte thanks to Halvard Hummel and 1 byte thanks to Jonathan Allan.

```
import math
def f(*l):
 for k in 0,1:print(l[~k]//math.gcd(*l)*(~-l[k]*"-"+"|"))

```

Test it online!

```
lambda*l:"\n".join(l[0]*l[1]//math.gcd(*l)//k*(~-k*"-"+"|")for k in l)
import math

```

Test it online! (82 bytes - initial answer)

This is the best I could do in Python 2 (81 bytes). It seems like I cannot comment on that answer, I'll just post this here instead:

```
from fractions import*
l=a,b=input()
for k in l:print a*b/gcd(*l)/k*(~-k*"-"+"|")

```

Test it online!

*First attempt here, probably sub-optimal!*
> 11 votes

# Answer
# Haskell, 57 bytes

```
x%y=unlines[["-|"!!(0^mod a b)|a<-[1..lcm x y]]|b<-[x,y]]

```

Try it online!
> 10 votes

# Answer
# Jelly, 12 bytes

```
Ṭ€ị⁾|-ṁ€æl/Y

```

Try it online!
> 7 votes

# Answer
# MATL, ~~16~~ 15 bytes

```
'-|'!i&Zm:G\go)

```

Input is a column vector with the two numbers. **Try it online!**

As a bonus, the input can contain *more than two numbers*. **Try it online!**

### Explanation

```
'-|'   % Push this string
!      % Transpose. This is needed because of input [1; 1]
i      % Input column vector of 2 (or N) numbers
&Zm    % LCM of the 2 (or N) numbers, say L
:      % Range
G      % Push input again
\      % Modulus, element-wise with broadcast. Gives a 2×L (or N×L) matrix
g      % Convert to logical: gives false for zeros, true for nonzeros
o      % Convert to double: gives 0 for false, 1 for true
)      % Index into string (modular, 1-based). Implicitly display

```
> 6 votes

# Answer
# , ~~109~~ 105 bytes

```
function(a,b){q=1:a*b
l=min(q[!q%%a])
x=rep("-",l*2)
x[c(seq(0,l,a),l+seq(0,l,b))]="|"
write(x,"",l,,"")}

```

Try it online!

Anonymous function. Computes `l=lcm(a,b)`, then generates a range from `0` to `l` by `a`, then from `l` to `2*l` by `b`, setting the indices to `|` and printing as a matrix with `l` columns.
> 5 votes

# Answer
# Python 2, 66 bytes

```
l=a,b=input()
while a%b:a+=l[0]
for x in l:print a/x*('-'*~-x+'|')

```

Try it online!
> 5 votes

# Answer
# Husk, 12 bytes

```
†?'-'|TUṪ`%N

```

Try it online!

Yeah, there is a lcm builtin in Husk. No, I don't need it.

Bonus: works with any number of input values

### Explanation

```
†?'-'|TUṪ`%N    input:[2,3]
        Ṫ`%N    table of all remainders of positive naturals divided by
                input numbers:
                             [[1,1],[0,2],[1,0],[0,1],[1,2],[0,0],[1,1],[0,2],...
       U        get all elements before the first repeated one:
                             [[1,1],[0,2],[1,0],[0,1],[1,2],[0,0]]
      T         transpose:
                             [[1,0,1,0,1,0],[1,2,0,1,2,0]]
†?'-'|          replace all truthy elements with '-' and all falsy elements
                with '|':
                             ["-|-|-|","--|--|"]
                implicit: since this is a full program, join the resulting array
                of strings with newlines, and print to stdout

```
> 5 votes

# Answer
# Mathematica, 63 bytes

```
(s=LCM@##;Print[""<>If[i~Mod~#<1,"|","-"]~Table~{i,s}]&/@{##})&

```

Try it online!

and another version which user202729 really, really, really wants to see posted

# Mathematica, 59 bytes

```
(s=LCM@##;Print[""<>If[#∣i,"|","-"]~Table~{i,s}]&/@{##})&

```

this one uses special character `\[Divides]`
> 4 votes

# Answer
# C, 72 bytes

```
i;f(x,y){for(i=1;i%y|i%x;)putchar(i++%x?45:124);puts("|");y>0&&f(y,-x);}

```
> 4 votes

# Answer
# Octave, ~~46~~ 38 bytes

*-8 bytes thanks to several suggestions by Luis Mendo*

```
@(a,b)'-|'.'(~mod(1:lcm(a,b),[a;b])+1)

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 13 bytes

```
ʒ<'-×'|«¹.¿∍,

```

Uses the **05AB1E** encoding. Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 69 bytes

```
f=(a,b,S,A=1)=>(A%a?'-':'|')+(A%a|A%b?f(a,b,S,A+1):S?'':`
`+f(b,a,1))

```

Recursively runs until `A` is divisible by both `a` and `b` – outputting a dash or pipe based on `a`'s divisibility by `A`.

The function then calls itself, swapping `a` and `b`.

The `S` variable prevents the function from calling itself infinitely.

**Test Cases:**

```
f=(a,b,S,A=1)=>(A%a?'-':'|')+(A%a|A%b?f(a,b,S,A+1):S?'':`
`+f(b,a,1))

console.log(f(1,1));
console.log(f(1,2));
console.log(f(2,1));
console.log(f(2,2));
console.log(f(6,4));
console.log(f(4,6));
console.log(f(2,3));
console.log(f(3,2));
console.log(f(10,10));
console.log(f(3, 6));
console.log(f(2, 5));
console.log(f(4, 3));
console.log(f(10, 10));
console.log(f(10, 5));
console.log(f(10, 6));
console.log(f(24, 8));
console.log(f(7, 8));
console.log(f(6, 8));
console.log(f(13, 11));
```

---

Previous answers:

# JavaScript (ES8), 91 bytes

```
f=(a,b,i=2,g=(c,d)=>d?g(d,c%d):c)=>i?'|'.padStart(a,'-').repeat(b/g(a,b))+`
`+f(b,a,i-1):''

```

Uses the algorithms:

```
lcm(a, b) = ab / gcd(a, b)
gcd(c, d) = d ? gcd(d, c%d) : c

```

Recursively calls itself just once to output the second line.

**Test Cases:**

```
f=(a,b,i=2,g=(c,d)=>d?g(d,c%d):c)=>i?'|'.padStart(a,'-').repeat(b/g(a,b))+`
`+f(b,a,i-1):''

console.log(f(1,1));
console.log(f(1,2));
console.log(f(2,1));
console.log(f(2,2));
console.log(f(6,4));
console.log(f(4,6));
console.log(f(2,3));
console.log(f(3,2));
console.log(f(10,10));
console.log(f(3, 6));
console.log(f(2, 5));
console.log(f(4, 3));
console.log(f(10, 10));
console.log(f(10, 5));
console.log(f(10, 6));
console.log(f(24, 8));
console.log(f(7, 8));
console.log(f(6, 8));
console.log(f(13, 11));
```

# JavaScript (ES6), 93 bytes

```
f=(a,b,i=2,g=(c,d)=>!d=>d?c:g(d,c%d):c)=>i?('-'.repeat(a-1)+'|').repeat(a*bb/g(a,b)/a)+`
`+f(b,a,i-1):''

```

Same algorithm as before, using `repeat` instead of `padStart`.
> 3 votes

# Answer
# APL (Dyalog), 22 bytes

Assumes `⎕IO←0`. Takes A,B as right argument. **Bonus:** handles input list of any length!

```
{'|-'[⌽×⍵∘.|⍳∧/⍵]}

```

Try it online!

`{``}` anonymous lambda where  represents the right argument

`'|-'[``]` index the string with:

`∧/` LCM across the input

first that many **ɩ**ntegers (0 through N-1)

`⍵∘.|` division remainder table with the input vertically and that horizontally

`×` signum

flip horizontally
> 3 votes

# Answer
# Scala, 98 bytes

```
print((a to a*b).find(l=>l%a+l%b==0).map(l=>("-"*(a-1)+"|")*(l/a)+"\n"+("-"*(b-1)+"|")*(l/b)).get)

```

Try it online
> 3 votes

# Answer
# Java 8, ~~125~~ ~~118~~ 117 bytes

```
a->b->{String A="\n",B=A,t="|";for(int i=1;!A.endsWith(t)|!B.endsWith(t);B+=i++%b<1?t:"-")A+=i%a<1?t:"-";return A+B;}

```

-7 bytes thanks to *@Nevay*.
-1 byte by starting with a trailing new-line (`A="",B="\n"` replaced with `A="\n",B=A`).

**Explanation:**

Try it here.

```
a->b->{             // Method with two integer parameters and String return-type
  String A="\n",    //  String top line (starting with a trailing new-line)
         B=A,       //  String bottom-line (starting with a new-line)
         t="|";     //  Temp String "|" which is used multiple times
  for(int i=1;      //  Index-integer, starting at 1
      !A.endsWith(t)|!B.endsWith(t);
                    //  Loop as long as both Strings aren't ending with "|"
      B+=           //    After every iteration: append `B` with:
         i++%b<1?   //     If `i` is divisible by `b`:
                    //     (and increase `i` by 1 in the process)
          t         //      `t` (holding "|")
         :          //     Else:
          "-")      //      A literal "-"
    A+=             //   Append `A` with:
       i%a<1?       //    If `i` is divisible by `a`
        t           //     `t` (holding "|")
       :            //    Else:
        "-";        //     A literal "-"
                    //  End of loop (implicit / single-line body)
  return A+B;       //  Return both lines, separated by the new-line `B` started with
}                   // End of method

```
> 3 votes

# Answer
# Java (OpenJDK 8), 103 bytes

```
a->b->{String l="",r="|\n";for(int m=0;(++m%a|m%b)>0;r+=m%b<1?'|':'-')l+=m%a<1?'|':'-';return l+r+'|';}

```

Try it online!

### 110 bytes, n input values

```
a->{String s="";for(int v:a){for(int i=1,z=1;z>(z=0);s+=i++%v<1?'|':'-')for(int k:a)z|=i%k;s+='\n';}return s;}

```

Try it online!
> 3 votes

# Answer
# Python 2, 96 88 bytes

**Edit:** Saved 4 bytes thanks to @Leaky Nun

**Edit:** Saved 4 bytes thanks to @Rod

```
lambda a,b:b/gcd(a,b)*("-"*~-a+"|")+"\n"+a/gcd(a,b)*("-"*~-b+"|")
from fractions import*

```

Try it online!
> 2 votes

# Answer
# Haskell, ~~66~~ 60 bytes

```
a#b=do x<-[a,b];lcm a b`take`cycle(([2..x]>>"-")++"|")++"\n"

```

Try it online!
Same length:

```
a#b=unlines[take(lcm a b)$cycle$([2..x]>>"-")++"|"|x<-[a,b]]

```

Old solution:

```
l!x=[1..div l x]>>([2..x]>>"-")++"|"
a#b|l<-lcm a b=l!a++'\n':l!b

```
> 2 votes

# Answer
# Python 2, 89 bytes

*Not the shortest Python 2 entry, but a different approach than* `gcd` *which may still be golfable.*

```
a,b=input()
h,p='-|'
x=b*(h*~-a+p),a*(h*~-b+p)
for v in x:print v[~zip(*x).index((p,p)):]

```

**Try it online!**
> 2 votes

# Answer
# Whispers v2, 131 bytes

```
> Input
> Input
>> 1⊔2
>> (3]
>> L∣1
>> L∣2
>> Each 5 4
>> Each 6 4
> '-|'
>> 9ⁿL
>> Each 10 7
>> Each 10 8
>> Output 11 12

```

Try it online!

## How it works

If you're unfamiliar with Whispers' program structure, I'd recommend reading the first part of this post.

In this explanation, we'll refer to the two inputs as \\$x\\$ and \\$y\\$ respectively. Our first two lines simply take the inputs in, and store them on lines **1** (\\$x\\$) and **2** (\\$y\\$). We then move to line **3**, which returns \\$\alpha = \mathrm{lcm}(x, y)\\$ and to line **4**, which returns the range \\$A = \[1, 2, ..., \alpha\]\\$.

Next, we reach our first two `Each` statements, operating on each of the inputs:

```
>> L∣1
>> L∣2
>> Each 5 4
>> Each 6 4

```

These four lines both operate on \\$A\\$, but return two different arrays, which we will call \\$A\_x\\$ and \\$A\_y\\$. While being different arrays, they are both formed in similar ways, as can be noted from the similarities in the two pairs of lines. In fact, we can define \\$A\_x\\$ and \\$A\_y\\$ as

$$A\_x := \[(i \div x) \in \mathbb{Z} \\: | \\: i \in A\]$$ $$A\_y := \[(i \div y) \in \mathbb{Z} \\: | \\: i \in A\]$$

This leaves us with two lists consisting of a \\$1\\$ where we'd expect there to be a `|` character, and a \\$0\\$ where there should be a `-`. This takes us to the next section of our code:

```
> '-|'
>> 9ⁿL
>> Each 10 7
>> Each 10 8

```

First, we yield the string `-|`, then we create our next two arrays \\$B\_x\\$ and \\$B\_y\\$. Helpfully, we can use the same function to map \\$A\_x\\$ to \\$B\_x\\$ and \\$A\_y\\$ to \\$B\_y\\$, namely `9ⁿL`. This function yields the \\$n^{th}\\$ element of the string on line **9** i.e. `-|`, where \\$n\\$ is either \\$0\\$ or \\$1\\$, depending on the element from the respective \\$A\\$ arrays. This yields the two arrays \\$B\_x\\$ and \\$B\_y\\$ as defined below:

$$(B\_x)\_i = \begin{cases} \text{"-"}, & (A\_x)\_i = 0 \\ \text{"|"}, & (A\_x)\_i = 1 \end{cases}$$

$$(B\_y)\_i = \begin{cases} \text{"-"}, & (A\_y)\_i = 0 \\ \text{"|"}, & (A\_y)\_i = 1 \end{cases}$$

The `Each` command is special-cased for when yielding an array of strings, where it returns a single string, rather than an array. Finally, we reach the statement

```
>> Output 11 12

```

which outputs \\$B\_x\\$, then a newline, then \\$B\_y\\$
> 2 votes

# Answer
# SOGL V0.12, ~~19~~ 16 bytes

```
2{H┌*┐+..*..g/mP

```

Try it Here!

Explanation:

```
2{                two times do
  H                 decreate ToS - input - by 1
   ┌*               get that many dashes
     ┐+             append a vertical bar
       ..*          push both inputs multiplied           \
          ..g       push gcd(input1, input2)              | LCM - 7 bytes :/
             /      divide the multiblication by the GCD  /
              m     mold the string to that length
               P    print that in a new line

```
> 1 votes

# Answer
# C (gcc), ~~121~~ ~~99~~ ~~93~~ ~~92~~ 89 bytes

This should be much shorter, hmmmm....

```
#define L(x)for(j=-1,i=a;j<i;i+=i%b||i%a)putchar(++j?j%x?45:124:10);
i,j;f(a,b){L(a)L(b)}

```

Try it online!
> 1 votes

# Answer
# , 20 bytes

```
'-|'{~*.$&>;&(<:=i.)

```

Try it online!
> 1 votes

# Answer
# Ruby, 64 57 bytes

```
->a,b{[a,b].map{|n|(1..a.lcm(b)).map{|x|x%n>0??-:?|}*''}}

```

-7 bytes thanks to G B.

Try it online!
> 1 votes

# Answer
# Charcoal, ~~32~~ ~~30~~ 29 bytes

```
ＮθＮη≔θζＷ﹪ζη≦⁺θζＥ⟦θη⟧…⁺×-⁻ι¹|ζ

```

Try it online! Link is to verbose version of code. Edit: Saved 1 byte thanks to @ASCII-only.
> 1 votes

# Answer
# Stacked, ~~42~~ 38 bytes

```
[:...lcm@z:[:z\/\#-'-'*\rep'|'+out]"!]

```

Try it online!

Input in the form of a pair of numbers. All the test cases put together look kinda like buildings.

## Explanation

This first takes the `lcm` of the two input numbers into `z`. Then, for each number `k`, we generate `z / k` strings of `-` of length `k - 1`, adding `|` to the end of each, and outputting each.

## Previous counted attempts

42 bytes: `[:...lcm@z:[:z\/\#-'-'*\rep'|'+''#`out]"!]`

## Other attempts

43 bytes: `[:...lcm@z:[:z\/\#-'-'*\rep'|'#`'|'+out]"!]`

45 bytes: `['@lcm'!#~@z,[:z\/\#-'-'*\rep'|'#`'|'+out]"!]`

45 bytes: `[:...lcm@x[x'-'*\#<$betailmap'|'#`'|'+out]"!]`

53 bytes: `[:...lcm'-'*@z#-'.'*'('\+')'+'.'+[z\'$1|'repl out]"!]`

54 bytes: `[:...lcm@x{!x'-'*('('n#-'.'*').')''#`'$1|'repl out}"!]`
> 1 votes

# Answer
**VBA (Excel) , 144  142 bytes**

```
Sub q()
a=[a1]
b=[a2]
Do Until c=d And d="|"
e=e+1
c=IIf(e Mod a,"-","|")
d=IIf(e Mod b,"-","|")
f=f& c
g=g& d
Loop
Debug.? f& vbCr& g
End Sub

```

-2 bytes. thanks Sir Washington Guedes.
> 1 votes

# Answer
# JavaScript (ES6), 89

```
f=(a,b,t=`
`,l=0,R=n=>'-'.repeat(n-1)+'|')=>l||1/t?f(a,b,l<0?t+R(b,l+=b):R(a,l-=a)+t,l):t

```

Evaluating the LCM with repeated addictions.

*Less golfed*

```
F=(a,b, sa='', sb='', la=0, lb=0)=>
{
    var R=n=>'-'.repeat(n-1)+'|'
    if (la != lb || la == 0)
    {
        if (la < lb) {
            sa += R(a)
            la += a
        }
        else
        {
            sb += R(b)
            lb += b
        }
        return F(a, b, sa, sb, la, lb)
    }
    else
        return sa+'\n'+sb
}

```

**Test**

```
f=(a,b,t=`
`,l=0,R=n=>'-'.repeat(n-1)+'|')=>l||1/t?f(a,b,l<0?t+R(b,l+=b):R(a,l-=a)+t,l):t

function update()
{
  var [a,b]=I.value.match(/\d+/g)
  R.textContent = f(+a,+b)
}

update()
```

```
<input id=I oninput='update()' value='4 6'>
<pre id=R></pre>
```
> 1 votes

# Answer
# , 20 bytes

```
*./($'-|'#~<:,1:)"0]

```

Try it online!
> 1 votes

# Answer
# Google Sheets, 77 Bytes

Anonymous worksheet formula that takes input from range `A1:B1` and outputs to the calling cell

```
=REPT(REPT("-",A1-1)&"|",LCM(1:1)/A1)&"
"&REPT(REPT("-",B1-1)&"|",LCM(1:1)/B1

```

-4 Bytes thanks to @EngineerToast
> 1 votes

# Answer
# Excel VBA, 79 Bytes

Anonymous VBE immediate window function that takes input from the range `[A1:B1]` and outputs a visualization of their LCM to the VBE immediate window.

<sub>*This is a port of my Google Sheets answer.*</sub>

```
?[Rept(Rept("-",A1-1)&"|",LCM(1:1)/A1)]:?[Rept(Rept("-",B1-1)&"|",LCM(1:1)/B1)]

```
> 1 votes

# Answer
# Japt, 12 bytes

```
£×/Ury)î|ù-X

```

Japt Interpreter

Inputs as an array of numbers. Outputs as an array of strings. The -R flag slightly improves how the output looks, but isn't necessary for the logic.

Explanation:

```
£              For each of the two inputs as X, print...
        |           The string "|"
         ù-X        Left-padded with "-" until it is X characters long
       î            Repeated until its length is
 ×/Ury)             The Least Common Multiple
```

Extra thanks to Shaggy for finding some bytes to save.
> 1 votes

# Answer
# Jelly, 11 bytes

```
,ḍþælị⁾|-ZY

```

Try it online!

## How it works

```
,ḍþælị⁾|-ZY - Main link. Takes A on the left and B on the right
,           - Pair; [A, B]
   æl       - LCM; L := LCM(A, B)
  þ         - Create a 2×L matrix and for each cell (i,j) i ∈ (A,B), 1 ≤ j ≤ L:
 ḍ          -   Is i divisible by j?
     ị⁾|-   - Index into "|-", replacing 1 with "|" and 0 with "-"
         Z  - Transpose the matrix into a L×2 matrix
          Y - Join by newlines

```
> 1 votes

# Answer
# Pyth - 20 bytes

```
j.e*/@QtkiFQ+*\-tb\|

```

Test Suite.
> 0 votes

# Answer
# Retina, 67 bytes

```
\d+
$*-
^((-+)(\2)*) ((\2)+)$
$1$#5$*1¶$4$#3$*11
-1
|
+`(-*.)1
$1$1

```

Try it online! Link includes test cases.
> 0 votes

# Answer
# PHP, 142 bytes

```
list(,$a,$b)=$argv;for($n=$a;$n<=$a*$b;$n+=$a)if($n%$b==0)break;while($i<$n)echo++$i%$a==0?'|':'-';echo"
";while($j<$n)echo++$j%$b==0?'|':'-';

```

Try it online !
> 0 votes

# Answer
## Javascript (ES6), 84 bytes

```
f=(a,b,c=1,o=x='-'.repeat(a-1)+'|')=>(o.length%b?f(a,b,0,o+x):o)+(c?`
`+f(b,a,0):'')

```

Test Cases:

```
f=(a,b,c=1,o=x='-'.repeat(a-1)+'|')=>(o.length%b?f(a,b,0,o+x):o)+(c?`
`+f(b,a,0):'')

console.log(f(1,1));
console.log(f(1,2));
console.log(f(2,1));
console.log(f(2,2));
console.log(f(6,4));
console.log(f(4,6));
console.log(f(2,3));
console.log(f(3,2));
console.log(f(10,10));
console.log(f(3, 6));
console.log(f(2, 5));
console.log(f(4, 3));
console.log(f(10, 10));
console.log(f(10, 5));
console.log(f(10, 6));
console.log(f(24, 8));
console.log(f(7, 8));
console.log(f(6, 8));
console.log(f(13, 11));
```

## Old answer Javascript (ES6), 91 bytes

```
f=(a,b)=>{for(x=y='',i=0;!i++||q||r;)q=i%a,r=i%b,x+=q?'-':'|',y+=r?'-':'|';return x+'\n'+y}

```
> 0 votes

# Answer
# AWK, 80 bytes

```
{for(;++m%$1||m%$2;)for(i=0;i++<2;)r[i]=r[i](m%$i?"-":"|");$0=r[1]"|\n"r[2]"|"}1

```

Try it online!

For 2 or more values you can use the following 94 bytes:

```
{m=0;for(x=1;x&&++m;)for(x=i=0;i++<NF;){x+=r=m%$i;R[i]=R[i](r?"-":"|")}for(;++z<i;)print R[z]}

```

Try it online!

I'm probably missing something obvious to shorten this. :)
> 0 votes

# Answer
# Ruby, 45 bytes

```
->a,b{[a,b].map{|x|(?-*~-x+?|)*(a.lcm(b)/x)}}

```

Try it online!
> 0 votes

# Answer
# PHP, ~~85~~ 82 bytes

```
for([,$a,$b]=$argv;++$i%$a|$y=$i%$b;$t.="-|"[!$y])$s.=$i%$a?"-":"|";echo"$s|
$t|";

```

Try it online.
> 0 votes

# Answer
# Perl 6, 39 bytes

```
{@^a>>.&{('-'x$_-1~'|')x([lcm] @a)/$_}}

```

Try it online!

Takes input as a pair of numbers and returns a list of lines. Note that you can pass in as many integers as you like and it will print the `lcm` graph of all of them.
> 0 votes

# Answer
# Powershell, 79 bytes

```
param($a,$b)do{$x+='-|'[!($c=++$i%$a)];$y+='-|'[!($d=$i%$b)]}while($c+$d)
$x;$y

```

Ungolfed test script:

```
$f = {

param($a,$b)
do{
    $x+='-|'[!($c=++$i%$a)]
    $y+='-|'[!($d=$i%$b)]
}while($c+$d)
$x;$y

}

@(
    ,(1,1,"| |")
    ,(1,2,"|| -|")
    ,(2,1,"-| ||")
    ,(6,4,"-----|-----| ---|---|---|")
    ,(4,6,"---|---|---| -----|-----|")
    ,(2,3,"-|-|-| --|--|")
    ,(3,2,"--|--| -|-|-|")
    ,(3,6,"--|--| -----|")
    ,(2,5,"-|-|-|-|-| ----|----|")
    ,(4,3,"---|---|---| --|--|--|--|")
    ,(10,10,"---------| ---------|")
    ,(10,5,"---------| ----|----|")
    ,(10,6,"---------|---------|---------| -----|-----|-----|-----|-----|")
    ,(24,8,"-----------------------| -------|-------|-------|")
    ,(7,8,"------|------|------|------|------|------|------|------| -------|-------|-------|-------|-------|-------|-------|")
    ,(6,8,"-----|-----|-----|-----| -------|-------|-------|")
    ,(13,11,"------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|------------| ----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|")
) | % {
    $a,$b,$expected = $_
    $result = &$f $a $b
    "$(""$result"-eq"$expected"): $a,$b"
    $result
}

```

Output:

```
True: 1,1
|
|
True: 1,2
||
-|
True: 2,1
-|
||
True: 6,4
-----|-----|
---|---|---|
True: 4,6
---|---|---|
-----|-----|
True: 2,3
-|-|-|
--|--|
True: 3,2
--|--|
-|-|-|
True: 3,6
--|--|
-----|
True: 2,5
-|-|-|-|-|
----|----|
True: 4,3
---|---|---|
--|--|--|--|
True: 10,10
---------|
---------|
True: 10,5
---------|
----|----|
True: 10,6
---------|---------|---------|
-----|-----|-----|-----|-----|
True: 24,8
-----------------------|
-------|-------|-------|
True: 7,8
------|------|------|------|------|------|------|------|
-------|-------|-------|-------|-------|-------|-------|
True: 6,8
-----|-----|-----|-----|
-------|-------|-------|
True: 13,11
------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|
----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|

```
> 0 votes

# Answer
# Julia 1.0, ~~52~~ 47 bytes

```
p->println.(@.("-"^(p-1)*"|").^(lcm(p...).÷p))

```

Anonymous function; takes a list or tuple of two integers and prints the ASCII-art. Try it online!

### Explanation

```
p->                 Function of p (a list or tuple of two integers):
 println.(   )       Print with newline, vectorized:
  @.(   )             Vectorize throughout the following expression:
    "-"^(p-1)*"|"      String of x-1 hyphens and one pipe for each x in p
   (   ).^(   )        each repeated this many times:
      lcm(p...)         LCM of the two integers in p
               .÷p      divided by each number in p

```
> 0 votes

---
Tags: code-golf, math, ascii-art, number, integer
---


title: How lit is this mountain?

text:
# Question
Title: How lit is this mountain?
A *mountain* is defined to be a set of line segments whose first point has coordinates `(0,a)` where `a > 0`, and whose last point has coordinates `(b,0)`, where `b > 0`. All intermediate points have a y-coordinate (ordinate) strictly greater than 0. You are given the points on the mountain sorted in ascending order of x-coordinate (abscissa). **Note that two points can have the same x-coordinate, producing a vertical segment of the mountain. If you are given two points with the same x-coordinate, they should be connected in the order they are given. In addition, there can be horizontal segments of the mountain These horizontal segments are not lit, no matter what.** All coordinates are nonnegative integers.

The question: what is the total length of the mountain that would be lit, assuming the sun is an infinite vertical plane of light located to the right of the mountain? This number does not need to be rounded, but if it is rounded, include at least **four decimal places.** I have included a picture:  Here, the lines that are bolded represent the segments that are lit. Note that in the input, P appears before Q (PQ is a vertical line segment) so the previous point is connected to P and not Q.

You may take input in any reasonable format, like a list of lists, a single list, a string, etc.

Test case:

```
(0,3000)
(500, 3500)
(2500, 1000)
(5000,5000)
(9000,2000)
(9000,3500)
(10200,0)

Output: 6200.0000

```

There are two lit-up segments here, as shown in this image: The first one has length 5000/2 = 2500 and the second one has length 3700.

This is , so the shortest answer in bytes wins.

# Answer
> 15 votes
# Python 2,  ~~134 131 128 124 120 117 109~~  107 bytes

```
p=input();s=0
for X,Y in p[1:]:x,y=p.pop(0);n=y-max(zip(*p)[1]);s+=n*(1+((X-x)/(y-Y))**2)**.5*(n>0)
print s

```

Try it online!

Takes input as a list of tuples / two-element lists of floating-point numbers.

# Explanation

We basically iterate through the pairs of points in the graph, and if \\$y\_1 \> y\_2\\$, then we calculate how much of the line is exposed to light. The pairwise iteration is performed with a `for` loop to get the next point, \\$(x\_2, y\_2)\\$, popping the first element in the list each time to retrieve the current point, \\$(x\_1, y\_1)\\$.

### Maths – What part of the line segment is exposed to light?

Let \\$(x\_1, y\_1)\\$ be the coordinates of the current point. Let \\$y\_{max}\\$ be the maximum height of a point after the current one (local maxima after the current point) and \\$(x\_2, y\_2)\\$ be the coordinates of the next point. In order to calculate the length exposed to the sun, \\$L\\$, we ought to find \\$x\_3\\$, as shown in the diagram. Naturally, if \\$y\_1 \le y\_{max}\\$, the segment is not exposed to light at all.

In the triangle formed, the line segment of length \\$x\_3\\$ is parallel to the base, of length \\$x\_2 - x\_1\\$, so all three angles are congruent. Therefore, from the Fundamental Theorem of Similarity (case Angle-Angle), we can deduce that \\$\frac{x\_3}{x\_2 - x\_1} = \frac{y\_1-y\_{max}}{y\_1}\\$. Hence, \\$x\_3 = \frac{(y\_1-y\_{max})(x\_2 - x\_1)}{y\_1}\\$. Then, we can apply the Pythagorean Theorem to find that:

$$L = \sqrt{(y\_1-y\_{max})^2+x\_3^2}$$

By joining the two formulas, we arrive at the following expression, which is the core of this approach:

$$L = \sqrt{(y\_1-y\_{max})^2+\left(\frac{(y\_1-y\_{max})(x\_2 - x\_1)}{y\_1}\right)^2}$$ $$L = \sqrt{(y\_1-y\_{max})^2\left(1+\frac{(x\_2 - x\_1)^2}{y\_1^2}\right)}$$

### Code – How does it work?

```
p=input();s=0                             # Assign p and s to the input and 0 respectively.
for X,Y in p[1:]:                         # For each point (X, Y) in p with the first
                                          # element removed, do:
    x,y=p.pop(0)                          # Assign (x, y) to the first element of p and
                                          # remove them from the list. This basically
                                          # gets the coordinates of the previous point.
    n=y-max(zip(*p)[1])                   # Assign n to the maximum height after the
                                          # current one, subtracted from y.
    s+=n*(1+((X-x)/(y-Y))**2)**.5         # Add the result of the formula above to s.
                                 *(n>0)   # But make it null if n < 0 (if y is not the
                                          # local maxima of this part of the graph).
print s                                   # Output the result, s.

```

### Changelog

* Gradually optimised the formula for golfing purposes.
* Saved 1 byte thanks to FlipTack.
* Saved 2 bytes by removing the unnecessary condition that `y>Y`, since if the local maxima of the *Y*-coordinate after the current point subtracted from `y` is positive, then that condition is redundant. This unfortunately invalidates FlipTack’s golf, though.
* Saved 3 bytes by changing the algorithm a bit: instead of having a counter variable, incrementing it and tailing the list, we remove the first element at each iteration.
* Saved 8 bytes thanks to ovs; changing `(x,y),(X,Y)` in the loop condition with a `list.pop()` technique.
* Saved 2 bytes thanks to Ørjan Johansen (optimised the formula a little bit).

# Answer
> 12 votes
# JavaScript, 97 bytes

```
a=>a.reduceRight(([p,q,l=0,t=0],[x,y])=>[x,y,y>t?(y-t)/(s=y-q)*Math.hypot(x-p,s)+l:l,y>t?y:t])[2]

```

```
f=a=>a.reduceRight(([p,q,l=0,t=0],[x,y])=>[x,y,y>t?(y-t)/(s=y-q)*Math.hypot(x-p,s)+l:l,y>t?y:t])[2];
t=[[0, 3000], [500, 3500], [2500, 1000], [5000, 5000], [9000, 2000], [9000, 3500], [10200, 0]];
console.log(f(t));
```

( 5 bytes may be saved, if taking reversed version of input is considered valid. )

# Answer
> 10 votes
# APL+WIN, 48 bytes

```
+/((h*2)+(((h←-2-/⌈\m)÷-2-/m←⌽⎕)×(⌽-2-/⎕))*2)*.5

```

Prompts for a list of x coordinates followed by a list of y coordinates

Explanation

```
h←-2-/⌈\m difference between successive vertical maxima viewed from the right (1)

-2-/m←⌽⎕ vertical difference between points (2)

⌽-2-/⎕ horizontal difference between points (3)

```

The lit vertical distances = h and the lit horizontal distances are (3)\*(1)/(2). The rest is Pythagoras.

# Answer
> 6 votes
# Swift, 190 bytes

```
import Foundation
func f(a:[(Double,Double)]){var t=0.0,h=t,l=(t,t)
a.reversed().map{n in if l.0>=n.0&&n.1>l.1{t+=max((n.1-h)/(n.1-l.1)*hypot(n.0-l.0,n.1-l.1),0)
h=max(n.1,h)}
l=n}
print(t)}

```

Try it online!

## Explanation

```
import Foundation                  // Import hypot() function
func f(a:[(Double,Double)]){       // Main function
  var t=0.0,h=0.0,l=(0.0,0.0)      // Initialize variables
  a.reversed().map{n in            // For every vertex in the list (from right to left):
    if l.0>=n.0&&n.1>l.1{          //   If the line from the last vertex goes uphill:
      t+=max((n.1-h)/(n.1-l.1)     //     Add the fraction of the line that's above the
        *hypot(n.0-l.0,n.1-l.1),0) //     highest seen point times the length of the line
                                   //     to the total
      h=max(n.1,h)}                //     Update the highest seen point
    l=n}                           //   Update the last seen point
  print(t)}                        // Print the total

```

# Answer
> 5 votes
# Python 2, ~~122~~ 120 bytes

```
k=input()[::-1]
m=r=0
for(a,b),(c,d)in zip(k,k[1:]):
 if d>m:r+=(b>=m or(m-b)/(d-b))*((a-c)**2+(b-d)**2)**.5;m=d
print r

```

Try it online!

# Answer
> 5 votes
# Python 2, 89 bytes

```
M=t=0
for x,y in input()[::-1]:
 if y>M:t+=(y-M)*abs((x-X)/(y-Y)+1j);M=y
 X,Y=x,y
print t

```

Try it online!

Takes in a list of pairs of floats. Based off ovs's solution.

# Answer
> 4 votes
# Jelly,  ~~23~~  21 bytes

-2 thanks to caird coinheringaahing

```
ṀÐƤḊ_⁸«©0×I}÷I{,®²S½S

```

A dyadic link taking a list of y values on the left and a list of the respective x values on the right (as explicitly allowed by the OP in comments)

**Try it online!**

### How?

The fraction of a (sloping) section that is lit is the same fraction that would be lit if it were a vertical drop. Note that since squaring occurs to evaluate slope lengths the calculated heights along the way may be negative (also in the below the run-lengths of the lit slopes are calculated as negative divided by negative).

```
ṀÐƤḊ_⁸«©0×I}÷I{,®²S½S - Link:list, yValues; list, xValues
 ÐƤ                   - for suffixes of the yValues:       e.g. [ 3000, 3500, 1000, 5000, 2000, 3500,    0]
Ṁ                     -   maximum                               [ 5000, 5000, 5000, 5000, 3500, 3500,    0]
   Ḋ                  - dequeue                                 [ 5000, 5000, 5000, 3500, 3500,    0]
     ⁸                - chain's left argument, yValues          [ 3000, 3500, 1000, 5000, 2000, 3500,    0]
    _                 - subtract                                [ 2000, 1500, 4000,-1500, 1500,-3500,    0]
        0             - literal zero                            0
      «               - minimum (vectorises)                    [    0,    0,    0,-1500,    0,-3500,    0]
       ©              - copy to the register for later
           }          - apply to right:                     e.g [    0,  500, 2500, 5000, 9000, 9000, 10200]
          I           -   incremental differences               [  500, 2000, 2500, 4000,    0, 1200]
         ×            - multiply (vectorises)                   [    0,    0,    0,-6000000, 0,-4200000, 0]
               {      - apply to left:                     e.g. [ 3000, 3500, 1000, 5000, 2000, 3500,    0]
              I       -   incremental differences               [  500,-2500, 4000,-3000, 1500,-3500]
             ÷        - divide (vectorises)                     [    0,    0,    0, 2000,    0, 1200,    0]
                ®     - recall from the register                [    0,    0,    0,-1500,    0,-3500,    0]
               ,      - pair (i.e. lit slope [runs, rises])     [[0, 0, 0,    2000, 0,    1200, 0], [0, 0, 0,   -1500, 0,    -3500, 0]]
                 ²    - square (vectorises)                     [[0, 0, 0, 4000000, 0, 1440000, 0], [0, 0, 0, 2250000, 0, 12250000, 0]]
                  S   - sum (vectorises)                        [  0,   0,   0, 6250000,   0, 13690000,   0]
                   ½  - square root (vectorises)                [0.0, 0.0, 0.0,  2500.0, 0.0,   3700.0, 0.0]
                    S - sum                                     6200.0

```

---

25 byte monadic version taking a list of `[x,y]` co-ordinates:

```
ṀÐƤḊ_«0
Z©Ṫµ®FI×Ç÷I,Ç²S½S

```

Try this one.

# Answer
> 2 votes
# APL (Dyalog Unicode), 31 bytesSBCS

Uses Graham's formula.

Anonymous prefix function taking 2×n matrix of data as right argument. The first row contains x-values from right to left, and the second row the corresponding y-values.

```
{+/.5*⍨(×⍨2-/⌈\2⌷⍵)×1+×⍨÷⌿2-/⍵}

```

Try it online!

`{``}` anonymous lambda where  is the argument:

`2-/⍵` deltas (lit. pairwise minus-reductions)

`÷⌿`ΔxΔy (lit. vertical division reduction)

`×⍨` square (lit. multiplication selfie)

`1+` one added to that

`(` multiply the following with that:

`2⌷⍵` second row of the argument (the y values)

`⌈\` running maximum (highest height met until now, going from right)

`2-/` deltas of (lit. pairwise minus-reduction)

`×⍨` square (lit. multiplication selfie)

`.5*⍨`square-root (lit. raise that to the power of a half)

`+/` sum

# Answer
> 1 votes
# , 46 bytes

```
1#.((2([:%:@+&*:/-)/\,.)*>./\@]%&(2-~/\])])&|.

```

Try it online!

Takes x coord list as left arg, y coord list as right arg.

Could save 5 bytes if reversed lists were allowed.

Though solved independently, the approach I landed on is almost identical to Adam's APL approach.

# Answer
> 0 votes
# Kotlin, 178 bytes

```
fun L(h:List<List<Double>>)=with(h.zip(h.drop(1))){mapIndexed{i,(a,b)->val t=a[1]-drop(i).map{(_,y)->y[1]}.max()!!;if(t>0)t*Math.hypot(1.0,(a[0]-b[0])/(a[1]-b[1]))else .0}.sum()}

```

Try it online!

The testing part is very much *not* golfed :)

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


title: Shoes for seahorses

text:
# Question
Title: Shoes for seahorses
Seahorses, of course, need shoes. However, a seahorse, having just one tail, needs just one shoe. Unfortunately, the shoes only come in pairs. Money is tight for the seahorse government, so they need to buy as few pairs as possible. Each seahorse has a shoe size *x* where *x* is a positive integer. However, a seahorse can wear a shoe of size *x - 1* or *x + 1* if need be.

Your task is to output the minimum number of pairs the seahorse government must buy to put shoes on all their seahorses.

You may take input however you want, standard loopholes, etc.

As this is , shortest code in bytes wins.

## Test cases

```
2 4 6 6 8 14 ->        4
2 1 3 1 1 ->           3
4 1 4 9 1 8 9 1 8 4 -> 6
1 2 3 5 7 8 10 12 ->   4

```

# Answer
> 6 votes
# 05AB1E, 13 bytes

Uses the approach OP described in the comments.

```
{¥3‹J0¡€gÌ2÷O

```

Try it online!

### Explanation

```
{¥3‹J0¡€gÌ2÷O   Argument l
{               Sort l
 ¥              Push deltas
  3‹            Map to lower than 3 (1 for true, 0 for false)
    J0¡         Join and split on 0
       €g       Map to length
         Ì      Each + 2
          2÷    Integer division by 2
            O   Sum

```

# Answer
> 9 votes
## Husk, ~~15~~ 14 bytes

```
Γ0(→₀?tI↑<+3)O

```

Uses the greedy algorithm: sort and pair from the left. Try it online!

Thanks to Leo for saving 1 byte.

## Explanation

This is the first Husk answer that uses `Γ`, the function for pattern matching a list. In this use case, if `a` is a value and `g` is a function, then `Γag` corresponds to the function `f` defined by the Haskell snippet

```
f [] = a
f (x:xs) = g x xs

```

I define the base case as `a = 0` and

```
g x xs = 1 + line0 (if head xs < x+3 then tail xs else xs)

```

where `line0` refers to the entire line. In the Husk code, `x` and `xs` are implicit arguments to the lambda function, and `line0` is . The list is sorted again in each recursive call, but that doesn't matter in a golf challenge.

```
Γ0(→₀?tI↑<+3)O
             O  Sort
Γ               and pattern match
 0              giving 0 for an empty list
  (         )   and applying this function to a non-empty list:
          +3     Add 3 to first argument (x),
         <       make a "test function" for being less than that,
        ↑        take values from second argument (xs) while they pass the test.
     ?           If that prefix is nonempty (next value can be paired),
      t          take tail of xs,
       I         otherwise take xs as is.
    ₀            Apply the main function (line0) to this list
   →             and add 1 for the singleton/pair we just processed.

```

# Answer
> 7 votes
# Python 2, 49 bytes

```
f=lambda a:a>[a.sort()]and-~f(a[[3+a.pop(0)]>a:])

```

Try it online!

Based on Leaky Nun's recursive solution.

---

**Python 2, 59 bytes**

```
p=c=0
for x in sorted(input()):c+=x>p;p=(x>p)*(x+2)
print c

```

Try it online!

Iterates through the sizes `x` in sorted order. Remembers the upper threshold `p` for the current size to the paired with the previous one. If so (`x>p`), reset the threshold to `0` to make it impossible for the next one to be paired. If not, increment the output count `c` and set the next threshold `p` to `x+2`.

The new threshold `p=(x>p)*(x+2)` is a bloated expression. I'd like to find a way to shorten it.

# Answer
> 5 votes
# Python 3, ~~69~~ ~~66~~ 60 bytes

9 bytes thanks to xnor.

```
f=lambda a:a[1:a.sort()]and-~f(a[1+(a[1]-a[0]<3):])or len(a)

```

Try it online!

# Answer
> 4 votes
# Jelly, ~~20~~ 18 bytes

```
ṢLµIḢ<3+2⁸ṫß‘µLỊ$?

```

Try it online!

Fork of my Python answer.

# Answer
> 2 votes
## C#, ~~111~~ ~~108~~ ~~137~~ 102 bytes

This will never win but I wanted to solve the exercise anyway:

```
Array.Sort(a);var c=0;for(var i=0;i<a.Length;i++){c++;i+=a.Length-i>1&&a[i+1]-a[i]<3?1:0;}Console.WriteLine(c);

```

Thanks to the comment of @grabthefish, I was able to nibble of a few more bytes:

```
Array.Sort(a);int c=0,i=0;for(;i<a.Length;i++){c++;i+=a.Length-i>1&&a[i+1]-a[i]<3?1:0;}Console.WriteLine(c);

```

Following the PC&G special C# rules:

```
class P{static void Main(){Array.Sort(a);int c=0,i=0;for(;i<a.Length;i++){c++;i+=a.Length-i>1&&a[i+1]-a[i]<3?1:0;}Console.WriteLine(c);}}

```

Using a lambda function:

```
a=>{System.Array.Sort(a);int c=0,i=0;for(;i<a.Length;c++)i+=a.Length-i>1&&a[i+1]-a[i]<3?2:1;return c;}

```

# Answer
> 2 votes
## Perl, 113 bytes

```
say sub{for(1..$#_){$x{$i}++;$i++if$_[$_]-$_[$_-1]>2}$x{$i}++;$-+=$_/2+$_%2for values%x;$-}->(sort{$a<=>$b}@ARGV)

```

Takes list of arguments from command line (as `@ARGV`), prints to `STDOUT` by default.

## In Seahorseville...

A ***neighbourhood*** is a sequence of neighbouring shoe sizes. When sorted, each seahorse has immediate neighbours that can share the same shoe size. There can be multiple neighbours in the neighbourhood and no neighbours can differ in value by more than two:

e.g. `3 3 4 5 5 6` is a single neighbourhood, as are `2 4 6 6`, and `1 2 3 5 7 8 10 12`

e.g. `1 1 1 4 5 6` contains two neighbourhoods: `1 1 1` and `4 5 6`.

## Basis of the algorithm

There are two types of neighbourhood:

* ***Even-sized***

For these, `n/2` pairs is always sufficient:

e.g. `3 3 4 5 5 6` requires three pairs for `3 3`, `4 5` and `5 6`
* ***Odd-sized***

For these, `ceil(n/2)` pairs is always sufficient:

e.g. `12 13 13 14 15` requires three pairs for `12 13`, `13 14`, and `15` alone.

## Ungolfed code to test the algorithm

```
sub pairs {
    @_ = sort { $a <=> $b } @_;
    my @hood;
    my $i = 0;
    for (1..$#_) {
        push @{$hood[$i]}, $_[$_-1];
        $i++ if $_[$_]-$_[$_-1]>2
    }
    push @{$hood[$i]}, $_[$#_];
    my $pairs;
    $pairs += int(@{$hood[$_]} / 2) + @{$hood[$_]} % 2 for 0..$#hood;
    return "$pairs : @{[map qq([@$_]), @hood]}\n";
}

```

## Sample Results

*(Neighbourhoods enclosed in* `[ ]` *)*

```
4 : [2 4 6 6 8] [14]
3 : [1 1 1 2 3]
6 : [1 1 1] [4 4 4] [8 8 9 9]
4 : [1 2 3 5 7 8 10 12]
17 : [1 2 3] [6 8 9 11 13 13 15 17 19 20 21] [27 28 29 30 32 33 35 35] [38 38 40] [43 45 45 46] [49]
18 : [3 3 3] [8 10 11 11 11 12 14] [18] [21 22 23] [29] [32 33 34 34 34 35 37 38 39 41] [44 46 48 49 49]
18 : [1 2 3] [6] [9] [12 13 15 17 18 19 20 21 21 23 24 25 25] [35 36] [40 41 41 41 43 45 46 46 46] [49]
16 : [1 3] [6 6 6 6] [11 12 14 14 15 17 19 20 20 21 21 22] [25 25 27 29 31 32 33] [38 39] [44 45] [49]
16 : [2 4] [7 7 8 10 12 13 15 16] [22 22 24 24] [27 29 31 31 33 34] [37 38 39] [42 43 43 44 45 46 47]
17 : [2 4 5 6 7] [11 11 13 13 14 15 16 17 17 17 19] [29] [34 35 36] [39 39 41 41 41 42 44 46] [49 49]
18 : [3 4 5 7 7] [10 10 12 12 12 14 15 15 17 18] [21] [24 24] [28] [32] [39 40 41 42 43 44 44] [47 47] [50]
16 : [2 4] [7 7 8 8] [11 11] [14 16 17 17 18 19] [22 24 26 26] [30 31 33 34 34 35] [38 38 39] [42 43] [50]
16 : [1 3 4 5] [11 11] [15 15 17 18 19 21 22 23 23 25 27 27 27 27 28 29 30 30] [33 34] [41 41] [45] [48]
17 : [2 2 3 4 6 6 7] [10 10] [13 14 15 16 17 19] [23 25] [28 30 31 32 33 34 36 37 38] [42] [48 49 50]
17 : [2] [7 9 9 9 9 10 10 12] [16 16] [19 21 21 22 24] [27 27 27] [36 36 36 37 39 39 40 40 40 41] [46]
18 : [1] [5 6 6 8] [11 11 12] [19 19 20 21 22 24 26 26] [29 30 31 32 34 35 35] [38] [42] [45] [48 48 49 49]
16 : [2 4 4 6] [11 12 13 13 13] [21 21 21 23] [30 31 31 33 35] [41 41 41 43 45 46 47 48 48 49 49 50]
16 : [2 2] [8 10 12] [15 15 15 15 16 16] [19 20] [23 24] [28 28 29] [32 34 36 36 36 37 39 41] [44 45 47 48]
17 : [3 3] [6] [9 10 11] [17 18] [21 23 23] [27 28 29 29 30 31 31 33] [37 37 39 39 39 40] [43 44] [47 48 49]
17 : [4] [7 9 10 10] [14 14 14] [17] [21] [25 25 27 27 28 30] [33 35 37 37 38 40 41 43 44 45 47 48 49 50]
18 : [3 4 5 6 7] [10 11 12 12 14 15 16 17] [20] [23 24 25 25 26 26] [31] [35] [38 40 41 42] [45 46 47] [50]
17 : [1 3] [8 10] [16 16 18 19 20 20] [23 23] [26] [30 31 33 34 35] [39 39 39 40 41 42 43] [46 46 47 47 49]
18 : [2 4 4 4 4 6 7 8 8 10 10] [13] [16 17] [20 22 23 25 25] [29 29 29] [33] [39 40 42] [48 48 49 49]
16 : [1 1 3 4] [7 8 10 10] [18 18 20 21] [24 25 26 27 29 31 33 33 34 34] [37 37 39] [45 46 48 49 49]
17 : [1] [4 4] [7 9 9 11 12] [15 16 17 17 18 19 21 21 21 22 23] [27 28 30 31] [37 39] [42] [48 49 49 50]
17 : [3 4 6 7 7 8 9 10 10 11 13 14 14] [21 21 23] [26 27] [31 32] [35 36] [39 40 41 41 41] [44 44] [49]
16 : [1] [4 6 6 8 10 12 13 15] [20 20 21 21] [29 29 30] [34 36 36 37 37 38 38 40] [44 45 46 47 47 48]
17 : [3 4 4 6] [12 14 15 16 17] [20 21 22 22 22 23 24 26 26] [29 30 32] [35 37 37 37 38 39 41 42] [48]
19 : [1] [5] [8 9] [14 14 14 16 16 17 17 17 17] [21] [24 24 24] [30] [34 35 36 37 39 40 40] [45 46 46 47 48]

```

# Answer
> 1 votes
# Mathematica, 67 bytes

```
Length@Flatten[Partition[#,UpTo@2]&/@Split[Sort@#,Abs[#-#2]<3&],1]&

```

Try in Wolfram sandbox.

# Answer
> 1 votes
# K (ngn/k), 31 bytes

```
{#,/0N 2#/:(0,&~t)_t:3>-':x@<x}

```

Try it online!

* `x@<x` sort the input (ascending)
* `t:3>-':` generate boolean array indicating where the difference between values is less than 3, storing in `t`
* `(0,&~t)_t` split `t` on where 0's are present, e.g. `1 1 1 0 1 1 0 1 1 1` =\> `(1 1 1;0 1 1;0 1 1 1)`
* `0N 2#/:` split each of the right-side arguments into length 2 chunks (i.e. valid "pairs" of shoes)
* `#,/` flatten the chunks and take their count

# Answer
> 0 votes
## Perl, 103 bytes

```
say sub{for(1..$#_+1){$x{$i}++;$i++if$_[$_]-$_[$_-1]>2}@_/2+.5*grep$_%2,values%x}->(sort{$a<=>$b}@ARGV)

```

Takes list of arguments from command line (as `@ARGV`), prints to `STDOUT` by default.

This is an alternative approach, based on the following relationship:

```
Minimum pairs = ( Population size + # Odd neighbourhoods ) / 2

```

(See this answer for how *neighbourhood* is defined)

# Answer
> 0 votes
# Javascript, 67 bytes

```
a=>(a=a.sort((a,b)=>a-b)).filter((n,i)=>m=!m|n-a[i-1]>2,m=0).length

```

Example code snippet:

```
f=
a=>(a=a.sort((a,b)=>a-b)).filter((n,i)=>m=!m|n-a[i-1]>2,m=0).length

v=[[2,4,6,6,8,14],[2,1,3,1,1],[4,1,4,9,1,8,9,1,8,4],[1,2,3,5,7,8,10,12]]
for(k=0;k<4;k++)
  console.log(`f([${v[k]}])=${f(v[k])}`)
```

# Answer
> 0 votes
# , 29 28 bytes

```
[:#(([#~_2>-&{.),_:0}])/@/:~

```

Try it online!

Basic idea:

* `/:~` Sort.
* `(...)/` Fold from the right, collapsing pairs into the single value infinity `_`, and appending the new value otherwise.
* `[:#` Return the length of the result.

Specifically, step 2 works like this:

* `_:0}]` Update the first element `0}` of the right-hand fold argument `]` (the list we're "building", the "memo" of the reduce, etc) to infinity `_:`.
* `_2>-&{.` When the difference between the left-hand fold argument and the first element of the right-hand fold argument is less than negative 2 `_2`, append the left-hand argument `[#~...,`. This condition will hold when either:
    + The values are too far apart to wear the same shoe.
    + The previous value was already "used up" by a preceding pair. The right argument will always be infinity in this case.

# Answer
> 0 votes
# Jelly, 13 bytes

```
Ṣ3+þŒpŒɠ€HĊ§Ṃ

```

Try it online!

# Explatation

```
Ṣ3+þŒpŒɠ€HĊ§Ṃ   Main monadic link
Ṣ               Sort
 3+þ            Add [1,2,3] to each element
    Œp          Cartesian product
      Œɠ        Run lengths
        €         of each sublist
         H      Halve all numbers
          Ċ     Ceil all numbers
           §    Sum each sublist
            Ṃ   Minimum

```

---
Tags: code-golf
---


title: Tips for golfing in Julia

text:
# Question
Title: Tips for golfing in Julia
What general tips do you have for golfing in Julia? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Julia (e.g. "remove comments" is not an answer).

# Answer
> 27 votes
NOTE: The below are correct as of Julia 1.4.1

A few tricks to save a few characters

1. **Overload operators with frequently used binary functions**. For example, if you need to do a lot of integer divisions, and no need for inverse division, use `\ =div`, and you can then type `a\b` instead of `div(a,b)`. Note the space - this is necessary to avoid it parsing as a "=" operator. Also note that, if overloaded at REPL prompt level, use `(\)=Base.(\)` or `\ =Base. \` to reset it. NOTE: some functions have existing UTF-8 operators pre-defined, such as `÷` for `div`, as noted by Alex A.
2. **Use ^ with strings for conditional output**. That is, rather than `a>0?"Hi":""`, use `"Hi"^(a>0)` to save one byte, or for boolean a, use `"Hi"^a` to save three bytes.
3. (sometimes) **Store small fixed-size vectors as separate variables**. For instance, rather than `a=split("Hi there"," ")`, you may be able to avoid `a[1]` and `a[2]` by using `a,b=split("Hi there"," ")`, which can be referenced as `a` and `b`, saving three bytes for each use, at the cost of just two extra characters at assignment. Obviously, do not do this if you can work with vector operations.
4. **Don't use isempty for Arrays, Tuples, or Strings** \- instead, use `==[]` for arrays and `==()` for tuples; similarly, for the negative, use `!=[]` and `!=()`. For strings, use `==""` for empty, but use `>""` for not-empty, as "" is lexicographically before any other string and it saves one byte.
5. **Use the right short-circuit boolean operator in place of "if"**. It might be a bit less Julia-specific, but it is worth bearing in mind. `x<=1&&"Hi"` can be written as `x>1||"Hi"`, saving a character (so long as the return of the boolean isn't important).
6. **Don't use contains to check presence of character in string** \- if you're restricted to the basic ASCII, use `in('^',s)` rather than `contains(s,"^")`. If you can use other characters, you can save a bit more with `'^'∈s`, but note that  is 3 bytes in UTF-8.
7. **Looking for minimum/maximum values in an array? Don't use minimum or maximum** \- rather than using `minimum(x)` or `maximum(x)`, use `min(x...)` or `max(x...)`, to shave one character off your code. ~~Alternatively, if you know all elements of `x` will be non-negative, use `minabs(x)` or `maxabs(x)`~~
8. **Where possible and permitted by the challenge, use an actual newline instead of \n** \- note that this will make your code harder to read, and may mean that you need to provide an "ungolfed" version to make it possible for people to actually understand it.
9. **Put options after the regex string** \- if you want to have a regex string in multiline mode, for example, don't type `r"(?m)match^ this"`, type `r"match^ this"m`, saving three characters.
10. **Where possible, use array concatenation instead of push!, unshift!, append!, or prepend!** \- for normal arrays, this can be done easily. For arrays of type Any with array elements, you will need the type `Any`, as in `Any[[1,2]]`. At one stage, curly braces could be used as an alternate notation (`{[1,2]}`), but this has been discontinued.
11. **Don't use collect to convert a string into a char array** \- instead of `collect(A)`, use `[A...]`, which will do the same thing and save 4 bytes.
12. **Need a number converted to a string?** Use `"$(s[i])"` ~~or `dec(s[i])`~~ for expressions or multi-character variables, and `"$i"` for single-character variables.
13. **Use `union` or  instead of `unique`** \- `union(s)` will do the same thing as `unique(s)`, and save a byte in the process. If you can use non-ASCII characters, then `∪(s)` will do the same thing, and  only costs 3 bytes instead of the 5 bytes in `union`. In some circumstances, for single-character variables, you can save another byte using `s∪s` (thanks, MarcMush, for `s∪s`).
14. **Use array indexing to get the size of an array or string** \- when you use `end` within array indexing, it automatically gets converted to the length of the array/string. This can be handy when you want to collect the length while doing certain operations. For example, if you need the length of `A` and the middle value, you might write `A[(k=end)÷2]`. This can also work in multiple dimensions, and for index iterators - `A[(k=1:end;)]` will give you an iterator for `k=1:length(A)`, which can be handy when you also want to use `A`. Note that the assignment must occur in brackets, with a semicolon (such as `(k=end;)`) if no operation is done outside the brackets. (thanks to MarcMush for identifying a workaround for keywords in array indexing)

***Outdated tricks that worked at some point, but no longer do:***

> **Access first element of Array with `[]`** \- for arrays, the expression `A[]` is equivalent to `A[1]`. Note that this does not work for Strings if you wish to get the first character, or for Tuples. - **`A[]` no longer works.**

> **Reverse 1-D arrays using flipud** \- `reverse(x)` is one byte longer than `flipud(x)` and will perform the same operation, so the latter is better. - **`flipud` is no longer in Base.**

> **Use `?:` instead of `&&` or `||` for conditional assignment** \- that is, if you want to perform an assignment only on some condition, you can save one byte by writing `cond?A=B:1` rather than `cond&&(A=B)`, or `cond?1:A=B` rather than `cond||(A=B)`. Note that the `1`, here, is a dummy value. - **the `?:` notation now requires spaces around `?` and `:`.**

# Answer
> 18 votes
# Redefine operators to define functions

Redefining operators can save a lot of bytes in parentheses and commas.

### Recursive unary operators

For a unary example, compare the following recursive implementations of the Fibonacci sequence:

```
F(n)=n>1?F(n-1)+F(n-2):n # 24 bytes
!n=n>1?!~-n+!(n-2):n     # 20 bytes
!n=n>1?!~-n+!~-~-n:n     # 20 bytes

```

Try it online!

The redefined operator retains its initial precedence.

Note that we could not simply swap out `!` in favor of `~`, since `~` is already defined for integers, while `!` is only defined for Booleans.

### Binary operators

Even without recursion, redefining an operator is shorter than defining a binary function. Compare the following definitions of a simple divisibility test.

```
f(x,y)=x==0?y==0:y%x==0 # 23 bytes
(x,y)->x==0?y==0:y%x==0 # 23 bytes
x->y->x==0?y==0:y%x==0  # 22 bytes
x\y=x==0?y==0:y%x==0    # 20 bytes

```

Try it online!

### Recursive binary operators

The following illustrates how to redefine a binary operator to compute the Ackermann function:

```
A(m,n)=m>0?A(m-1,n<1||A(m,n-1)):n+1    # 35 bytes
^ =(m,n)->m>0?(m-1)^(n<1||m^~-n):n+1   # 36 bytes
| =(m,n)->m>0?m-1|(n<1||m|~-n):n+1     # 34 bytes
m\n=m>0?~-m\(n<1||m\~-n):n+1           # 28 bytes

```

Try it online!

Note that `^` is even longer than using a regular identifier, since its precedence is too high.

As mentioned before

```
m|n=m>0?m-1|(n<1||m|~-n):n+1           # 28 bytes

```

would not work for integer arguments, since `|` is already defined in this case. The definition for integers *can* be changed with

```
m::Int|n::Int=m>0?m-1|(n<1||m|~-n):n+1 # 38 bytes

```

but that's prohibitively long. However, it *does* work if we pass a float as left argument and an integer as right argument.

# Answer
> 13 votes
1. **Don't be too easily seduced by factor(n)** The tempting base library function `factor(n)` has a fatal flaw: it returns the factorization of your integer in an unordered `Dict` type. Thus, it requires costly `collect(keys())` and `collect(values())` and potentially also a `cat` and a `sort` to get the data you wanted out of it. In many cases, it may be cheaper to just factor by trial division. Sad, but true.
2. **Use map** `map` is a great alternative to looping. Be aware of the difference between `map` and `map!` and exploit the in-place functionality of the latter when you can.
3. **Use mapreduce** `mapreduce` extends the functionality of map even further and can be a significant byte-saver.
4. **Anonymous functions are great!** ..especially when passed to the aforementioned `map` functions.
5. **Cumulative array functions** `cumprod`, `cumsum`, the flavorful `cummin` and the other similarly named functions enable cumulative operations along a specified dimension of an n-dimensional array. (Or \*un\*specified if the array is 1-d)
6. **Short notation for Any** When you want to select all of a particular dimension of a multi-dimensional array (or Dict), e.g. `A[Any,2]`, you can save bytes by using `A[:,2]`
7. **Use the single-line notation for functions** Instead of `function f(x) begin ... end` you can often simplify to `f(x)=(...)`
8. **Use the ternary operator** It can be a space-saver for single-expression If-Then-Else constructions. *Caveats:* While possible in some other languages, you cannot omit the portion after the colon in Julia. Also, the operator is expression-level in Julia, so you cannot use it for conditional execution of whole blocks of code.
`if x<10 then true else false end` vs
`x<10?true:false`

# Answer
> 11 votes
# Iterate over functions

This is also possible in other languages, but usually longer than the straightforward method. However, Julia's ability to redefine its unary and binary operators make it quite golfy.

For example, to generate the addition, subtraction, multiplication and division table for the natural numbers from 1 to 10, one could use

```
[x|y for x=1:10,y=1:10,| =(+,-,*,÷)]

```

which redefines the *binary* operator `|` as `+`, `-`, `*` and `÷`, then computes `x|y` for each operation and `x` and `y` in the desired ranges.

This works for unary operators as well. For example, to compute complex numbers **1+2i**, **3-4i**, **-5+6i** and **-7-8i**, their negatives, their complex conjugates and their multiplicative inverses, one could use

```
[~x for~=(+,-,conj,inv),x=(1+2im,3-4im,-5+6im,-7-8im)]

```

which redefines the *unary* operator `~` as `+`, `-`, `conj` and `inv`, then computes `~x` for all desired complex numbers.

### Examples in actual contests

# Answer
> 7 votes
# 1. Use `@b_str` to store lists

returning an array of `UInt8`s (ranging 0-127 in ascii)

for example

* `[99,100]` -- 8 characters
* `b"cd"` -- 5 characters

and using Unicode characters:

* `b""` -- 4 characters, 7 bytes
* `[240,159,144,162]` -- way more

# 2. Avoid loops, use `.|>` or `@.`

Very often, `.|>` or broadcasting is shorter:

* `r=1:n;@.print(r*n^r)`
* `1:n.|>i->print(i*n^i)`
* `@.print((1:n)n^(1:n))`
* `print.((1:n).*n.^(1:n))`
* `[print(i*n^i) for i=1:n]`
* `for i=1:n print(i*n^i)end`

# 3. Choose the right function to override

* depending on the number of arguments it can take without parenthesis (useful for recursive functions)
* depending on their operator precedence

+ `>` and `<` are useful, with a lower precedence than `+` Example with `<`
    + `~` has a *very* low precedence, lower than `<`, `=>`, `&&`... Example
    + `^` has the highest precedence, battling with unary operators (`-x^-y == -(x^(-y))`)
    + `*` has the precedence of an unary operator when the `*` is omitted (`2x^2abs(y)a == 2*(x^(2*abs(y)*a))`)
* some quirky operators

+ `~` is the only operator that can be placed directly before a `=` (for example `~=length`)
    + `>` (and `>`, `==`...) can be splat without parenthesis, `~` also but not in the function definition Try it online!
    + `+` (and `*`, `++`) interprets `a+b+c` as `+(a,b,c)` rather than `(a+b)+c`
    + `<` (and `>`, `==`...) has a short-circuiting behaviour Try it online!

# 4. Some common substitions:

# Answer
> 6 votes
1. **Don't type `return`** `f(x)=x+4` is identical to but shorter than `f(x)=return x+4`. Julia always returns the result of the last statement.
2. **Use = instead of in**. `[x for x in 1:4]` is 3 characters longer than, but equivalent to `[x for x=1:4]`

# Answer
> 6 votes
1. Keywords can sometimes immediately follow constants without the need for a space or semicolon. For example:

```
n->(for i=1:n n-=1end;n)

```

Note the lack of a space between `1` and `end`. This is also true for `end` occurring after a close paren, i.e. `)end`.
2. Perform integer division using `÷` rather than `div()` or overloading an operator. Note that `÷` is worth 2 bytes in UTF-8.
3. Use `vec()` or `A[:]` (for some array `A`) rather than `reshape()` whenever possible.
4. Create functions rather than full programs when allowed in the challenge rules. It's shorter to define a function which accepts input rather than defining variables by reading from stdin. For example:

```
n->(n^2-1)
n=read(STDIN,Int);n^2-1

```
5. Variables can be incremented inside the argument to a function. For example, the following is my answer to the Find the Next 1-Sparse Binary Number challenge:

```
n->(while contains(bin(n+=1),"11")end;n)

```

This is shorter than incrementing `n` inside of the loop.

# Answer
> 6 votes
# Use Broadcasting function calls.

Introduced in Julia 0.5. It is like map, but uses less characters, and does broadcasting behavour over it's args -- which means you can write less lambda's to deal with things.

Rather than:

* `map(f,x)` -- 8 characters.
* `f.(x)` -- 5 characters

Better still:

* `map(a->g(a,y),x)` -- 16 characters
* `g.(x,[y])` -- 9 characters

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