title: Novel Prime Factors of Repunits

text:
# Question
Title: Novel Prime Factors of Repunits
### The Background

Folks were talking prime factorization in chat and we found ourselves talking about repunits. Repunits are a subset of the numbers known as repdigits, which are numbers consisting of only repeating digits, like `222` or `4444444444444444`, but repunits consist only of `1`.

The first couple repunits are therefore `1`, `11`, `111`, etc. These are referred to by *R*n, so *R*1=`1`, *R*2=`11`, etc., and are generated by the formula `R(n) = (10^n - 1)/9`, with `n > 0`.

Prime factorization of these repunit numbers follows sequence A102380 in the OEIS. For example:

> R1 = 1
> R2 = 11
> R3 = 111 = 3 * 37
> R4 = 1111 = 11 * 101
> R5 = 11111 = 41 * 271
> R6 = 111111 = 3 * 7 * 11 * 13 * 37
> R7 = 1111111 = 239 * 4649
> ...

### The Challenge

Write a program or function which, when given an input integer *n* with `n >= 2` via STDIN or equivalent, outputs or returns the novel prime factors for *R*n, in any convenient format. "Novel prime factors" here means all `x` where `x` is a prime factor of *R*n, but `x` is not a prime factor for any previous *R*k, with `1 <= k < n` (i.e., if we write the prime factors for all *R* in sequence, we've not seen `x` before).

### The Examples

```
Input: 6
Output: 7, 13
(because 3, 11, and 37 are factors of a smaller R_k)

Input: 19
Output: 1111111111111111111
(because R_19 is prime, so no other factors)

Input: 24
Output: 99990001
(because 3, 7, 11, 13, 37, 73, 101, 137, 9901 are factors of a smaller R_k)

Input: 29
Output: 3191, 16763, 43037, 62003, 77843839397
(because no factors of R_29 are also factors of a smaller R_k)

```

### The Extras:

* Your code can do anything or nothing if `n < 2`.
* You can assume a "reasonable" upper limit for `n` for testing and execution purposes -- your code will not be *expected* to output for `n = 10000000`, for example, but your algorithm should *work* for such a case if given unlimited computing power and time.
* Here is a site dedicated to the factorizations of repunits for reference.
* I've not gone through the math, but I propose a hypothesis that every *n* has a distinct result for this algorithm -- that is, no *n* exists such that *R*n has no novel factors. ~~I'll offer a **250-point bounty** if someone proves or disproves that in their answer.~~ Thomas Kwa proposed an elegant proof, and I awarded the bounty.

# Answer
> 5 votes
# Pyth, ~~16~~ ~~14~~ 13 bytes

```
-F_m{P/^Td9SQ

```

As best I can tell, 19 takes forever.

```
-F_m{P/^Td9SQ      Implicit: Q = input
           SQ      Inclusive range 1 to Q
                        Implicit lambda d:
    {P                  unique primes dividing
       ^Td              10**d
      /   9                  //9
   m               map lambda over the range
   m{P/^Td9SQ      Unique prime factors of all repunits up to the Qth
  _                Reverse the list
-F                 Reduce by set difference

```

Try it here.

# Answer
> 12 votes
# Proof that every repunit has a novel prime factor

Using Zsigmondy's Theorem, the proof is simple. From Wikipedia:

> In number theory, Zsigmondy's theorem, named after Karl Zsigmondy, states that if ***a \> b \> 0*** are coprime integers, then for any integer ***n ≥ 1***, there is a prime number ***p*** (called a primitive prime divisor) that divides ***an − bn*** and does not divide ***ak − bk*** for any positive integer ***k \< n***, with the following exceptions: \[things that don't apply here\].

Consider the repunits times 9: that is, ***10n-1***. By Zsigmondy's Theorem with **a=10**, **b=1**, there is some prime ***p*** **|** ***10n-1*** that does not divide any ***10k-1***, ***k \< n***.

* Since ***p*** is prime and ***10n-1 = 9 · Rn***, it must divide either **9** or ***Rn***.
* ***p*** cannot divide **9**, since ***9 = 101-1***.
* Therefore ***p*** divides ***Rn***.
* ***p*** cannot divide any ***Rk***, since it doesn't divide ***10k-1 = 9 · Rk***.

Therefore the ***p*** from Zsigmondy's Theorem is a novel prime factor of any ***Rn***, ***n ≥ 2***. ∎

---

## An example of a repeated novel prime factor

The prime **487** is a repeated prime factor of ***R486***:

By the Fermat-Euler theorem, **10487-1 ≡ 1 (mod 487)**. The order of 10 mod 487, that is, the smallest power of 10 that is 1 mod 487, therefore must be a divisor of 486. In fact, the order is equal to 486. It also happens that not only is **10486 ≡ 1 (mod 487)**, it's also **1 (mod 4872)**.

See here that the order of 10 mod 487 is 486; that is, that no smaller ***10k-1*** is divisible by 487. Obviously, 487 doesn't divide 9, so it must divide ***R486***.

# Answer
> 6 votes
## CJam, 18 bytes

```
{{)'1*imf}%W%:-_&}

```

Test it here.

Starting at 19 (the first repunit prime after 2) it will take a fairly long time.

### Explanation

This is an unnamed block (CJam's equivalent of a function), which expects the input number `n` on the stack and leaves a list of prime factors instead:

```
{      e# Map this block over [0 1 ... n-1]...
  )'1* e#   Increment and create a string of that many 1s.
  i    e#   Convert to integer.
  mf   e#   Get its prime factors.
}%
W%     e# Reverse the list.
:-     e# Fold set difference onto the list, removing from the first list the elements of
       e# all other lists.
_&     e# Remove duplicates. Unfortunately, this necessary. Thomas Kwa found that the 486th
       e# repunit contains 487^2 (where 487 is a novel prime factor).

```

# Answer
> 4 votes
## Haskell 86 bytes

```
import Data.Numbers.Primes
f n=[x|x<-primeFactors$div(10^n-1)9,notElem x$f=<<[1..n-1]]

```

Usage example: `f 8` -\> `[73,137]`.

Takes a lot of time and memory for big `n`.

Direct implementation of the definition: take all prime factors `x` of `Rn` which do not show up before (`f=<<[1..n-1]` are all prime factors of `R1 ... R(n-1)`).

# Answer
> 3 votes
# Mathematica ~~82 74~~ 63 bytes

With 11 bytes saved thanks to alephalpha.

```
Complement@@Reverse@FactorInteger[(10^Range@#-1)/9][[;;,;;,1]]&

```

---

**Prime factors of R70**

(10^70 - 1)/9 = 1111111111111111111111111111111111111111111111111111111111111111111111

```
FactorInteger[(10^70 - 1)/9]

```

> {{11, 1}, {41, 1}, {71, 1}, {239, 1}, {271, 1}, {4649, 1}, {9091, 1}, {123551, 1}, {909091, 1}, {4147571, 1}, {102598800232111471, 1}, {265212793249617641, 1}}

---

**Novel prime factors of R70**

```
Complement@@Reverse@FactorInteger[(10^Range@#-1)/9][[;;,;;,1]]&[70]

```

> {4147571, 265212793249617641}

# Answer
> 2 votes
# LabVIEW, 33 LabVIEW Primitives

19 takes forever...

Work by saving all Primes and deleting elements from the last set when they are found in the other array.

# Answer
> 2 votes
# MATL, 25 bytes

This works for input up to `16`:

```
10,i:^9/Y[t0)Yftb!w\~s1=)

```

The following version uses **31 bytes** and works up to `18`. For `19` it requires about 4 GB memory (I haven't been able to run it).

```
10,i:^9/Y[t0)5X2Y%Yfotb!w\~s1=)

```

### Example

```
>> matl
 > 10,i:^1-,9/t0)5X2Y%Yfotb!w\~s1=)
 >
> 6
7 13

```

### Explanation

Consider for concreteness input `6`. First the prime divisors of `111111` are computed; in this case the results are `3`, `7`, `11`, `13`, `37`. Then the modulo operation (division remainder) is computed for all combinations of numbers `1`, `11`, ... `111111` and the computed divisors. This exploits MATL's implicit singleton expansion. The result is in this case a `6`x`5` matrix, with each column corresponding to one of the divisors. Accepted divisors (columns) are those for which only `1` value (namely the last) gives zero remainder.

```
10,i:^9/Y[   % generate vector with `1`, `11`, ... depending on input number, say "n"
t0)          % pick the last element: `111...1` (n ones)
5X2Y%        % * convert to uint64, so that larger numbers can be handled
Yf           % prime factors
o            % * convert to double precision, so that modulus can be done
t            % duplicate
b            % bubble up element in stack
!            % transpose
w            % swap elements in stack
\            % modulus after division (element-wise, singleton expansion)
~s           % number of zero values in each column
1=           % is equal to 1? (element-wise, singleton expansion)
)            % index divisors with that logical index

```

(\*) Removed in short version

# Answer
> 2 votes
# Julia, 103 bytes

```
R(n)=[keys(factor((10^n-1)÷9))...]
n->(r=R(n);isprime(r)?r:setdiff(r,reduce(vcat,[R(i)for i=1:n-1])))

```

This is an unnamed function that calls a helper function `R`. To call it, give the main function a name, e.g. `f=n->...`.

Ungolfed:

```
function R(n::Integer)
    collect(keys(factor((10^n - 1) ÷ 9)))
end

function f(n::Integer)
    r = R(n)
    if isprime(r)
        r
    else
        setdiff(r, reduce(vcat, [R(i) for i = 1:n-1]))
    end
end

```

# Answer
> 1 votes
# J, 24 bytes

```
[:({:-.}:)@:q:[:+/\10^i.

```

Expects extended-precision numerics after 6 (e.g. `19x` instead of `19`).

Try it online!

There's probably a shorter way to generate the repunits which avoids the caps, too.

# Explanation

```
[: ({: -. }:) @: q: [: +/\ 10 ^ i.
                                i. Range [0, input)
                           10 ^    10 raised to the power of the range
                       +/\         Running sum of this list (list of repunits)
                 q:                Prime factors of the repunits
              @:                   Composed with
   ({: -. }:)                      Unique prime factors of last repunit
    {:                              Factors of last repunit (tail of matrix)
       -.                           Set subtraction with
          }:                        Rest of the matrix (curtail)

```

### How it works, visually

I think that these sorts of visual explanations are easier to stomach for those who don't know J. These are results from the REPL.

```
   10 ^ i.6
1 10 100 1000 10000 100000

   +/\ 10 ^ i. 6
1 11 111 1111 11111 111111

   q: +/\ 10 ^ i. 6
 0   0  0  0  0
11   0  0  0  0
 3  37  0  0  0
11 101  0  0  0
41 271  0  0  0
 3   7 11 13 37

   ({: -. }:) q: +/\ 10 ^ i. 6
7 13

```

---
Tags: code-golf, math, number-theory, primes, factoring
---


# Question
Title: Advent Challenge 7: Balance the storage carts!
\<\< Prev Next \>\>

After some careful analysis, Santa was able to determine the dock size ranges and get the presents into the correct transportation dock.

Now, he needs you to help him balance out the transportation carts and place the presents in them in the most balanced fashion.

# Challenge

You will be given the size of (the base of) the transportation cart as `(width, height)` and a list of all of the presents' sizes as integers.

An arrangement of presents on the transportation cart will have a certain center of mass, which should be as close to the center as possible (in other words, you want to minimize the Euclidean Distance between the center of mass and `(width / 2, height / 2)`. The center of mass can be calculated by the following formula.

# Formula

Let `{(x_1, y_1), (x_2, y_2), ..., (x_i, y_i)}` be the coordinates of the centers of the presents (these coordinates may be half-numbers (so #.5) if the size is even). Let `s = {s_1, s_2, ..., s_i}` be the sizes of the presents.

Then, the center of mass is at `((x_1 × s_1 + x_2 × s_2 + ... + x_i × s_i) / sum(s), (y_1 × s_1 + y_2 × s_2 + ... + y_i × s_i) / sum(s))`.

# Task

Given the dimensions of the transportation cart `m × n` and the sizes of the presents, determine the positions of the presents in the most balanced arrangement. Note that presents may not intersect; each present with size `s` is an `s × s × s` cube.

# Formatting Specifications

You may give the output in any reasonable format; for example, the positions of the top-left corners of the presents, the centers, an `m × n` matrix of integers indicating what present covers each space, etc. If there are multiple valid answers, you may return just one (does not have to be deterministic) or you can return them all.

# Test Cases

```
Input
Output (given as the `m × n` matrix as ASCII-art)
----
5 × 5, 2, 2, 2, 2
11022    00220
11022    11220
00000 or 11033
33044    04433
33044    04400
----
5 × 7, 1, 1, 1, 2, 2
1000022
0000022
0003000 (or others)
4400000
4400005
----
3 × 4, 3
1110
1110
1110
---
3 × 4, 2, 1
0110
0110
0020

```

Please feel free to correct me if my test cases are not correct.

# Rules

* Standard Loopholes Apply
* This is a , so the shortest answer in bytes wins
* No answer will be accepted
* There will always be at least one solution to all of the inputs

Note: I drew inspiration for this challenge series from Advent Of Code. I have no affiliation with this site

You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge here.

Happy Golfing!

# Answer
> 3 votes
# Python 3, ~~533~~ ~~494~~ 476 bytes

```
from numpy import*
def o(a,v,t=[],n=1):
 if len(v)<1:return[[sum((d-e)**2for d,e in zip([sum(a)/sum(r)for a in zip(*[[a*k for k in b]for a,b in zip(r,t)])],[-~a/2 for a in a.shape]))**.5,a]]
 s,k=v[0],[[]]
 for p,i,j,l in[[copy(a),i,j,(i-~s/2,j-~s/2)]for i in range(a.shape[0]-s+1)for j in range(a.shape[1]-s+1)if all(a[i:i+s,j:j+s]<1)]:p[i:i+s,j:j+s]=n;k+=o(p,v[1:],t+[l],n+1)
 return k
w=input()
q,r=w[0],w[1:]
print(min([a for a in o(zeros(q),r)if a],key=lambda a:a[0])[1])

```

Try it online!

I used the `numpy` library in Python. It is a very popular Python library and it specializes matrix/multi-dimensional array manipulation.

Mine finds a different, but equally valid, solution. I did double check my work and, when I tried to find all solutions, it did find the one presented in the question as well.

Basic methodology is to bruteforce it. So, every possible present location is checked, then the one with the least distance between it's center of gravity and the center of the slay is returned (or at least one of the possible solutions).

---

# Pseudo-Ungolfed Version

I figured providing the ungolfed version would help people understand the algorithm. I have made marginal improvements since this version, but this should give you a jump start in understanding it:

```
import numpy as np

with open("test.txt","w") as fo:
    input = lambda: [[3,4], 2, 1]

    def bruteForce(array, size, number):
        for i in range(array.shape[0]-size+1):
            for j in range(array.shape[1]-size+1):
                if np.all(array[i:i+size,j:j+size] == 0):
                    temp = np.copy(array)
                    temp[i:i+size,j:j+size] = number
                    yield temp, (i+(size+1)/2,j+(size+1)/2)

    #y, x because of how numpy works
    #euclid = https://codegolf.stackexchange.com/a/70536/67929
    def recursiveCheck(array,presents,presentLocations=[],number=1,currentMin=[10000,[]]):
        global rest, size
        if (len(presents) == 0):
            centerI = sum(a*b[0] for a,b in zip(rest,presentLocations)) / sum(rest)
            centerJ = sum(a*b[1] for a,b in zip(rest,presentLocations)) / sum(rest)
            euclid = lambda a,b:sum((d-e)**2for d,e in zip(a,b))**.5
            centerDelta = euclid([centerI,centerJ],[(a+1)/2 for a in array.shape])
            if centerDelta <= currentMin[0]:
                currentMin[0] = centerDelta
                currentMin[1] = array
                fo.write(repr(array) + "\n")
                fo.write(repr(presentLocations) + "\n")
                fo.write(repr([centerI,centerJ]) + "\n")
                fo.write(repr(centerDelta) + "\n")
            return
        for potentialPresentArray, newPresentLocation in bruteForce(array,presents[0],number):
            recursiveCheck(potentialPresentArray,presents[1:],presentLocations+[newPresentLocation],number+1,currentMin)

    suMatrix = input()
    size = suMatrix[0]
    rest = suMatrix[1:]
    recursiveCheck(np.zeros(size),rest)

```

---

# Credits

I used a response by CarpetPython to aide me in creating a euclidean distance calculation in a minimal amount of bytes.

Mr. Xcoder reduced it by 28 bytes.

---
Tags: code-golf, math, array, matrix
---


# Question
Title: Advent Challenge 8: Storage Cart Transport Planning!
\<\< Prev

Thanks to the PPCG community, Santa now has balanced his storage carts. Now, he needs to move them into the transport docks so that they can be sent to the loading bays. Unfortunately, the tracks to move the carts around are a mess, and he needs to figure out how to get them all around without them crashing together!

# Challenge

You will be given the tracks for each of the carts as lists of "labels" (or stations). The carts must be moved such that at any time frame, no two carts are on the same label/station. Essentially, the carts move between positions that each have a unique label.

# Task

Given the tracks for each of the carts as a list of lists of labels (which are all positive integers), determine when each cart should be released in order to send all the carts to their destinations safely in the shortest time possible.

Here's an explanation of how the entire track system works. Let's say cart `i` is released at time `t_i` onto a track with labels `T_i_1, T_i_2, ..., T_i_n`. Then, during `t_1` to `t_i-1`, cart `i` is not on the grid and can be ignored.

At time frame `t_i`, the cart is on label `T_i_1`, and for each time frame `t_k` from `t_i` to `t_i+n` (half-inclusive), the cart is on label `T_i_k+1`.

For all time frames after and including `t_i+n`, the cart is at its destination and is no longer on the grid.

The total amount of time `t_T` taken is the last time frame with a cart still on a track in the system.

# Specifications

Given a track system, return a list of time frames `[t_1, t_2, ..., t_n]` where the `i`th cart starts at time `t_i`, such that no other arrangement would allow the carts to safely get to their destinations with a lesser total amount of time.

In terms of "safely", if at any time frame from `t_1` to `t_T` there is more than one cart on any label, then they collide and the arrangement was not "safe". Note that two carts can move from `a, b` to `b, a` and still be "safe" because the tracks are 2-way.

# Formatting Specifications

Input will be given as a matrix of positive integers in any reasonable format. Output should be given as a list of positive integers in any reasonable format. You may give output in zero-indexed time frames, so then the output would be a list of non-negative integers in any reasonable format.

# Rules

* Standard Loopholes Apply
* This is a so the shortest answer in bytes wins
* No answer will be accepted

# Test Cases

```
Input -> Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> [1, 1, 1]
[[1, 2, 3], [1, 2, 3]] -> [1, 2]
[[1, 2, 3], [3, 2, 1]] -> [1, 2]
[[1, 2, 3, 4], [4, 3, 2, 1]] -> [1, 1]
[[1, 1, 1], [1, 1, 1]] -> [1, 4]
[[1, 2, 3, 4], [2, 4, 3, 1]] -> [2, 1]
[[1, 2, 3, 4, 5, 6, 7], [2, 3, 3, 4], [5, 4, 3]] -> [1, 3, 4]
[[1, 2, 3, 4, 4], [1, 2, 3, 5, 4], [1, 2, 3, 4, 5]] -> [2, 3, 1]

```

Note: I drew inspiration for this challenge series from Advent Of Code. I have no affiliation with this site

You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge here.

Happy Golfing!

# Answer
> 4 votes
# JavaScript (ES7), 172 bytes

Returns an array of 0-indexed time frames.

```
a=>(g=k=>a.map((a,i)=>[l=a.length+1,i,a,L=L<l?l:L]).sort(([a],[b])=>a-b).every(([,n,b],i)=>b.every((c,t)=>o[t+=A[n]=k/L**i%L|0]&1<<c?0:o[t]|=1<<c),o=[],A=[])?A:g(k+1))(L=0)

```

*NB*: This can only work with labels in \[0-31\]. This is a JS limit, not a limit of the algorithm.

### Test cases

```
let f =

a=>(g=k=>a.map((a,i)=>[l=a.length+1,i,a,L=L<l?l:L]).sort(([a],[b])=>a-b).every(([,n,b],i)=>b.every((c,t)=>o[t+=A[n]=k/L**i%L|0]&1<<c?0:o[t]|=1<<c),o=[],A=[])?A:g(k+1))(L=0)

console.log(JSON.stringify(f([[1, 2, 3], [4, 5, 6], [7, 8, 9]])))                   // -> [0, 0, 0]
console.log(JSON.stringify(f([[1, 2, 3], [1, 2, 3]])))                              // -> [0, 1] or [1, 0]
console.log(JSON.stringify(f([[1, 2, 3], [3, 2, 1]])))                              // -> [0, 1] or [1, 0]
console.log(JSON.stringify(f([[1, 2, 3, 4], [4, 3, 2, 1]])))                        // -> [0, 0]
console.log(JSON.stringify(f([[1, 1, 1], [1, 1, 1]])))                              // -> [0, 3] or [3, 0]
console.log(JSON.stringify(f([[1, 2, 3, 4], [2, 4, 3, 1]])))                        // -> [1, 0]
console.log(JSON.stringify(f([[1, 2, 3, 4, 5, 6, 7], [2, 3, 3, 4], [5, 4, 3]])))    // -> [0, 2, 3]
console.log(JSON.stringify(f([[1, 2, 3, 4, 4], [1, 2, 3, 5, 4], [1, 2, 3, 4, 5]]))) // -> [1, 2, 0]
```

### Commented

```
a => (                         // given a = array of tracks
  g = k =>                     // g = recursive function taking k = counter
    a.map((t, i) => [          // map each track t in a to a new entry made of:
      l = t.length + 1,        //   - its length + 1 (l)
      i,                       //   - its original index in the input array
      t,                       //   - the original track data
      L = L < l ? l : L        //   and update the maximum track length L
    ])                         // end of map()
    .sort(([a], [b]) =>        // let's sort the tracks from shortest to longest
      a - b                    // so that solutions that attempt to delay short
    )                          // tracks are tried first
    .every(([, n, b],          // for each track b with an original position n,
                      i) =>    // now appearing at position i:
      b.every((c, t) =>        //   for each label c at position t in b:
        o[t += A[n] =          //     add to t the time frame A[n] corresponding
          k / L**i % L | 0     //     to this position (i) and this combination (k)
        ] & 1 << c ?           //     if the station c is already occupied at time t:
          0                    //       make every() fail
        :                      //     else:
          o[t] |= 1 << c       //       mark the station c as occupied at time t
      ),                       //   end of inner every()
      o = [],                  //   start with: o = empty array (station bitmasks)
      A = []                   //               A = empty array (time frames)
    ) ?                        // end of outer every(); if successful:
      A                        //   return A
    :                          // else:
      g(k + 1)                 //   try the next combination
)(L = 0)                       // initial call to g() + initialization of L

```

---
Tags: code-golf, array
---


title: Iterated phi sequence

text:
# Question
Title: Iterated phi sequence
Related: Iterated phi(n) function.

Your challenge is to compute the iterated phi function:

```
f(n) = number of iterations of φ for n to reach 1.

```

Where `φ` is Euler's totient function.

Related OEIS.

Here's the graph of it:

---

### Rules:

Your goal is to output `f(n)` from `n=2` to `n=100`.

This is code-golf, so shortest code wins.

Here's the values you can check against:

```
1, 2, 2, 3, 2, 3, 3, 3, 3, 4, 3, 4, 3, 4, 4, 5, 3, 4, 4, 4, 4, 5, 4, 5, 4, 4, 4, 5, 4, 5, 5, 5, 5, 5, 4, 5, 4, 5, 5, 6, 4, 5, 5, 5, 5, 6, 5, 5, 5, 6, 5, 6, 4, 6, 5, 5, 5, 6, 5, 6, 5, 5, 6, 6, 5, 6, 6, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 5, 6, 7, 5, 7, 5, 6, 6, 7, 5, 6, 6, 6, 6, 6, 6, 7, 5, 6, 6

```

# Answer
# Haskell, ~~53~~ 52 bytes

Thanks nimi for saving 1 byte!

```
f<$>[2..100]
f 1=0
f n=1+f(sum[1|1<-gcd n<$>[1..n]])

```

Try it online!

`sum[1|1<-gcd n<$>[1..n]]` gives `φ(n)` (Taken from flawr, thanks!)

`f` is a recursive function that calculates `1+φ(n)` if n is not `1`, and outputs `0` if `n` is `1`, as there are no more iterations to be taken to reach `1`

Finally `f<$>[2..100]` creates a list of `f` applied to each element of `[2..100]`
> 10 votes

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

```
99:Q"@`_Zptq}x@

```

Try it online!

### Explanation

```
99:       % Push [1 2 ... 99]
Q         % Add 1 element-wise: gives [2 3 ... 100]
"         % For each k in that array
  @       %   Push k
  `       %   Do...while
    _Zp   %     Euler's totient function
     tq   %     Duplicate, subtract 1. This is the loop condition
  }       %   Finally (execute on loop exit)
  x       %     Delete
  @       %     Push latest k
          %   End (implicit)
          % End (implicit)
          % Display stack (implicit)

```

## Old version, 16 bytes

```
99:Qt"t_Zp]v&X<q

```

Try it online!

### Explanation

```
99:       % Push [1 2 ... 99]
Q         % Add 1 element-wise: gives [1 2 ... 100]
t"        % Duplicate. For each (i.e. do the following 100 times)
  t       %   Duplicate
  _Zp     %   Euler's totient function, element-wise
]         % End
v         % Concatenate vertically. Gives a 100×100 matrix
&X<       % Row index of the first minimizing entry for each column.
          % The minimum is guaranteed to be 1, because the number of
          % iterations is more than sufficient.
q         % Subtract 1. Display stack (implicit)

```
> 7 votes

# Answer
# Haskell, ~~70 69~~ 68 bytes

The function `(\n->sum[1|1<-gcd n<$>[1..n]])` is the totient function, which we repeatedly apply in the anonymous function. Thanks @laikoni for -1 byte!

EDIT: I just found out @xnor used this exact totient function in a previous challenge.

```
length.fst.span(>1).iterate(\n->sum[1|1<-gcd n<$>[1..n]])<$>[2..100]

```

Try it online!
> 7 votes

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

```
³ḊÆṪƬ>1S

```

Try it online!

-1 byte thanks to HyperNeutrino!

-1 byte thanks to Mr. Xcoder!

-1 byte thanks to Dennis

## How it works

```
³ḊÆṪƬ>1S - Main link. No arguments
³        - Yield 100
 Ḋ       - Dequeue. Creates the list [2, 3 ... 99, 100]
    Ƭ    - Until the following produces a repeated value, collecting each loop:
  ÆṪ     -   Totient of each
     >1  - Greater than one?
       S - Sum the columns

```
> 6 votes

# Answer
# APL (Dyalog), ~~50~~ ~~29~~ 25 bytes

Look 'ma, no built-in totient!

*4 bytes saved thanks to @H.PWiz*

```
{⍵=1:0⋄1+∇+/1=⍵∨⍳⍵}¨1+⍳99

```

Try it online!

**How?**

*Apparently I went for the longer (and harder) totient formula first. See revisions history.*

`⍳⍵` \- `1` to `n`

`⍵∨` \- gcd with `n`

`1=` \- equal to 1?

`+/` \- sum 'em all

This is the totient. All the rest is wrapper for the counting (`1+∇`) and applying on the range `2..100` (`¨1+⍳99`).
> 6 votes

# Answer
# Mathematica, 44 bytes

```
(i=-1;#+1//.x_:>EulerPhi[++i;x];i)&~Array~99

```

-10 bytes from @Misha Lavrov
-2 bytes from @user202729

Try it online!
> 5 votes

# Answer
# JavaScript (ES6), ~~115~~ ... ~~104~~ 99 bytes

Hard-coding might be shorter, but let's try a purely mathematical approach.

```
f=n=>n>97?6:(P=(n,s=0)=>k--?P(n,s+(C=(a,b)=>b?C(b,a%b):a<2)(n,k)):s>1?1+P(k=s):1)(k=n+2)+' '+f(-~n)

console.log(f())
```
> 4 votes

# Answer
# J REPL, 23 bytes

```
<:#@(5&p:^:a:)"0|2+i.99

```

I haven’t checked, but this probably works in regular J if you define it as a noun (I golfed this on my phone on the REPL).

Built-ins, yo.

I’d say that there are *at least* 2-3 bytes to shave off (off-by-one because of the way `a:` works, having to use `|` as a noop, etc.).
> 4 votes

# Answer
# Python 2, 80 bytes

```
n,_=r=2,0;exec'r+=r[sum(k/n*k%n>n-2for k in range(n*n))]+1,;print r[n];n+=1;'*99

```

Try it online!
> 4 votes

# Answer
# Python 2, 82 bytes

```
l=0,1
exec"n=len(l);p=2\nwhile n%p:p+=1\nl+=l[p-1]+l[n/p]-n%4%3/2,;print l[n];"*99

```

Try it online!

This uses the observations that:

* `f(a*b) = f(a) + f(b) - 1`, except the `-1` is omitted if `a` and `b` are both even
* `f(p) = f(p-1) + 1` when `p` is prime, with `f(2)=1`

These imply that if `n` has prime factorization `n = 2**a * 3**b * 5**c * 7**d * 11**e * ...`, then `f(n) = max(a,1) + b + 2*c + 2*d + 3*e + ...`, where each `p>2` in the factorization contributes `f(p-1)`.

I'm not sure if these continue to hold past `n=100`, but if they do, they give a way to define and calculate `f` without using `φ`.
> 3 votes

# Answer
# Husk, ~~10~~ 17 bytes

```
mö←LU¡Sȯṁε⌋ḣtḣ100

```

Try it online!

**Edit**: +7 bytes for actually mapping the function over the range that was asked for, before it was only the function computing A003434.

### Explanation

The following computes A003434:

```
←LU¡S(ṁ(ε⌋))ḣ -- takes a number as input, for example: 39
   ¡          -- iterate the following function on the input: [39,24,8,4,2,1,1,1..]
    S(     )ḣ --   with itself (x) and the range [1..x]..
      ṁ(  )   --   ..map and sum the following
        ε⌋    --     0 if gcd not 1 else 1
  U           -- longest unique prefix: [39,24,8,4,2,1]
 L            -- length: 6
←             -- decrement: 5

```

The `m(....)ḣ100` part just map that function over the range \[2..100\], not sure how I missed that part before :S
> 3 votes

# Answer
# PowerShell, 110 bytes

```
$a=,0*101;2..100|%{$i=$_;for($z=$j=0;++$j-lt$i;$z+=$k-eq1){for($k=$j;$j%$k-or$i%$k;$k--){}};($a[$i]=$a[$z]+1)}

```

Try it online!

Mathematical approach.

Actually, looking through it, very similar to the C answer, but developed independently. Creates an array of `0`s, loops from `2` to `100`, then calculates `phi` using the `gcd` formulation. The part in parens at the end both saves the result into `$a` for the next go-round, and places a copy on the pipeline, which results in the implicit output.

---

### PowerShell, 112 bytes

```
"122323333434344534444545444545555545455645555655565646555656556656665656565656656757566756666667566"-split'(.)'

```

Try it online!

Hard-coded. Ho-hum. ~~Shorter than I could get a mathematical approach by about 10-15 bytes.~~
> 2 votes

# Answer
# Bubblegum, 49 bytes

```
00000000: 5d88 0511 0020 0003 ab2c 024e ff64 e8a3  ].... ...,.N.d..
00000010: 379f 956b f05d 206c 0545 7274 743a b876  7..k.] l.Ertt:.v
00000020: 2267 27f9 9f4d 9b9d fc85 e7e6 994d 6eb0  "g'..M.......Mn.
00000030: 2b                                       +

```

Try it online!
> 2 votes

# Answer
# Python 2, 83 bytes

```
n=2
exec"print len(bin(n))-3+n%2-~n%9/8-(0x951a5fddc040419d4005<<19>>n&1);n+=1;"*99

```

Try it online!

Combines a heuristic estimate with a hardcoded constant that corrects each estimate as either `-0` or `-1`.
> 2 votes

# Answer
# PHP, 98 bytes

```
1,2,<?=join(',',str_split(unpack('H*','##3444E4DEEDEEUUEEVEUVUVVFUVVUfVfVVVVVegWVgVffgV')[1]))?>,6

```

Try it online!

I packed all digits into a binary string. After unpacking it, converting it to a an array and then mergin the array again, i only had to prepend the 1,2 and append the 6 as those wouldnt fit or caused a control code to appear.
> 1 votes

# Answer
# Perl 6, 47 bytes

```
map {($_,{+grep 1==* gcd $_,^$_}...1)-1},2..200

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 11 bytes

```
тL¦ε[DNs#sÕ

```

Try it online!

**Explanation**

```
тL¦           # push range [2 ... 100]
   ε          # apply to each
    [         # start a loop
     D        # duplicate the current number
      N       # push the loop iteration counter
       s      # swap one copy of the current number to the top of the stack
        #     # if true, break the loop
         s    # swap the second copy of the current number to the top of the stack
          Õ   # calculate eulers totient

```
> 1 votes

# Answer
# C, 112 bytes

```
a[101];f(i,j,k,t){for(a[i=1]=0;i++<100;printf("%d ",a[i]=a[t]+1))for(t=j=0;++j<i;t+=k==1)for(k=j;j%k||i%k;k--);}

```

Ungolfed:

```
a[101];
f(i,j,k,t){
    for(a[1]=0,i=2;i<=100;i++) {   // initialize
        for(t=j=0;++j<i;t+=k==1)   // count gcd(i, j) == 1 (t = phi(i))
            for(k=j;j%k||i%k;k--); // calculate k = gcd(i, j)
        printf("%d ",a[i]=a[t]+1); // print and store results
    }
}

```

Try it online!
> 1 votes

# Answer
# Alumin, 87 bytes

```
hhhhhdadtqdhcpkkmzyhqkhwzydqhhwdrdhhhwrysrshhwqdrybpkshehhhwrysrarhcpkksyhaydhehycpkkmr

```

Try it online!

## Explanation

```
hhhhhdadt      CONSTANT 100

RANGE FROM 100 to 0
q
  dhc
p

REMOVE 0 AND 1
kk

OVER EACH ELEMENT...
m
  zyh
  q
    kh
    wzyd
    q
      DUPLICATE TOP TWO ELEMENTS...
      hhwdrdhhhwrysrshhw
      GCD...
      qdryb
    p
    ks
    he
    hhhw
    ry
    s
    rarhc
  p
  IS IT ONE? IF SO TERMINATE (FIXPOINT)
  kksyhaydhehyc
p
kk
m
REVERSE THE VALUES
r

```
> 0 votes

# Answer
# Pyth, 38 bytes (not competitive)

```
.e-+1sl+1kb_jC"Éõ4ÕYHø\\uÊáÛ÷â¿"3

```

Try it on the Pyth Herokuapp, because it doesn't work on TIO for whatever reason.

I have no doubt the explicit Pyth solution is smaller, but I wanted to see how small I could get the code by compressing the sequence, and learn Pyth I guess. This uses the fact that an upper bound of the sequence is `log2(n)+1`.

## Explanation

```
.e-+1sl+1kb_jC"Éõ4ÕYHø\\uÊáÛ÷â¿"3
             C"Éõ4ÕYHø\\uÊáÛ÷â¿"   interpret string as base 256 integer
            j                   3  convert to array of base 3 digits
           _                       invert sequence (original had leading 0s)
.e                                 map with enumeration (k=index, b=element)
       +1k                                   k+1
     sl                            floor(log(   ))
   +1                                             +1
  -       b                                         -b

```

I got the compressed string via `Ci_.e+1-sl+1ksb"122323333434344534444545444545555545455645555655565646555656556656665656565656656757566756666667566"3`, which is just the opposite of the code above with a few type conversions.
> 0 votes

# Answer
# Ohm v2, 41 bytes

```
“ ‽W3>€þΣÌιZ§Á HgüυH§u·β}Bā€ΣNπáÂUõÚ,3“8B

```

Try it online!

Literally completely hardcoded... I actually took the sequence above, stripped everything that wasn't a number, interpreted it as base 8, then turned it into Ohm's built-in base 255 number representation. That's what the quotes do. Then, the program simply turns that into base 8 again.
> 0 votes

---
Tags: code-golf, math, sequence, kolmogorov-complexity, number-theory
---


title: HSL to RGB values

text:
# Question
Title: HSL to RGB values
> The main purpose of the RGB (Red Green Blue) color model is for the sensing, representation and display of images in electronic systems, such as televisions and computers
>
> HSL (Hue Saturation Lightness) is an alternative color model, designed in the 1970s by computer graphics researchers to more closely align with the way human vision perceives color-making attributes

Here are the wiki articles for RGB and HSL. It is common for graphics programs to do the calculations in HSL, and later convert to the preferred format for most screens: RGB.

The task is to write a function/program that takes HSL as an input and outputs RGB.

You can pick your preferred representation for I/O, as long as its consistent between them.

For example, they can be an array/tuple with 3 elements or an object with 3 properties named `h`, `s`, and `l`, but I'll accept other clever variations, like receiving the hsl as an integer (losing precision) and outputting an rgb integer.

The input can be assumed to be safe in range and format, both of which you can decide. I strongly suggest either the ranges `0-1 0-1 0-1` or `0-360 0-100 0-100` for hsl, and `0-1 0-1 0-1` or `0-255 0-255 0-255` for rgb.

Each answer is required to specify both of the above, and do put various variations in your answers if you're particularly proud of them, even if they don't have less characters than your other variations. Put the smallest on top.

Pseudo test cases for `0-360 0-100 0-100``0-255 0-255 0-255`

```
h   s   l   → r   g   b

0   0   0   → 0   0   0
90  56  17  → 43  68  19
202 19  39  → 81  104 118
72  55  26  → 88  103 30

```

The formulae for the conversion can be found here:

This as a nice way to visualize the conversion:

# Answer
> 8 votes
# JavaScript (ES6), ~~98~~ ~~95~~ 94 bytes

Takes **H** in **\[0,360)** and **S**/**L** in **\[0,1)**. Outputs **R**, **G** and **B** as an array of 3 floats in **\[0,1)**.

```
(H,S,L)=>[5,3,1].map(i=>A(L*2)*S*([1,Y,0,0,Y,1][(i-~H)%6]-.5)+L,Y=(A=n=>n>1?2-n:n)((H/=60)%2))

```

### Test cases

This snippet converts the results back into **\[0,255\]**.

```
let f =

(H,S,L)=>[5,3,1].map(i=>A(L*2)*S*([1,Y,0,0,Y,1][(i-~H)%6]-.5)+L,Y=(A=n=>n>1?2-n:n)((H/=60)%2))

format = a => JSON.stringify(a.map(v => v * 255 + 0.5 | 0))

console.log(format(f(  0, 0.00, 0.00))) //  0   0    0
console.log(format(f( 90, 0.56, 0.17))) // 43  68   19
console.log(format(f(202, 0.19, 0.39))) // 81  104 118
console.log(format(f( 72, 0.55, 0.26))) // 88  103  30
```

### How?

**Initialization code**

```
Y = (                  // we compute Y = 1 - |(H/60) mod 2 - 1| = X / C
  A = n =>             // A = function that returns 1 - |n - 1|
    n > 1 ?            //   first compare n with 1
      2 - n            //     which allows to simplify the formula to either 2 - n
    :                  //   or
      n                //     just n
)((H /= 60) % 2)       // divide H by 60 and compute Y = A(H % 2)

```

**Main code**

```
[5, 3, 1].map(i =>     // for each i in (5, 3, 1):
  A(L * 2) * S * (     //   compute (1 - |2L - 1|) * S (this is C), and multiply it by:
    [1, Y, 0, 0, Y, 1] //     either 0, 1 or Y (let's call this factor K), picked from
    [(i - ~H) % 6]     //     a cyclic sequence of period 6, using i and ~H (-6 ≤ ~H ≤ -1)
    - .5               //     minus 1/2
  )                    //   this gives: C(K - 1/2) = CK - C/2, where CK = 0, C or X
  + L                  //   we add L, leading to CK - C/2 + L = CK + m
)                      // end of map() --> returns [R, G, B]

```

**Permutations of (0,C,X)**

The slightly tricky part is to generate the correct permutation of **(0,C,X)** according to the angle of the hue component. As shown in the following figure, each column value is picked from the same cycling sequence of period **6**, starting at different offsets. In the above code, we're using **-~H** instead of just **+H** because we need to coerce **H** to an integer. Hence the offsets **(5,3,1)** instead of **(0,4,2)**.

```
                       C,X,0,0,X,C,C,X,0,0,X,C, ...
 +------> C,X,0,0,X,C  <--------->                  offset = 0, (0 - 1) mod 6 = 5
 | +----> X,C,C,X,0,0          <--------->          offset = 4, (4 - 1) mod 6 = 3
 | | +--> 0,0,X,C,C,X      <--------->              offset = 2, (2 - 1) mod 6 = 1
 | | |
(C,X,0) for   0 ≤ H <  60
(X,C,0) for  60 ≤ H < 120
(0,C,X) for 120 ≤ H < 180
(0,X,C) for 180 ≤ H < 240
(X,0,C) for 240 ≤ H < 300
(C,0,X) for 300 ≤ H < 360

```

# Answer
> 5 votes
# Python 2, 32 bytes

```
from colorsys import*;hls_to_rgb

```

Try it online!

This functionality is actually built into Python via the `hls_to_rgb` inside of the `colorsys` library. The format mine inputs is a 0-1 range of HLS (instead of HSL, both are common acronyms for the same thing \[albeit, HSL is more common\]). And mine outputs RGB values in a tuple with a range from 0 to 1.

**Credits**

Thanks to Jonathan Allan for pointing out that I just need to import it (and then further helping me reduce byte count).

# Answer
> 4 votes
# Mathematica, 155 bytes

```
(x~Clear~c;d=Piecewise@Table[{(P=Permutations)[P@{c,x,0}][[42,i]],(i-1)<=#<i*p},{i,6}];c=(1-Abs[2#3-1])#2;x=c(1-Abs[Mod[#/(p=60),2]-1]);m=#3-c/2;(m+d)255)&

```

Try it online!

# Answer
> 4 votes
## C++, ~~228~~ 221 bytes

-7 bytes thanks to Zacharý

```
#define S(o,n)r[t[int(h[0])/60*3+o]+o-2]=(n+h[2]-c/2)*255;
void C(float*h,int*r){float g=2*h[2]-1,c=(g<0?1+g:1-g)*h[1],a=int(h[0])%120/60.f-1;int t[]={2,2,2,3,1,2,3,3,0,4,2,0,4,1,1,2,3,1};S(0,c)S(1,c*(a<0?1+a:1-a))S(2,0)}

```

The arguments are both arrays that have a minimum size of 3 elements ( i.e. `float hsl[3]` and `int rgb[3]`

Okay. Now, how does that work ? What is that long array ?

Well, it's not a long array, it's a `int` array. Joke aside, the array indicates by how many position we right shift C X and 0 when we want to select the correct permutation, + 2. Remember how R', G' and B' are selected ?

Let's say we have a "normal" order that is {C, X, 0}

Now, when the first permutation (i.e. {C,X,0}) is selected, you need to not shift, which is exactly the same thing as right shifting by 0. So the first 3 elements of the array are 0,0 and 0

For the second permutation ( {X,C,0} ), we need to right shift C by 1, and left shift X by -1, so the fourth, fifth and sixth element of the array are 1,-1 and 0

And so on...

With the case of the 3rd and 4th permutation, i need to left shift the 0 by 2, so right shift by -2. Since there are more that 2 numbers that are negative, i rather add 2 to each elements in the array and substract 2 at the runtime ( for golfing reasons, to have only whole numbers in the array ).

# Answer
> 4 votes
# Python 2, ~~119~~ 112 bytes

```
def f(h,s,l):c=(1-abs(2*l-1))*s;m=l-c/2;x=c*(1-abs(h%2-1))+m;c+=m;return[c,m,x,c,m,x,m,c,x,m][7-int(h)*5%9:][:3]

```

Try it online!

Takes input as `H=[0,6[, S=[0,1], L=[0,1]`

# Answer
> 3 votes
## HTML + JavaScript (ES6), 8 + 88 = 96 bytes

```
f=
(h,s,l)=>(p.style.color=`hsl(${h},${s}%,${l}%)`,getComputedStyle(p).color.match(/\d+/g))
```

```
<div oninput=o.textContent=f(h.value,s.value,l.value)>H: <input type=number min=0 max=360 value=0 id=h>°<br>S: <input type=number min=0 max=100 value=0 id=s>%<br>L: <input type=number min=0 max=100 value=0 id=l>%<pre id=o>0,0,0</pre>
<p id=p>
```

Takes input as an angle and two percentages. I'm scoring the HTML snippet `<p id=p>` and the JavaScript arrow function. I don't know what rounding browsers use, so my answers might differ slightly from yours.

# Answer
> 2 votes
# Swift 4, 218 bytes

Accepts HSL values in the range \[0,1\] as arguments, and returns an array containing the RGB values in the same range:

```
import Cocoa;typealias F=CGFloat;func f(h:F,s:F,l:F)->[F]{var r=F(),g=F(),b=F(),x=s*min(1-l,l),n=2*x/max(l+x,1e-9);NSColor(hue:h,saturation:n,brightness:l+x,alpha:1).getRed(&r,green:&g,blue:&b,alpha:nil);return[r,g,b]}

```

The idea is to first convert the input from HSL to HSB, then using the HSB constructor of the built-in color object in Cocoa to retrieve the RGB values.

The UIKit version is the exact same length, as the only replacements are:

* `Cocoa``UIKit`
* `NSColor``UIColor`

### Ungolfed:

```
#if os(iOS)
    import UIKit
    typealias Color = UIColor
#elseif os(OSX)
    import Cocoa
    typealias Color = NSColor
#endif

typealias F = CGFloat

func f(h: F,s: F,l: F) -> [F] {
    var r = F(), g = F(), b = F()

    let x = s * min(1 - l, l)
    let n = 2 * x / max(l + x, 1e-9)

    let color = Color(hue: h, saturation: n, brightness: l + x, alpha: 1)
    color.getRed(&r, green: &g,blue: &b, alpha: nil)

    return [r, g, b]
}

```

The following snippet can be used for testing, by just replacing the values of `h`, `s`, and `l`:

```
let h: CGFloat = 0
let s: CGFloat = 0
let l: CGFloat = 0

let result = f(h: h/360, s: s/100, l: l/100).map { Int(round($0*255)) }
print(result)

```

---

Unfortunately I can't provide a link to an online sandbox, since all of them run on Linux, which doesn't include Cocoa.

# Answer
> 2 votes
# GLSL (GL\_ES) ~~160 144 134~~ 131 bytes

Hue is in range 0-6 (saves 3 bytes)
Sat,light and rgb are 0-1

```
vec3 f(vec3 c){return mix(c.bbb,mix(clamp(vec3(-1,2,2)-abs(c.r-vec3(3,2,4))*vec3(-1,1,1),0.,1.),vec3(c.b>.5),abs(.5-c.b)*2.),c.g);}

```

Try it on book of shaders

Used colorpicker tool on a printscreen to test the output which was correct,
except a small error on 202 19 39 → 81 104 118 , which gave 80 104 118

# Answer
> 1 votes
# , 88 bytes

```
function(h,s,l){v=(2*l+s*(1-abs(2*l-1)))/2;col2rgb(hsv(h,ifelse(v==0,v,(2*(v-l))/v),v))}

```

Try it online!

This function takes as input the H, S, and L values as 0-1 ranged values and outputs the RGB values as 0-255 ranged values. It converts the HSL representation to an HSV representation, then uses `hsv()` to convert the HSV representation to an R color (i.e. hex representation -- #rrggbb), then uses `col2rgb()` to convert the R color to RGB values.

# Answer
> 1 votes
# Jelly,  ~~39~~  32 bytes

-1 thanks to caird coinheringaahing (`%2` is just )
-1 and/or inspiration for -4 thanks to caird coinheringaahing too!

```
Ḥ;Ḃ’AC×©"⁵×\;0+³_®H¤⁴Ḟị336Œ?¤¤œ?

```

A full program taking three command line arguments:

* `L`, `H`, `S` in the ranges `[0,1)`, `[0,6)`, and `[0,1)` respectively

which prints a list giving the RGB format as

* `[R, G, B]` with each of the three values in the range `[0,1]`

Note: `H` may also wrap just like `[0,360)` would.

**Try it online!**

### How?

```
Ḥ;Ḃ’AC×©"⁵×\;0+³_®H¤⁴Ḟị336Œ?¤¤œ? - Main link: number, L (in [0,1]); number, H (in [0,6))
Ḥ                                - double                 =     2L
  Ḃ                              - modulo by 2            =              H%2
 ;                               - concatenate            = [   2L   ,   H%2]

   ’                             - decrement              = [   2L-1 ,   H%2-1]
    A                            - absolute               = [  |2L-1|,  |H%2-1|]
     C                           - complement             = [1-|2L-1|,1-|H%2-1|]
                                 -                        = [C/S     ,C/X]
         ⁵                       - 3rd program argument   = S  (in [0,1])
        "                        - zip with:
      ×                          -   multiplication       = [C,C/X]
       ©                         -   (copy the result, C, to the register)
           \                     - cumulative reduce with:
          ×                      -   multiplication       = [C, C/X*C] = [C,X]
            ;0                   - concatenate zero       = [C,X,0]
               ³                 - 1st program argument   = L
              +                  - add (vectorises)       = [C+L,X+L,L]
                   ¤             - nilad followed by link(s) as a nilad:
                 ®               -   recall from register = C
                  H              -   halve                = C/2
                _                - subtract               = [C+L-C/2,X+L-C/2,L-C/2]
                             ¤   - nilad followed by link(s) as a nilad:
                    ⁴            -   2nd program argument = H
                     Ḟ           -   floor                = floor(H)
                            ¤    -   nilad followed by link(s) as a nilad:
                       336       -     literal 336
                          Œ?     -     Shortest permutation of natural numbers with a
                                 -     lexicographical index of 336 in all permutations
                                 -     thereof            = [3,5,6,4,2,1]
                      ị          -   index into (1-indexed & modular)
                              œ? - get that permutation of [C+L-C/2,X+L-C/2,L-C/2]
                                 - implicit print

```

---
Tags: code-golf, conversion, color
---


title: Make a Bit Continent

text:
# Question
Title: Make a Bit Continent
Let's imagine we have a matrix of bits (which contains at least one `1`):

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

```

We want to set some of the bits in this matrix such that it forms a contiguous blob of `1`s, in which every `1` is directly or indirectly connected to every other `1` through orthogonal movement:

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

```

(You can see this more clearly by searching for `1` with your browser's "find" feature.)

However, we also want to minimize the number of bits that we set.

## The Task

Given a matrix (or array of arrays) of bits or booleans, return the minimum number of bits that need to be set to create a contiguous continent of `1`s. It should be possible to get from one set bit in the matrix to another by only traveling in an orthogonal direction to other set bits.

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

## Test Cases

```
0 1 0 1 1 0 1 0 0 1 0
0 1 0 1 0 0 1 0 1 1 0
0 0 1 0 1 1 0 1 0 1 0
1 1 0 0 1 0 0 1 1 0 1
0 0 0 1 0 1 1 0 0 1 0
=> 6

1 0 0 0 0 0 1 0 0
1 1 0 0 1 1 1 0 0
1 1 1 0 1 1 1 1 1
0 1 0 0 0 0 0 0 0
0 0 0 0 0 1 1 1 1
0 1 0 0 0 0 1 1 0
1 0 0 0 0 0 1 0 0
=> 4

0 0 0 1 1 1 0 1 1
0 0 1 0 0 0 0 1 0
0 0 1 1 1 1 1 1 0
1 1 0 0 1 1 0 0 0
0 0 1 1 1 0 0 1 1
0 1 1 1 0 0 0 0 0
1 1 1 0 0 1 1 1 0
1 1 1 0 1 1 0 1 1
0 0 0 0 1 0 0 0 1
1 1 0 0 1 1 0 1 1
0 0 0 0 0 0 0 1 0
0 1 1 1 1 0 0 0 0
0 0 0 1 1 0 0 0 1
0 1 0 0 1 0 1 1 0
0 1 1 1 0 0 0 0 1
=> 8

1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
=> 0

```

# Answer
> 2 votes
# C (gcc), ~~308~~ 306 bytes

Function `f` receives `(height, width, flattened array, pointer to ans)`, and returns answer by pointer.

If there's no `1` in the matrix, it will return `0`.

```
#define v A[i]
N,M,K,R,C,T,i,*A;s(x,y){i=x*M+y;if(!(x<0|y<0|x>=N|y>=M|v^1))v=2,s(x,y+1),s(x,y-1),s(x+1,y),s(x-1,y);}g(i){if(C<R){if(i^K){g(i+1);if(!v)C+=v=1,g(i+1),v=0,C--;}else{T=1;for(i=0;i<K&&!v;i++);s(i/M,i%M);for(i=0;i<K;i++)T&=v^1,v=!!v;if(T)R=C;}}}f(n,m,a,b)int*a,*b;{K=R=(N=n)*(M=m),A=a;g(0);*b=R;}

```

Try it online!

**Ungolfed:**

```
N,M,R,C,T,i,*A; // height, width, result, recursion depth

s(x,y)
{ // depth first search: replace all 1 in the same connected component with 2
    i=x*M+y;
    if(!(x<0|y<0|x>=N|y>=M|A[i]^1)) { // check if out of boundary
        A[i]=2;
        s(x, y+1),s(x, y-1),s(x+1, y),s(x-1, y);
    }
}

g(i)
{ // enumerate all posible solutions
    if(C<R) {
        if(i!=N*M) {
            g(i+1);      // nothing change for this entry
            if (!A[i]) { // set the entry to 1
                C++, A[i]=1;
                g(i+1);
                C--, A[i]=0;
            }
        }
        else {
            T=1;
            for (i=0; i<N*M && !A[i]; i++); // find first non-zero entry
            s(i/M, i%M);     // replace the connected component
            for (i=0; i<N*M; i++) {
                T&=A[i]!=1;   // check if no other components
                A[i]=!!A[i]; // change 2s back to 1
            }
            if (T) R=C;      // update answer
        }
    }
}

f(n,m,a,b)int*a,*b;{
    R=(N=n)*(M=m), A=a;
    g(0);
    *b=R;
}

```

# Answer
> 1 votes
# Python 2, 611 bytes

A full program that takes a list of lists through user input. The functions `I` and `d` count the number of islands in the array. The for loop at the end enumerates through all possibilities of where you can change `0`s to `1`s then if there is one island left stores the number of `1`s added to the list `C`. The minimum of that list is the minimum number of bit flips required to connect any islands. It is a very slow algorithm so it doesn't run the test cases given in under 60s (I didn't try longer) but I tried a few smaller (~5x5) test cases and it seems to be working correctly. I got the island counting algorithm from this page.

```
from itertools import*
def d(g,i,j,v):
 v[i][j],R,C=1,[-1,1,0,0],[0,0,-1,1]
 for k in range(4):
	if len(g)>i+R[k]>=0<=j+C[k]<len(g[0]):
	 if v[i+R[k]][j+C[k]]<1and g[i+R[k]][j+C[k]]:v=d(g,i+R[k],j+C[k],v)
 return v
def I(g):
 w=len(g[0])
 v,c=[w*[0]for r in g],0
 for i in range(len(g)*w):
	if v[i/w][i%w]<1and g[i/w][i%w]>0:v=d(g,i/w,i%w,v);c+=1
 return c
g=input()
C=[]
for p in [list(t)for t in product([0,1],repeat=sum(r.count(0)for r in g))]:
 h,G,x=0,[r[:]for r in g],len(g[0])
 for i in range(x*len(G)):
	if G[i/x][i%x]<1:h+=p[0];G[i/x][i%x]=p[0];del p[0]
 if I(G)<2:
	C.append(h)
print min(C)

```

Try it online!

Pregolfed version before I optimized a few things:

```
from itertools import*
def d(g,i,j,v):
    v[i][j]=1
    R=[-1,1,0,0]
    C=[0,0,-1,1]
    for k in range(4):
        if len(g)>i+R[k]>=0<=j+C[k]<len(g[0]):
            if v[i+R[k]][j+C[k]]<1:
                if g[i+R[k]][j+C[k]]:
                    v=d(g,i+R[k],j+C[k],v)
    return v
def I(g):
    w=len(g[0])
    v=[[0]*w for r in g]
    c=0
    for i in range(len(g)):
        for j in range(w):
            if v[i][j]<1and g[i][j]>0:
                v=d(g,i,j,v)
                c+=1
    return c
g=input()
z=sum(r.count(0)for r in g)
f=[list(t)for t in product('01',repeat=z)]
C=[]
for p in f:
    h=0
    G=[r[:]for r in g]
    x=len(G[0])
    for i in range(x*len(G)):
        exec('h+=int(p[0]);G[i/x][i%x]=int(p[0]);del p[0]'*(G[i/x][i%x]<1))
    if I(G)<2:
        C.append(h)
print min(C)

```

---
Tags: code-golf, binary-matrix
---


title: Calculate the Upper Divmod

text:
# Question
Title: Calculate the Upper Divmod
# Task

Given two positive integers (divid**e**nd and divis**o**r), calculate the **q**uotient and the **r**emainder.
Normally it would be calculated as `e = o*q+r` where `q*o<=e` and `0<=r<o`.
For this challenge it still `e = o*q+r` but `q*o>=e` and `-o<r<=0`.
For example `e=20` and `o=3`, normally it would be `20/3 -> 20=3*6+2`, since `18<=20` and `0<=2<3`. Here it will be `20/3 -> 20=3*7-1` where `21>=20` and `-3<-1<=0`

# Test Cases

```
Input -> Output
20, 3 -> 7, -1
10, 5 -> 2, 0
7, 20 -> 1, -13
100, 13 -> 8, -4

```

You don't need to handle `o=0`.

# Answer
> 8 votes
# Python 3,  39 26 bytes

Martin Ender saved 13 bytes

```
lambda x,y:(-(x//-y),x%-y)

```

Try it online!

## Python 2, 25 bytes

```
lambda x,y:(-(x/-y),x%-y)

```

Try it online!

# Answer
> 8 votes
# Jelly, 3 bytes

```
NdN

```

Try it online!

### How it works

Abusing divmod again \o/. Look ma’ no unicode!

```
NdN - Full program / Dyadic chain. | Example: 7, 20

N   - Negate the first input.      | -7
 d  - Divmod by the second one.    | [-1, 13]
  N - Negate each again.           | [1, -13]

```

# Answer
> 6 votes
# Haskell, 25 bytes

```
n#k=[-div(-n)k,mod n(-k)]

```

Try it online!

# Answer
> 5 votes
# Mathematica, 21 bytes

```
{s=⌈#/#2⌉,#-#2s}&

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 4 bytes

```
(s‰(

```

Try it online!

**5 bytes**

```
(‰ćÄJ

```

Try it online!

### How they work

Abuses Python's modulo! \o/

```
(s‰(  | Full program. Let A and B be the two inputs. | Example: 100, 13.

(     | Compute -A.                                  | -100
 s    | Swap (reverse the stack, in this case).      | 13, -100
  ‰   | Divmod.                                      | [-8, 4]
   (  | Negative (multiply each by -1, basically).   | [8, -4]

----------------------------------------------------

(‰ćÄJ | Full program. Takes input in reverse order.

(     | Negative. Push -A.
 ‰    | Divmod
  ć   | Push head extracted divmod (make the stack [quotient, [remainder]].
   Ä  | Absolute value (operates on the quotient).
    J | Join the stack.

```

# Answer
> 4 votes
## Alice, 15 bytes

```
/O.
\io/R%e,R:R

```

Try it online!

### Explanation

Ruby's integer division and modulo (on which Alice's are implemented) are defined such that using a negative divisor already sort of does what we want. If we negated the divisor we automatically get the correct modulo, and we get minus the quotient we want. So the easiest way to solve this is by negating a bunch of numbers:

```
/   Switch to Ordinal mode.
i   Read all input as a string "e o".
.   Duplicate the string.
/   Switch to Cardinal mode.
R   Implicitly convert the top string to the two integer values it
    contains and negate o.
%   Compute e%-o.
e,  Swap the remainder with the other copy of the input string. We can't
    use the usual ~ for swapping because that would convert the string
    to the two numbers first and we'd swap e%-o in between e and o instead
    of to the bottom of the string.
R   Negate o again.
:   Compute e/-o.
R   Negate the result again.
\   Switch to Ordinal mode.
O   Output -(e/-o) with a trailing linefeed.
o   Output e%-o.

    The code now bounces through the code for a while, not doing much except
    printing a trailing linefeed when hitting O again. Eventually, the IP
    reaches : and attempts a division by zero which terminates the program.

```

# Answer
> 4 votes
# Pari/GP, 18 bytes

```
x->y->-[-x\y,-x%y]

```

Try it online!

# Answer
> 3 votes
# MATL, ~~5~~ 4 bytes

```
_&\_

```

Try it online!

*-1 byte thanks to Luis Mendo*

```
      # implicit input
_     # unary minus (negates first input, o)
&\    # alternative output mod, returns remainder, quotient, implicitly takes e
_     # unary minus, takes the opposite of the quotient.
      # implicit output, prints stack as remainder
                                         quotient

```

# Answer
> 3 votes
# Julia, 18 bytes

```
x$y=.-fldmod(-x,y)

```

Try it online!

`.-` is element wise negation, and `fldmod` returns a tuple made of the results of floored divison and corresponding residue.

# Answer
> 2 votes
# JavaScript (ES6), ~~37~~ ~~31~~ ~~29~~ ~~27~~ 25 bytes

*Saved 2 bytes thanks to @Rod*
*Saved 2 bytes thanks to @ETHproductions*

Takes input in currying syntax. Returns **\[q,r\]**.

```
a=>b=>[q=~-a/b+1|0,a-q*b]

```

### Test cases

```
let f =

a=>b=>[q=~-a/b+1|0,a-q*b]

console.log(JSON.stringify(f(20)(3)))   // -> 7, -1
console.log(JSON.stringify(f(10)(5)))   // -> 2, 0
console.log(JSON.stringify(f(7)(20)))   // -> 1, -13
console.log(JSON.stringify(f(100)(13))) // -> 8, -4
```

# Answer
> 2 votes
# , 16 bytes

```
([-]*a),~a=.>.@%

```

This is essentially the Jenny\_mathy's Mathematica solution rewritten in J.

# How it works:

`a=.>.@%` Finds the ceiling of the division of the left and right arguments and stores it into variable a

`,~` concatenated to (reversed)

`([-]*a)` subtracts a\*right argument from the left argument

Try it online!

# Answer
> 2 votes
# , ~~31~~ 29 bytes

*-2 bytes thanks to Giuseppe*

```
function(e,o)-c(e%/%-o,-e%%o)

```

Try it online!

# Answer
> 2 votes
# Common Lisp, 7 bytes

Built-in function `ceiling` returns two values: the ceiling of the quotient, and the remainder to match:

```
$ clisp -q
[1]> (ceiling 20 7)
3 ;
-1

```

# Answer
> 1 votes
# , ~~55~~ 50 bytes

```
3.711712114001231311141130013513213131211513115154

```

Try it online!

Represents the reminder by it's negation (`10` instead of `-10`), since the language uses byte input and output, deemed valid by OP comment.

# Answer
> 1 votes
# Perl 5, 30 + 1 (`-p`) = 31 bytes

```
say+($_-($\=$_%-($"=<>)))/$"}{

```

Try it online!

# Answer
> 1 votes
# Commentator, 90 bytes

```
//
;{- -}
{-{-//-}e#<!-}
;{-{-{- -}-}-}
{-{-{-e#-}
;{-{- -}-}
{-%e#*/-}#          /*-}e#*/

```

Try it online!

Outputs the remainder, then the quotient, newline separated.

# Answer
> 0 votes
# C (gcc), 43 bytes

```
f(x,y,z)int*x;{for(z=0;*x>0;*x-=y)z++;y=z;}

```

## Usage

```
main(){
    int a=7,b=20,c;
    c=f(&a,b);
    printf("%d %d\n",c,a);
}

```

Try it online!

# Answer
> 0 votes
# Java (OpenJDK 8), 30 bytes

```
(i,j)->(i+j-1)/j+","+(i%j-j)%j

```

Try it online!

```
7,-1
2,0
1,-13
8,-4

```

# Answer
> 0 votes
# Add++, 35 bytes

```
L*,@0$_$2D2D%V/1B]b\GLVB]-1Gx$pBcB*

```

Try it online!

# Answer
> 0 votes
# Deorst, 23 bytes

```
@l0-%z]@l0-,l0-@l0-miE_

```

Try it online!

## How it works

```
@                       - Swap the inputs
 l0-                    - Negate
    %                   - Modulo
     z]                 - Push the inputs
       @                - Swap
        l0-             - Negate
           ,            - Integer divide
            l0-         - Negate
               @        - Swap
                l0-     - Negate
                   miE_ - Print

```

# Answer
> 0 votes
# C (gcc) 41 bytes

```
f(a,b){b=(a+b-1)/b;}g(a,b){b=a-f(a,b)*b;}

```

This may be cheating, using two functions and it may fail other tests?

Try it online

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), ~~124~~ ~~123~~ 105 bytes

```
 E =INPUT
 O =INPUT
 Q =E / O
 R =E - Q * O
 EQ(0,R) :S(A)
 R =R - O
 Q =Q + 1
A OUTPUT =Q
 OUTPUT =R
END

```

Try it online!

Takes input as `E`, then `O`, separated by a newline and prints out `Q`, then `R`, separated by a newline.

# Answer
> 0 votes
# Swift, 47 bytes

```
func f(a:Int,b:Int){print((a+b-1)/b,(a%b-b)%b)}

```

# Answer
> 0 votes
# TXR: 8 bytes

Built-in function `ceil-rem`. E.g. `(ceil-rem 20 7)` yields `(7 -1)`.

# Answer
> 0 votes
# Clean, 42 bytes

```
import StdEnv
f a b#c=(a-1)/b+1
=(c,a-c*b)

```

Try it online!

---
Tags: code-golf, arithmetic, number-theory, division
---


title: Cases variations of a string

text:
# Question
Title: Cases variations of a string
For any String that is composed of lower cased alphabetical characters, make a function that returns a list of all of it's variations, empty strings returns empty list

**Test Cases**

```
"" -> []
"a" -> ["a", "A"]
"ab" -> ["ab", "Ab", "aB", "AB"]
"abc" -> ["abc", "Abc", "aBc", "ABc", "abC", "AbC", "aBC", "ABC"]

```

This is Code-golf. Shortest code in bytes wins

# Answer
> 0 votes
## JavaScript (Firefox 30-57), 75 bytes

```
f=([c,...s])=>c?[for(t of s[0]?f(s):[''])for(d of c+c.toUpperCase())d+t]:[]

```

67 bytes if the empty string returns `[""]`:

```
f=([c,...s])=>c?[for(t of f(s))for(d of c+c.toUpperCase())d+t]:['']

```

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


title: Adjacent Letter Test

text:
# Question
Title: Adjacent Letter Test
One aspect of password strength testing is runs of adjacent letters on the keyboard. In this challenge, a program must be created that returns `true` if a string contains any runs of adjacent letters.

## What counts as a run of adjacent letters?

For this simplified version of a password strength tester, a run of adjacent characters is 3 or more letters which are next to each other in a single direction (left, right, above or below) on a QWERTY keyboard. For the purpose of this challenge the layout of the keyboard looks like this:

```
1234567890
QWERTYUIOP
ASDFGHJKL
ZXCVBNM

```

In the diagram above `Q` is below `1` but not below `2`, so a string that contains `1qa` or `aq1` anywhere inside it would make the program return `true`, but `2qa` would not.

## Input

The password string to check. It will only contain the characters `[0-9a-z]` or `[0-9A-Z]` (your choice).

## Output

The program must return a truthy value if the password contains one or more runs of adjacent keys, or falsey if it contains none.

## Examples

The following inputs should output true:

* `asd`
* `ytrewq`
* `ju7`
* `abc6yhdef`

And these inputs should output false:

* `abc`
* `aaa`
* `qewretry`
* `zse`
* `qwdfbn`
* `pas`

## Rules

* Answers may be complete programs or functions.
* Standard loopholes are disallowed.
* This is , lowest score (in bytes) wins!

# Answer
# Pyth - ~~66~~ ~~62~~ 60 bytes

Pretty straightforward approach. Checks if any of substrings len 3 are in any of the rotations of the keyboard. Will be using base encoding for keyboard.

```
.E}Rjb+J+Kc+jkS9"0
qwertyuiop
asdfghjkl
zxcvbnm"b.tKN_MJ.:z3

```

Test Suite.
> 3 votes

# Answer
# Japt, 78 bytes

**Japt** is a shortened version of **Ja**vaScri**pt**. Interpreter

```
V=1oA ¬+`0\nqØÆyuiop\n?dfghjkl \nzxcvbnm`;1+¡Y©(((VbX -VbUgY-1)-5 a -5 %A a)bB

```

Outputs `0` for falsey cases; otherwise, a positive integer. The `?` should be replaced with the unprintable Unicode char U+0086, or if you don't want to go to all that trouble, just `as`.

### How it works

```
V=1oA q +"0\nqwertyuiop\nasdfghjkl \nzxcvbnm";1+Um@Y&&(((VbX -VbUgY-1)-5 a -5 %A a)bB
           // Implicit: U = input string
V=1oA q    // Set variable V to the digits 1-9, plus
+"...";    // this string.
Um@        // Take U and map each character X and its index Y with this function:
Y&&        //  If Y is 0, return Y; otherwise,
VbX -      //  take the index of X in V, subtract
VbUgY-1    //  the index of (char at position Y - 1 in U) in V,
-5 a -5    //  subtract 5, take the absolute value, subtract 5 again,
%A a       //  take modulo by 10, then take the absolute value.
           //  This returns 1 for any pair of characters that is adjacent
           //  within V, horizontally or vertically.
bB +1      // Take the index of 11 in the result and add one.
           // Implicit: output last expression

```
> 2 votes

# Answer
## C#, 227

```
int h(string k){var q="1234567890,QWERTYUIOP,ASDFGHJKL,ZXCVBNM,1QAZ,2WSX,3EDC,4RFV,5TGB,6YHN,7UJM,8IK,9OL,";int i=0,j=0;for(;i<k.Length-2;i++)if((q+String.Concat(Enumerable.Reverse(q))).Contains(k.Substring(i,3)))j=1;return j;}

```

0 is falsey, 1 is truthy. Concatenated all keys horizontal and vertical, and reversed, and checks if any of 3 chars of input is contained within.

C# is really verbose, gotta dive into other languages :(
> 2 votes

# Answer
# PHP, 173+1 bytes

```
while(~$argn[$i+2])($p=preg_match)($r=_.join(".{10}",str_split(($t=substr($argn,$i++,3))))."|$t"._,$d=_1234567890_qwertyuiop_asdfghjkl__zxcvbnm)||$p($r,strrev($d))?die(1):0;

```

Run as pipe with `-nR` with lowercase input or try it online.
> 0 votes

# Answer
## Clojure, 156 bytes

```
#(some(set(for[R[["1234567890""QWERTYUIOP""ASDFGHJKL.""ZXCVBNM..."]]R[R(apply map list R)]r R p(partition 3 1 r)p((juxt seq reverse)p)]p))(partition 3 1 %))

```

This was a quite interesting task to implement.
> 0 votes

---
Tags: code-golf, keyboard
---


title: It's a Slippery Slope

text:
# Question
Title: It's a Slippery Slope
There has not been a challenge regarding slope fields, as a far as I can tell. So, I might as well make one.

# The challenge

Given:

* A black box function `f` which takes two arguments, `x` and `y` (both real numbers) , and returns the value of the slope at point `(x,y)` (also a real number)
* A list of real numbers, `X`, representing the values along the `x` axis,
* Another list of real numbers, `Y`, representing the values along the `y` axis.
* A list of `(x,y)` pairs, `U`, which represents the inputs that `f` is undefined on. This argument can be removed if your language can detect errors.

Output:

* A rectangle with a length of the length `X`, and a height of the length of `Y`. At each combination of row `r` and column `c` in the rectangle, (starting from the bottom left corner), the character that is placed at that position will depend on the sign value of `f` evaluated at `x=c` and `y=r`:
    + If the value is positive, the character is `/`.
    + If the value is zero, the character is `-`.
    + If the value is negative, the character is `\`.
    + If `(x,y)` is not in the domain of `f` (a.k.a. a member of `U`), then the character is . `f` is guaranteed to not error on every combination of `x` within `X` and `y` within `Y` if `U` is utilized.

Since I am horrible at explaining things, here's an example:

Input:

```
f(x,y) = x / y
X=[-1,0,1]
Y=[-1,0,1]
U=[[-1,0],[0,0],[1,0]]

```

Output:

```
\-/

/-\

```
* At `(0,0)` (the bottom left corner), the corresponding `X` and `Y` values are `-1` and `-1` (since `X[0] = -1` and `Y[0] = -1`). `f(-1,-1)=(-1)/(-1)=1`, thus `/` is used.
* At `(1,0)` (the bottom row, middle column): `X[1] = 0, Y[0] = -1`, `f(0,-1)=(0)/(-1)=0`, and `0` is zero (duh), so the character is `-`.
* At `(1,1)` (the center): `X[1] = 0, Y[1] = 0`. `[0,0]` is a member of `U`. Therefore, it corresponds to the  character. Or, if done without `U`: `0/0` is undefined, thus the character is .
* At `(2,2)` (the top left): `X[2] = 1, Y[2] = 1, f(1,1)=(1)/(1)=1`, which is positive. Therefore, it corresponds to the `/` character.
* Etc...

# Floating Point

Any value of `f` within the range `[-1e-9,1e-9]` should be considered to have a sign of `0`.

# Winning condition

This is a , so lowest byte count wins!

# Answer
# Jelly, 23 bytes

```
Ṛ⁹,2⁶v$Ṡ$e⁵$?¥þị“/ \-”Y

```

Try it online!

Arguments: `Y`, `X`, `U`, `f`

`f` is a Python string containing Jelly code. **Be sure to quote it appropriately**, otherwise you may encounter errors.

Also, **`f` takes a pair `[x, y]` as its argument, not two arguments `x` and `y`**.
> 6 votes

# Answer
# APL (Dyalog), ~~36~~ 34 bytes

*2 bytes saved thanks to @ngn*

```
{o←⍺⍺⋄'\-/ '[⊖⍉⍺∘.{0::4⋄2+×⍺o⍵}⍵]}

```

Try it online! <sub>(with modified division, since basic APL 0÷0 is 1)</sub>

The black box function comes as left operand, `X` as left argument, and `Y` as right argument.
> 3 votes

# Answer
# Haskell, ~~114~~ ~~113~~ 109 bytes

```
z x=last$0:[x|abs x>1e-9]
(x#y)(%)u=reverse[[last$"\\-/"!!floor(1+signum(z$c%r)):[' '|elem(c,r)u]|c<-x]|r<-y]

```

Try it online!

Fairly straightforward solution. Uses `signum` to index into a string for the right char if the point is defined.

EDIT: Thought of a way to shave off a byte

EDIT 2: Thanks @Laikoni for taking off another 4 bytes!
> 2 votes

# Answer
# Python 2, ~~105~~ ~~103~~ ~~95~~ 92 bytes

```
def f(F,X,Y,U):
 for y in Y[::-1]:print''.join('/ \-'[[x,y]in U or~cmp(0,F(x,y))]for x in X)

```

Try it online!

---

Error handling version:

# Python 2, ~~135~~ ~~132~~ 125 bytes

```
def f(F,X,Y):
 def g(x,y):
	try:return'-\/'[cmp(0,F(x,y))]
	except:return' '
 for y in Y[::-1]:print''.join(g(x,y)for x in X)

```

Try it online!
> 1 votes

# Answer
# Python 2, 91 bytes

```
f,X,Y,U=input()
for y in Y[::-1]:print''.join('/ \-'[[x,y]in U or~cmp(0,f(x,y))]for x in X)

```

Try it online!

-3 thanks to Jonathan Allan.

Looks like I can't just assume `f` to be already assigned to a function.
> 1 votes

# Answer
# Swift, 142 bytes

```
func f(X:[Float],Y:[Float]){print(Y.reversed().flatMap{y in X.flatMap{let s=try?b($0,y);return s==nil ?" ":s!>0 ?"/":s!<0 ?"\\":"-"}+["\n"]})}

```

Prints as an array of characters
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~70~~ 68 bytes

```
Table["-"["/","\\"][[Sign[x~#~y]]]~Check~" ",{y,Reverse@#3},{x,#2}]&

```

Try it online!

In the expression `"-"["/","\\"]`, part 0 is the head (`"-"`), part 1 is `"/"`, and part -1 (the last part) is `"\\"`, so if we try to take the `Sign[f]`-th part of it, we get the appropriate character depending on if `f` is positive, negative, or zero. If none of the above apply, or if evaluating the function causes an error, the `~Check~` will catch the error and return the `" "` character instead.

(It still prints out a bunch of error messages, which should be ignored since we get the right answer at the end.)

We do this for all `x` and `y` values.
> 1 votes

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


title: Festival of ASCII-art lights

text:
# Question
Title: Festival of ASCII-art lights
Write, in as few **characters** as possible, a program that takes zero or six command-line arguments

```
menorah
menorah YEAR MONTH DAY HOUR MINUTE SECOND

```

(Both forms must be supported. The zero-argument version shall be equivalent to calling the six-argument version with the *current* system date and time in the local timezone.)

and if the specified (Gregorian-calendar) date and time falls during Hanukkah, then output an ASCII art (or Unicode art) nine-branch menorah with the appropriate number of candles lit. If it is *not* during Hanukkah, then output a single newline. For example,

```
~$ ./menorah 2015 12 7 0 0 0

    *
    |   *
    |   |
    |   |
+++++++++
    |
   -+-

~$ ./menorah 2015 12 9 0 0 0

    *
    | ***
    | |||
    | |||
+++++++++
    |
   -+-

~$ ./menorah 2015 12 14 0 0 0

    *
****|****
|||||||||
|||||||||
+++++++++
    |
   -+-

~$ ./menorah 2015 12 15 0 0 0
~$

```

On the Nth day of the festival, N+1 candles are lit: The central *shamash* candle, and N of the 8 Hanukkah candles, placed in right-to-left order.

Allowed variations in the output format are:

* Unused candles may be drawn unlit instead of omitted.
* You may use non-ASCII characters to make the result more aesthetically pleasing. Like  (U+1F525) instead of `*`. Or box-drawing characters instead of `+-|`.

For the purpose of this challenge, a day on the Hebrew calendar may be assumed to start at 18:00.

Results must be correct for Gregorian years between 1900 and 2239, inclusive.

---

Hanukkah begins at **sunset** on the Gregorian dates

```
1900-12-16  1901-12-05  1902-12-24  1903-12-13  1904-12-02  1905-12-22
1906-12-11  1907-11-30  1908-12-18  1909-12-07  1910-12-25  1911-12-15
1912-12-04  1913-12-23  1914-12-12  1915-12-01  1916-12-19  1917-12-09
1918-11-28  1919-12-16  1920-12-05  1921-12-25  1922-12-14  1923-12-02
1924-12-21  1925-12-11  1926-11-30  1927-12-18  1928-12-07  1929-12-26
1930-12-14  1931-12-04  1932-12-23  1933-12-12  1934-12-01  1935-12-20
1936-12-08  1937-11-28  1938-12-17  1939-12-06  1940-12-24  1941-12-14
1942-12-03  1943-12-21  1944-12-10  1945-11-29  1946-12-17  1947-12-07
1948-12-26  1949-12-15  1950-12-03  1951-12-23  1952-12-12  1953-12-01
1954-12-19  1955-12-09  1956-11-28  1957-12-17  1958-12-06  1959-12-25
1960-12-13  1961-12-02  1962-12-21  1963-12-10  1964-11-29  1965-12-18
1966-12-07  1967-12-26  1968-12-15  1969-12-04  1970-12-22  1971-12-12
1972-11-30  1973-12-19  1974-12-08  1975-11-28  1976-12-16  1977-12-04
1978-12-24  1979-12-14  1980-12-02  1981-12-20  1982-12-10  1983-11-30
1984-12-18  1985-12-07  1986-12-26  1987-12-15  1988-12-03  1989-12-22
1990-12-11  1991-12-01  1992-12-19  1993-12-08  1994-11-27  1995-12-17
1996-12-05  1997-12-23  1998-12-13  1999-12-03  2000-12-21  2001-12-09
2002-11-29  2003-12-19  2004-12-07  2005-12-25  2006-12-15  2007-12-04
2008-12-21  2009-12-11  2010-12-01  2011-12-20  2012-12-08  2013-11-27
2014-12-16  2015-12-06  2016-12-24  2017-12-12  2018-12-02  2019-12-22
2020-12-10  2021-11-28  2022-12-18  2023-12-07  2024-12-25  2025-12-14
2026-12-04  2027-12-24  2028-12-12  2029-12-01  2030-12-20  2031-12-09
2032-11-27  2033-12-16  2034-12-06  2035-12-25  2036-12-13  2037-12-02
2038-12-21  2039-12-11  2040-11-29  2041-12-17  2042-12-07  2043-12-26
2044-12-14  2045-12-03  2046-12-23  2047-12-12  2048-11-29  2049-12-19
2050-12-09  2051-11-28  2052-12-15  2053-12-05  2054-12-25  2055-12-14
2056-12-02  2057-12-21  2058-12-10  2059-11-29  2060-12-17  2061-12-07
2062-12-26  2063-12-15  2064-12-03  2065-12-22  2066-12-12  2067-12-01
2068-12-18  2069-12-08  2070-11-27  2071-12-16  2072-12-04  2073-12-24
2074-12-13  2075-12-01  2076-12-20  2077-12-10  2078-11-29  2079-12-17
2080-12-06  2081-12-26  2082-12-15  2083-12-04  2084-12-22  2085-12-11
2086-11-30  2087-12-19  2088-12-07  2089-11-27  2090-12-16  2091-12-05
2092-12-23  2093-12-13  2094-12-02  2095-12-20  2096-12-09  2097-11-29
2098-12-18  2099-12-06  2100-12-26  2101-12-16  2102-12-05  2103-12-23
2104-12-12  2105-12-02  2106-12-21  2107-12-10  2108-11-28  2109-12-17
2110-12-06  2111-12-25  2112-12-13  2113-12-03  2114-12-22  2115-12-10
2116-11-29  2117-12-19  2118-12-08  2119-12-26  2120-12-15  2121-12-04
2122-12-23  2123-12-12  2124-12-01  2125-12-21  2126-12-10  2127-11-29
2128-12-17  2129-12-06  2130-12-24  2131-12-14  2132-12-03  2133-12-22
2134-12-11  2135-11-30  2136-12-18  2137-12-07  2138-12-26  2139-12-15
2140-12-04  2141-12-23  2142-12-12  2143-12-01  2144-12-20  2145-12-09
2146-11-27  2147-12-17  2148-12-05  2149-12-24  2150-12-13  2151-12-03
2152-12-22  2153-12-11  2154-11-30  2155-12-19  2156-12-07  2157-12-25
2158-12-15  2159-12-05  2160-12-23  2161-12-12  2162-12-01  2163-12-20
2164-12-09  2165-11-28  2166-12-16  2167-12-06  2168-12-24  2169-12-13
2170-12-02  2171-12-22  2172-12-10  2173-11-28  2174-12-18  2175-12-08
2176-12-26  2177-12-14  2178-12-04  2179-12-24  2180-12-12  2181-12-01
2182-12-20  2183-12-09  2184-11-28  2185-12-17  2186-12-06  2187-12-25
2188-12-14  2189-12-03  2190-12-21  2191-12-11  2192-11-29  2193-12-17
2194-12-07  2195-12-27  2196-12-15  2197-12-03  2198-12-23  2199-12-13
2200-12-02  2201-12-20  2202-12-10  2203-11-30  2204-12-18  2205-12-07
2206-12-26  2207-12-15  2208-12-03  2209-12-22  2210-12-11  2211-12-01
2212-12-19  2213-12-08  2214-12-27  2215-12-17  2216-12-05  2217-12-23
2218-12-13  2219-12-02  2220-12-20  2221-12-09  2222-11-29  2223-12-18
2224-12-05  2225-12-25  2226-12-15  2227-12-04  2228-12-21  2229-12-11
2230-12-01  2231-12-20  2232-12-08  2233-12-27  2234-12-16  2235-12-05
2236-12-23  2237-12-12  2238-12-02  2239-12-21

```

# Answer
# Mathematica, ~~376~~ ~~338~~ 334 bytes

```
a=Rest@$ScriptCommandLine;b=CalendarConvert[If[a=={},Now~TimeZoneConvert~0,DateObject[FromDigits/@a,TimeZone->0]],j="Jewish"];c=Floor@DateDifference[DateObject[{b[[1,1]],9,25},CalendarType->j,TimeZone->0],b][[1]];d=If[#<=c,"*"," "]&;0<=c<8&&Print["    *
"<>{d/@{7,6,5,4},"|",d/@{3,2,1},"*
|||||||||
|||||||||
+++++++++
    |
   -+-"}]

```

Runs in a script.
> 3 votes

# Answer
## R, 467 bytes

With a little doubt if using a library for the Calendar conversion is allowed or not.

```
library(ConvCalendar)
f='%Y %m %d %H %M %S'
g='hebrew'
s=' '
if(length(n<-scan())!=6)n=format(Sys.time(),f)
if(n[4]>17)n[3]=n[3]+1
d=strptime(paste(n,collapse=s),f)
h=as.OtherDate(d,g)
i=OtherDate(25,3,h$year,g)
j=round(difftime(d,as.Date(i),,"days"))+1
N=ifelse(j>0&j<10,(1:9)[j],0)
if(!N)write('')else{l='**||+|+'
z=matrix(strsplit(l,'')[[1]],9,7,T)
z[c(1:4,6:9),c(1,6:7)]=s
z[c(4,6),7]='-'
if(N<8)z[1:(9-N),2:4]=s
z[5,2:4]='|'
write(z,'',9,,'')}

```

Example for input 2015 12 07 00 00 00:

```
    *
    |   *
    |   |
    |   |
+++++++++
    |
   -+-

```
> 3 votes

# Answer
# APL (Dyalog), 193 bytes

Prompts for input from STDIN and prints to STDOUT.

Uses box drawing characters and an actual lamp symbol!

```
⎕USING←'System'
→3×(c←+/i≥((⎕NEW Globalization.HebrewCalendar).(ToDateTime 7↑3 23 18,⍨GetYear)i←⎕NEW DateTime(6↑⍎∊⍞'⎕TS')).AddDays¨⍳9)∊⍳8
¯5↑'⍝'
'⍝'@(10-r+5≤r←⍳c)⊢9↑s←¯5↑'│'
9/⍪'││┴'
s
'   ─┴─'

```

`⎕USING←'System'` Use .NET

`⍳8` first eight **ɩ**ntegers
`(``)∊` Boolean for whether the following is a member of that:
`⍳9` first nine integers
`(``).AddDays¨` for each, add that many days to:
`⎕NEW DateTime(``)` a new DateTime .NET object with the value of:
`⍞'⎕TS'` STDIN and expression for current **T**ime **S**tamp
**ϵ**nlist (flatten)
execute (evaluate) that (gives six- or seven-element numeric list)
`6↑` take the first six elements (Y M D h m s)
`i←` store as `i` (for **i**nput)
`(⎕NEW Globalization.HebrewCalendar).(``)` in a new HebrewCalendar object:
`GetYear` get the (Hebrew) year of the input
`3 23 18,⍨` append these (3 month, 23th day, 18th hour — one night before Hanukkah)
`7↑` take the first seven elements, padding with 0s (minutes, seconds)
`ToDateTime` convert that Hebrew point in time to normal DateTime object
`i≥` Boolean whether the input is equal to or after each of those
`+/` sum the Booleans
`c←` store as `c` (for **c**ount)
multiply by three
go to that line (3, i.e. next, if Hanukkah; 0, i.e. quit, if not)

`¯5↑'⍝'` implicitly print the last five characters of the lamp symbol (padding with spaces)

`¯5↑'│'` last five characters of the middle-candle symbol (padding with spaces)
`s←` store as s (for **s**tem)
`9↑` take the first nine characters from that (padding with spaces)
yield (separates the above from the below
`'⍝'@(``)` implicitly print with lamps placed at the following indices:
`⍳c` as many **ɩ**ntegers as count of begun Hanukkah days
`r←` store in `r` (for **r**ange)
`5≤` Booleans for those larger than or equal to five (to skip the middle candle)
`r+` add to the range of indices
`10-` subtract those from ten (to begin at the right)

`⍪'││┴'` make this string into a column matrix
`9/` implicitly print nine horizontal copies of that

`s` implicitly print the stem

`' ─┴─'` implicitly print this string

### Example run:

```
      menorah
2015 12 7 0 0 0
    ⍝
    │   ⍝
│││││││││
│││││││││
┴┴┴┴┴┴┴┴┴
    │
   ─┴─
      menorah
2015 12 9 0 0 0
    ⍝
    │ ⍝⍝⍝
│││││││││
│││││││││
┴┴┴┴┴┴┴┴┴
    │
   ─┴─
      menorah
2015 12 14 0 0 0
    ⍝
⍝⍝⍝⍝│⍝⍝⍝⍝
│││││││││
│││││││││
┴┴┴┴┴┴┴┴┴
    │
   ─┴─
      menorah
2015 12 15 0 0 0

```
> 2 votes

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


title: Circles, where do you meet?

text:
# Question
Title: Circles, where do you meet?
Given 2 random circle sections, return how many times they intersect. Rules/clarifications are as below.

1. You are provided 10 total values,
    * The center (x,y) of the circle section
    * Angles of the circle (i.e. (0,90) would be a quarter circle "facing" the top-right corner.
    * The radius of the circle section
2. The circle sections are "drawn" on a 128 by 128 screen, with (0,0) being the center. They have a max radius of 64.
3. You don't need to draw the circles - the program should *only* print out the number of intersections.
4. You can choose to generate the values randomly, in-program, or have the user write it in at program start. (The latter is preferred, but not necessary.)

Below is an example case. As you can see, it has one intersect.

The output should look something like this:

```
$ run ./circle
input (circle 1 center)
input (circle 1 radius)
input (circle 1 angles)
input (more inputs...)
...
intersections

```

Heres the output for the example case (the prompts are optional):

```
$ run ./circle
c1center: (20,20)
c1radius: 40
c1angles: (210,150)
c2center: (-30,-30)
c2radius: 90
c2angles: (270,180
1

```

Anyway, best of luck! This is code golf, so the minimum number of bytes in any programming language wins!

Oh, and it'd be nice if you could provide a description/link to your program in the answer. Standard Loopholes are not allowed. If you find any errors in my explanation or want me to clarify, just ask. Thanks!

# Answer
> 3 votes
# Python 3 \+ numpy, ~~310~~ 291 bytes

<sup> -19 bytes thanks to ovs! </sup>

```
v=lambda c,x,y:sin(arctan2(*c[::-1])-x)>sin(y-x)
def f(a,r,w,x,b,s,y,z):
 d=linalg.norm(b-a)
 if abs(r-s)<d<r+s:e=(r*r-s*s+d*d)/2/d;g=a+e*(b-a)/d;t=(sqrt(r*r-e*e)*(b-a)/d*[1,-1])[::-1];return int(v(g+t-a,w,x)and v(g+t-b,y,z))+int(v(g-t-a,w,x)and v(g-t-b,y,z))-(t==0).all()
from numpy import*

```

Try it online!

This is a horrible answer.

Takes angles in radians.

---
Tags: code-golf
---


# Question
Title: Frequency Distribution of Mixed Dice Rolls
A follow-up to this challenge

Given a set of mixed dice, output the frequency distribution of rolling all of them and summing the rolled numbers on each die.

For example, consider `1d12 + 1d8` (rolling 1 12-sided die and 1 8-sided die). The maximum and minimum rolls are `20` and `2`, respectively, which is similar to rolling `2d10` (2 10-sided dice). However, `1d12 + 1d8` results in a flatter distribution than `2d10`: `[1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 7, 6, 5, 4, 3, 2, 1]` versus `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]`.

## Rules

* The frequencies must be listed in increasing order of the sum to which the frequency corresponds.
* Labeling the frequencies with the corresponding sums is allowed, but not required (since the sums can be inferred from the required order).
* You do not have to handle inputs where the output exceeds the representable range of integers for your language.
* Leading or trailing zeroes are not permitted. Only positive frequencies should appear in the output.
* You may take the input in any reasonable format (list of dice (`[6, 8, 8]`), list of dice pairs (`[[1, 6], [2, 8]]`), etc.).
* The frequencies must be normalized so that the GCD of the frequencies is 1 (e.g. `[1, 2, 3, 2, 1]` instead of `[2, 4, 6, 4, 2]`).
* All dice will have at least one face (so a `d1` is the minimum).
* This is , so the shortest code (in bytes) wins. Standard loopholes are forbidden, as per usual.

## Test Cases

These test cases are given as `input: output`, where the input is given as a list of pairs `[a, b]` representing `a` `b`-sided dice (so `[3, 8]` refers to `3d8`, and `[[1, 12], [1, 8]]` refers to `1d12 + 1d8`).

```
[[2, 10]]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[[1, 1], [1, 9]]: [1, 1, 1, 1, 1, 1, 1, 1, 1]
[[1, 12], [1, 8]]: [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 7, 6, 5, 4, 3, 2, 1]
[[2, 4], [3, 6]]: [1, 5, 15, 35, 68, 116, 177, 245, 311, 363, 392, 392, 363, 311, 245, 177, 116, 68, 35, 15, 5, 1]
[[1, 3], [2, 13]]: [1, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 37, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 1]
[[1, 4], [2, 8], [2, 20]]: [1, 5, 15, 35, 69, 121, 195, 295, 423, 579, 761, 965, 1187, 1423, 1669, 1921, 2176, 2432, 2688, 2944, 3198, 3446, 3682, 3898, 4086, 4238, 4346, 4402, 4402, 4346, 4238, 4086, 3898, 3682, 3446, 3198, 2944, 2688, 2432, 2176, 1921, 1669, 1423, 1187, 965, 761, 579, 423, 295, 195, 121, 69, 35, 15, 5, 1]
[[1, 10], [1, 12], [1, 20], [1, 50]]: [1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 285, 360, 444, 536, 635, 740, 850, 964, 1081, 1200, 1319, 1436, 1550, 1660, 1765, 1864, 1956, 2040, 2115, 2180, 2235, 2280, 2316, 2344, 2365, 2380, 2390, 2396, 2399, 2400, 2400, 2400, 2400, 2400, 2400, 2400, 2400, 2400, 2400, 2400, 2399, 2396, 2390, 2380, 2365, 2344, 2316, 2280, 2235, 2180, 2115, 2040, 1956, 1864, 1765, 1660, 1550, 1436, 1319, 1200, 1081, 964, 850, 740, 635, 536, 444, 360, 285, 220, 165, 120, 84, 56, 35, 20, 10, 4, 1]

```

# Answer
# Jelly,  ~~14~~  7 bytes

-3 bytes thanks to Mr. Xcoder (use of an implicit range to avoid leading `R`; replacement of reduce by the dyadic Cartesian product and flatten, `p/F€`, with the Cartesian product built-in for that very purpose, `Œp`.)

```
ŒpS€ĠL€

```

A monadic link taking a list of dice faces and returning the normalised distribution of the increasing sums.

**Try it online!**

### How?

Goes through the list of dice "sizes" (implicitly) makes them into their list of faces, then gets the Cartesian product of those lists (all possible rolls of the set of dice), then sums up those rolls, gets the groups of equal indices (by ascending value) and takes the length of each group.

```
ŒpS€ĠL€ - Link: list of numbers, dice  e.g. [2,5,1,2]
Œp      - Cartisian product (implicit range-ification -> [[1,2],[1,2,3,4,5],[1],[1,2]])
        -                   -> [[1,1,1,1],[1,1,1,2],[1,2,1,1],[1,2,1,2],[1,3,1,1],[1,3,1,2],[1,4,1,1],[1,4,1,2],[1,5,1,1],[1,5,1,2],[2,1,1,1],[2,1,1,2],[2,2,1,1],[2,2,1,2],[2,3,1,1],[2,3,1,2],[2,4,1,1],[2,4,1,2],[2,5,1,1],[2,5,1,2]]
  S€    - sum €ach          -> [4,5,5,6,6,7,7,8,8,9,5,6,6,7,7,8,8,9,9,10]
    Ġ   - group indices     -> [[1],[2,3,11],[4,5,12,13],[6,7,14,15],[8,9,16,17],[10,18,19],[20]]
     L€ - length of €ach    -> [1,3,4,4,4,3,1]

```

Note: there is only ever one way to roll the minimum (by rolling a one on each and every dice) and we are not double-counting any rolls, so there is no need to perform a GCD normalisation.
> 7 votes

# Answer
# Haskell, 54 bytes

```
1%r=r
n%r=zipWith(+)(r++[0,0..])$0:(n-1)%r
foldr(%)[1]

```

Try it online!

---

**Haskell, 63 bytes**

```
f l=[sum[1|t<-mapM(\x->[1..x])l,sum t==k]|k<-[length l..sum l]]

```

Try it online!

---

**Haskell, 68 bytes**

```
k%(h:t)=sum$map(%t)[k-h..k-1]
k%_=0^k^2
f l=map(%l)[length l..sum l]

```

Try it online!
> 5 votes

# Answer
# MATL, 8 bytes

```
1i"@:gY+

```

The input is an array of (possibly repeated) die sizes.

Try it online! Or verify all test cases.

### Explanation

```
1      % Push 1
i      % Input: numeric array
"      % For each k in that array
  @    %   Push k
  :    %   Range: gives [1 2 ... k]
  g    %   Convert to logical: gives [1 1 ... 1]
  Y+   %   Convolution, with full size
       % End (implicit). Display (implicit)

```
> 5 votes

# Answer
# Husk, 7 bytes

```
mLkΣΠmḣ

```

Input is a list of dice. Try it online!

## Explanation

```
mLkΣΠmḣ  Implicit input, say x=[3,3,6].
     mḣ  Map range: [[1,2,3],[1,2,3],[1,2,3,4,5,6]]
    Π    Cartesian product: [[1,1,1],[1,1,2],..,[3,3,6]]
  kΣ     Classify by sum: [[[1,1,1]],[[1,1,2],[1,2,1],[2,1,1]],..,[[3,3,6]]]
mL       Map length: [1,3,6,8,9,9,8,6,3,1]

```
> 5 votes

# Answer
# Octave, ~~88 69 58~~ 56 bytes

As mentioned in the Haskell answer, this uses the fact that the distribution of e.g. a 3-sided and a 5-sided dice is the discrete convolution of the two vectors `[1,1,1]` and `[1,1,1,1,1]`. Thanks @LuisMendo for -11 bytes worth of clever golfing!

```
function y=f(c);y=1:c;if d=c(2:end);y=conv(~~y,f(d));end

```

Try it online!

This submission is using an recursive approach. But if you would use a loop it would be slightly longer:

```
function y=f(c);y=1;for k=cellfun(@(x)ones(1,x),c,'Un',0);y=conv(y,k{1});end

```
> 4 votes

# Answer
# Mathematica, 44 bytes

Outputs the frequencies labeled with the corresponding sums

```
Tally@*Fold[Join@@Table[#+i,{i,#2}]&]@*Range

```

Try it online!

-5 bytes from Martin Ender

thanks to Misha Lavrov for letting me know that "labeled" is valid
> 4 votes

# Answer
# Wolfram Language (Mathematica), 26 bytes

```
Tally[Tr/@Tuples@Range@#]&

```

Try it online!

A modification of my answer to the previous challenge. This just generates all possible outcomes, adds them up, and tallies the results.

For fun, we could write it as `Tally@*Total@*Thread@*Tuples@*Range`, but that's longer.

# Wolfram Language (Mathematica), 41 bytes

```
CoefficientList[1##&@@((x^#-1)/(x-1)),x]&

```

Try it online!

This is the convolution-based approach (here, we take convolutions via the product of generating functions - `1+x+x^2+...+x^(N-1)` is the generating function for rolling a dN - and then take the list of coefficients). I include it because the first solution isn't practical for large inputs.
> 4 votes

# Answer
# Haskell, ~~80 78~~ 64 bytes

This solution ended up being almost the same as the one of @Sherlock9 in the previous challenge with the maybe more natural approach. @xnor has an even shorter Haskell solution!

```
import Data.List
g x=[1..x]
map length.group.sort.map sum.mapM g

```

Explanation:

```
                              mapM g -- all possible outcomes
                      map sum        -- the sums of all possible outcomes
map length.group.sort                -- count the frequency of each sum

```

Try it online!

**Previous solution:**

This is using the @AndersKaseorg discrete convolution function. The observation here is that the distribution of e.g. a 3-sided and a 5-sided dice is the discrete convolution of the two vectors `[1,1,1]` and `[1,1,1,1,1]`.

```
foldl1(#).map(`take`l)
(a:b)#c=zipWith(+)(0:b#c)$map(a*)c++[]#b
_#c=0<$c
l=1:l

```

Try it online!
> 3 votes

# Answer
# Jelly, 14 bytes

```
R+Ð€/FċÐ€SR$ḟ0

```

Try it online!

Input is a list of die values. I could golf this down by stealing `ĠL€` from the other Jelly answer but then I could also golf down the first half and end up with the same thing so I'll just leave it how it is
> 3 votes

# Answer
# Pyth, 12 bytes

```
lM.gs.nk*FSM

```

**Try it here!**

### How?

```
lM.gs.nk*FSM  ~ Full program.

          SM  ~ Map with inclusive unary integer range [1, N].
        *F    ~ Fold (Reduce by) Cartesian product.
  .g          ~ Group by function result.
    s.n       ~ The sum of the list when flattened.
lM            ~ Length of each group.

```
> 3 votes

# Answer
# Python 2, ~~120~~ 119 bytes

```
lambda v:[reduce(lambda a,c:sum([[b+y for b in a]for y in range(c)],[]),v,[0]).count(d)for d in range(sum(v)-len(v)+1)]

```

Try it online!

Thks for Mego/Jonathon Allan for 1 byte.
> 2 votes

# Answer
# 05AB1E, 11 bytes

```
€L.«âOO{γ€g

```

Try it online!

**How it works**

```
€L.«âOO{γ€g - Full program.

€L          - For each N in the list, get [1 .. N].
  .«        - Fold a dyadic function between each element in a list from right to left.
    â       - And choose cartesian product as that function.
     O      - Flatten each.
      O     - Sum each.
       {γ   - Sort, and group into runs of equal adjacent values.
         €g - Get the lengths of each.

```

Saved 1 byte thanks to Emigna!
> 2 votes

# Answer
# , 51 bytes

```
function(D){for(x in D)F=outer(F,1:x,"+")
table(F)}

```

Try it online!

Takes a list of dice and returns a named vector of frequencies; the names (values of the dice sums) are printed above the frequencies.

# , 59 bytes

```
function(D)table(Reduce(function(x,y)outer(x,1:y,"+"),D,0))

```

Try it online!

A `Reduce` approach rather than the iterative one above.

# , 62 bytes

```
function(D)Re(convolve(!!1:D,"if"(sum(x<-D[-1]),f(x),1),,"o"))

```

Try it online!

A convolution approach. It will give a few warnings that it's only using the first element of `D` for the expression `1:D` but it doesn't affect the output. If we didn't have to take the `Re`al part of the solution, it'd be 58 bytes.
> 2 votes

# Answer
# APL (Dyalog Classic), ~~12~~ 10 bytes

-2 thanks to @Adám

```
⊢∘≢⌸+/↑,⍳⎕

```

Try it online!

the input  is a list of N dice

`⍳⍵` is an N-dimensional array of nested vectors - all possible die throws

`+/↑,` flattens the arrays and sums the throws

`⊢∘≢⌸` counts how many of each unique sum, listed in order of their first appearance, which fortunately coincides with their increasing order
> 1 votes

# Answer
# Ruby, 72 bytes

```
->d{r=[0]*d.sum
[0].product(*d.map{|e|[*1..e]}){|e|r[e.sum-1]+=1}
r-[0]}

```

Try it online!

Takes a list of dice as input. No doubt it can be golfed down, but not too bad.
> 1 votes

# Answer
# Pari/GP, 35 bytes

```
v->Vec(prod(i=1,#v,1/(1-x)%x^v[i]))

```

Try it online!
> 1 votes

# Answer
# Clean, ~~154~~ ~~142~~ ~~136~~ ~~107~~ ~~100~~ 85+13=98 bytes

Input is a list of dice.

```
\l#t=foldr(\a-> \b=[x+y\\x<-[1..a],y<-b])[0]l
=[length[v\\v<-t|u==v]\\u<-removeDup t]

```

Answer is in the form of a lambda.

**+13** bytes from `import StdEnv`, which imports the module needed for this to work.

Try it online!
> 0 votes

# Answer
## JavaScript (ES6), 83 bytes

```
f=(n,...a)=>n?f(...a).map((e,i)=>[...Array(n)].map(_=>r[i]=~~r[i++]+e),r=[])&&r:[1]
g=s=>o.textContent=f(...(s.match(/\d+/g)||[]).map(n=>+n)).join`, `
```

```
<input oninput=g(this.value)><p id=o>1
```

Takes input of each die as a separate parameter.
> 0 votes

# Answer
# JavaScript (ES6), ~~76~~ 74 bytes

Takes input as a list of dice.

```
a=>(g=k=>a.map(d=>(s+=n%d|0,n/=d),s=0,n=k)|n?x:g(k+1,x[s]=-~x[s]))(0,x=[])

```

### Test cases

Processing the last two test cases would require to enable TCO or increase the default stack size limit of the JS engine.

```
let f =

a=>(g=k=>a.map(d=>(s+=n%d|0,n/=d),s=0,n=k)|n?x:g(k+1,x[s]=-~x[s]))(0,x=[])

console.log(f([10,10]).join(', '))
console.log(f([1,9]).join(', '))
console.log(f([12,8]).join(', '))
console.log(f([4,4,6,6,6]).join(', '))
console.log(f([3,13,13]).join(', '))
```

### Formatted and commented

*NB: This is a commented version of my initial submission which was using reduce(). It's 2 bytes longer but easier to read.*

```
a =>                    // given the list of dice a
  (g = k =>             // g = recursive function taking k = counter
    a.reduce((k, d) =>  //   for each die d in a:
      (                 //     k % d represents the current face of d
        s += k % d,     //     we add it to the total s
        k / d | 0       //     and we update k to pick the face of the next die
      ),                //     initialization:
      k,                //     start with the current value of k
      s = 0             //     total = 0
    ) ?                 //   reduce() returns 1 as soon as k = product of all dice
      x                 //     in which case we're done: stop recursion and return x
    :                   //   else:
      g(                //     do a recursive call to g() with:
        k + 1,          //       k incremented
        x[s] = -~x[s]   //       x[s] incremented
      )                 //     end of recursive call
  )(0, x = [])          // initial call to g() with k = 0 and x = empty array

```
> 0 votes

# Answer
## Clojure, 96 bytes

```
#(sort-by key(frequencies(reduce(fn[R D](for[d(range D)r R](+ r d 1)))[0](mapcat repeat % %2))))

```

First input is a list of number of dice, and the second input is a list of number of sides on each dice.
> 0 votes

# Answer
# Perl 5, 94 bytes

```
map$k{$_}++,map eval,glob join'+',map'{'.(join',',1..$_).'}',<>;say$k{$_}for sort{$a-$b}keys%k

```

Try it online!

Input format is a list of dice separated by newlines. Thus, 1d10+2d8 would input as:

```
10
8
8

```
> 0 votes

# Answer
## SageMath, 46 bytes

```
lambda*a:reduce(convolution,[x*[1]for x in a])

```

Try it online

This is an adaptation of my solution to the other challenge. It takes in any number of dice as parameters (e.g. `f(4,4,6,6,6)` for `2d4+3d6`), and returns a list.

---

# Python 2 \+ NumPy, 62 bytes

```
lambda*a:reduce(numpy.convolve,[x*[1]for x in a])
import numpy

```

Try it online!

As before, I've included this solution with the above one, since they're essentially equivalent. Note that this function returns a NumPy array and not a Python list, so the output looks a bit different if you `print` it.

`numpy.ones(x)` is the "correct" way to make an array for use with NumPy, and thus it could be used in place of `[x*[1]]`, but it's unfortunately much longer.
> 0 votes

---
Tags: code-golf, integer, probability-theory, statistics
---