title: Random triple with uniform marginals

text:
# Question
Title: Random triple with uniform marginals
Output a random triple \\$(x,y,z)\\$ of real numbers such that

* \\$x+y+z=\frac{3}{2}\\$
* Each of \\$x,y,z\\$, taken alone, is uniformly distributed from \\$0\\$ to \\$1\\$.

Please explain in your answer what distribution your code produces and why it meets these conditions. In particular, please include a demonstration that with many samples produced by running your code many times, the distribution of each variable alone is approximately uniform.

**Allowances for precision**

Since computers can't produce actual real numbers, you can approximate them by outputting any of:

* Floats
* Decimals
* Rationals

I've tried to make the rules here as friendly as possible.

Your outputs need to be accurate within \\$\pm 10^{-3}\\$, that is 3 decimal digits. That means you can imagine that each real-number output from your true distribution has been fudged by at most \\$\pm 10^{-3}\\$ in any way. It's fine if this makes \\$x+y+z\\$ be a bit off from \\$\frac{3}{2}\\$.

You may output rationals as (numerator, denominator) pairs of integers or similar. You may also choose to output just one denominator that applies to all three values, that is, output \\$a,b,c\\$ and \\$d\\$ to represent \\$\frac{a}{d},\frac{b}{d},\frac{c}{d}\\$. Rationals don't have to be in reduced form.

**Randomness**

You can assume any standard PRNG is in fact random. For instance, if it outputs random floats from 0 to 1, you can assume these are uniformly random reals that are independent from each other, and not worry about any endpoint issues. It's also fine if your code fails in a probability-zero event.

To decide whether a pseudo-random source such as time or memory contents is sufficiently random, consider an empirical test where your code is run many times in sequence to check if the randomness varies sufficiently between runs. You may have these runs be done within your language such as in a loop, or by repeatedly calling the code from outside like with a shell command. You may not assume any intentional time delay or other actions taken between runs.

# Answer
# APL (Dyalog Unicode), 15 bytesSBCS

```
1|(-,.5∘-,+⍨)?0

```

Try it online!

A full program that generates three floating-point numbers \\$ X,Y,Z \\$.

### The distribution

Uses the same method as Luis Mendo's MATL answer, which in turn is from this Math.SE answer. The Math.SE answer presents the following random variables:

$$ X = \text{uniform random value in } (0,1) \\ Y = \begin{cases} X + \frac12, \quad X \< \frac12 \\ X - \frac12, \quad X \geq \frac12 \end{cases} \\ Z = \frac32 - (X + Y) $$

I found that this is equivalent to

$$ X = \text{uniform random value in } (0,1) \\ Y = \\{ X + 1/2 \\}, Z = \\{-2X\\} $$

which, in turn, has the same distribution with

$$ r = \text{uniform random value in } (0,1) \\ X = \\{ -r \\}, Y = \\{ 1/2 - r \\}, Z = \\{ 2r \\} $$

where the notation \\$ \\{ x \\} \\$ means the positive fractional part of \\$ x \\$.

### How the code works

```
1|(-,.5∘-,+⍨)?0
             ?0  ⍝ r←Generate a random number from (0,1)
  ( ,    ,  )    ⍝ Create a 3-element array from r:
   -             ⍝ -r
     .5∘-        ⍝ 0.5 - r
          +⍨     ⍝ r + r (= 2r)
1|               ⍝ Extract positive fractional part from each number

```

### Test script

```
⍝ Take 10000 samples of X, Y, Z's
data←f¨⍳10000

⍝ Tests that X+Y+Z = 1.5 in all cases
∧/1.5=+/¨data

⍝ Shows the distribution of X,Y,Z in 10 bins
{(⊂∘⍋⌷⊢)↓,∘≢⌸⍵}¨⌊10×↓⍉↑data
                    ↓⍉↑data  ⍝ Reform the data into X's, Y's, and Z's
                ⌊10×         ⍝ Classify into 10 bins
{             }¨     ⍝ For each of X's, Y's, or Z's,
        ↓,∘≢⌸⍵       ⍝ Gather the list of (bin, count)
 (⊂∘⍋⌷⊢)             ⍝ Sort the bins

⍝ Example result
X:  0 1012  1 1016  2 993   3 1025  4 1002  5 969   6 1002  7 977  8 1049  9 955
Y:  0 969   1 1002  2 977   3 1049  4 955   5 1012  6 1016  7 993  8 1025  9 1002
Z:  0 1013  1 944   2 1022  3 1052  4 990   5 980   6 1039  7 979  8 959   9 1022

```

---

# Alternative method, 21 bytesSBCS

```
(3*9),3⊥¨3|(⍳3)+⊂?9/3

```

Try it online!

This one uses the OP's formulation from the same Math.SE question:

1. Generate a uniform random number \\$ X \\$ from \\$ (0, 1) \\$.
2. Take its ternary digits \\$ X = 0.X\_1 X\_2 X\_3 \cdots \\$ and generate ternary digits of \\$ Y \\$ and \\$ Z \\$:

$$ Y\_i = (X\_i + 1) \\% 3 \\ Z\_i = (X\_i + 2) \\% 3 $$

3. Then the resulting numbers \\$ X,Y,Z \\$ are uniform in range \\$ (0, 1) \\$, and their sum is

$$ \frac3{3^1} + \frac3{3^2} + \frac3{3^3} + \cdots = \frac32 $$

Theoretically it requires infinite number of digits; the code approximates the scheme with just 9 digits, which makes \\$ X+Y+Z=1.499923792 \\$. I'm not exactly sure if it meets the OP's spec though.

### How the code works

```
(3*9),3⊥¨3|(⍳3)+⊂?9/3
                 ?9/3  ⍝ Generate 9 ternary digits
         3|(⍳3)+⊂      ⍝ Ternary digits for X,Y,Z
      3⊥¨  ⍝ Convert each list of digits to numerator for the fraction
(3*9),     ⍝ Prepend the denominator

```
> 10 votes

# Answer
# MATL, ~~18~~ ~~17~~ 11 bytes

```
rt.5+yE_v1\

```

The code is based on this method, and incorporates Bubbler's improvement, which saved 6 bytes.

Try it online! Or see the three marginal histograms for `1000` realizations, using `10` bins on the interval (0,1).

### Commented code

```
r       % Push random number, r, uniformly distributed on (0,1)
t.5+    % Duplicate, add 0.5. Gives r+0.5
yE_     % Duplicate from below, multiply by 2, negate. Gives -2*r
v       % Concatenate the three values into a column vector
1\      % Modulo 1. Implicit display

```
> 8 votes

# Answer
# Wolfram Language (Mathematica), ~~51~~ 48 bytes

```
(.5+Sqrt[3/8]*(#-Mean@#))&@RandomPoint@Sphere[]

```

Try it online!

## Theory

According to this post on MathOverflow about a cool unsolved problem, referencing this other post also on MathOverflow about distributions with nice projections, the following procedure should provide a distribution satisfying the demands of this question:

1. Pick a random point on a sphere.
2. Project (orthogonally) to a fixed plane. The support of the distribution is now a disc, but with a non-uniform distribution.
3. Inscribe this disc in an equilateral triangle. Take the barycentric coordinates of our projected random point within this equilateral triangle.
4. These three coordinates now sum to a constant and have a uniform distribution on their support. Rescale if necessary.

The proof that this works fundamentally comes down to Archimedes's "Hat-Box" Theorem, which is the assertion that a single coordinate of a random point on a sphere has a uniform distribution on its support.

In the solution above, I use the plane x+y+z=0 because it's easy to project to it by subtracting off the mean (one-third of the total x+y+z) from each coordinate. Then I simply need to shift and scale appropriately (I can even skip the barycentric coordinates, which are themselves just a shift and scale here), which a bit annoyingly involves Sqrt\[3/8\]. Perhaps I can save a few bytes by taking an approximate value to the tolerances of the original question.

However, I hope that this answer -- or variants of it -- might be efficient to express in some language.

## Practice

You can run a Kolmogorov-Smirnov test to see if the distribution is correct. Try it online to compare the distribution of the first coordinate of this answer (which has the same distribution as the other two coordinates) with the uniform distribution. Put briefly, we want the result of this test to not be too "close to 0" ("statistically significant").

## Remarks

Fun fact: if you scale the coordinates so that their sum is 1, this can be used to solve a nice problem from the xkcd forums.

> Two generals, who each control the same number of units, each secretly decide how to split their units among three battle fronts. Whoever sends more units to a front wins that front, and whoever wins 2 out of 3 fronts wins overall. Margins of victory are irrelevant. What is the optimal strategy , pure or mixed?
> 7 votes

# Answer
# JavaScript (ES6), 38 bytes

Also derived from this method from math.SE used by Luis.

```
_=>[x=Math.random(),(x+.5)%1,--x*-2%1]

```

Try it online!

### How?

* We pick a uniform random value \\$x \in \[0,1\[\\$
* We define \\$Y=x+\dfrac{1}{2}\\$
* We define \\$Z=2-2x=-2(x-1)\\$

Then we define:

$$y=\cases{ Y&\text{if $Y\<1$}\\ Y-1&\text{if $Y\ge 1$} }$$

and:

$$z=\cases{ Z&\text{if $Z\<1$}\\ Z-1&\text{if $Z\ge 1$} }$$

Which can also be written as \\$y=Y-d\\$ and \\$z=Z-(1-d)\\$ with:

$$d=\cases{ 0&\text{if $x\<1/2$}\\ 1&\text{if $x\ge1/2$} }$$

Leading to:

$$x+y+z=x+\left(x+\dfrac{1}{2}-d\right)+(2-2x-(1-d))=\dfrac{3}{2}$$
> 4 votes

# Answer
# , ~~38~~ 27 bytes

-10 bytes thanks to Nick Kennedy's suggestion of following Bubbler's trick; -1 extra byte by switching \\$X\\$ to \\$1-X\\$.

```
c(x<-runif(1),.5+x,-2*x)%%1

```

Try it online!

The footer on TIO includes a Kolmogorov-Smirnov test of uniformity for the three marginals.

Equivalent to the easier to read:

# , 38 bytes

```
c(x<-runif(1),y<-1-2*x+(x>.5),1.5-x-y)

```

Try it online!

This uses the same method as other answers, rediscovered independently.

Defines \\$X\sim U(0,1)\quad Y = \begin{cases}1-2X\text{ if }X\<\frac12\\2-2X\text{ if } X\geq\frac12\end{cases}\quad Z=\frac32 - X - Y\\$

This way:

* \\$X\sim U(0,1)\\$ by definition
* \\$Y|X\<\frac12\\$ and \\$Y|X\geq\frac12\\$ are both \\$U(0,1)\\$, hence \\$Y\sim U(0,1)\\$
* \\$X+Y|X\<\frac12 = 1-X|X\<\frac12\sim U(\frac12, 1)\\$ and \\$X+Y|X\geq\frac12 = 2-X|X\geq\frac12\sim U(1, \frac32)\\$ hence \\$X+Y\sim U(\frac12, \frac32)\\$ and therefore \\$Z\sim U(0,1)\\$

---

## Alternative method: , 84 bytes

This is much longer, but uses a very different method so I am also posting it (with thanks to Amic Frouvelle).

```
`?`=runif
x=?1
y=?1
if(abs(x+y-1)>.5|(y>.5)!=(x>.5)&abs(x-y)<.5)y=1-y
c(x,y,1.5-x-y)

```

Try it online!

Samples \\$(X,Y)\\$ from the uniform distribution over this shape:

then lets \\$Z=\frac32-X-Y\\$. These histograms show that the marginals are uniform:
> 3 votes

# Answer
# C++ (clang), ~~206~~ ... ~~163~~ 160 bytes

```
#import<random>
std::vector<double>f(){std::random_device r;std::mt19937 g(r());auto x=std::generate_canonical<double,53>(g),y=x+(x<.5)-.5;return{x,y,1.5-x-y};}

```

Try it online!

Uses the C++ library's Mersenne twister engine to generate uniform random numbers with \\$53\\$ bits of randomness in \\$\[0,1)\\$.
I realise we only need to be accurate within \\$3\\$ decimal digits, but that's going to be at least \\$10\\$ bits so might as well go the whole hog with \\$53\\$ (the number of bits in the mantissa part of a `double`).
Also uses @Bubbler's method to calculate \\$(x, y, z)\\$.

Ungolfed:

```
#include <random>
#include <vector>

std::vector<double> f() {
    std::random_device rand_dev;
    std::mt19937 generator(rand_dev());
    double x = std::generate_canonical<double, numeric_limits<double>::digits>(generator);
    double y = x;
    if (y < 1./2) {
        y += 1./2;
    } else {
        y -= 1./2;
    }
    double z = 3./2 - x - y;
    return {x, y, z};
}

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 79 bytes

```
Sqrt[1-r[]^2]{Sin@#,Cos@#}.{{1,1,-2},Sqrt@3{1,-1,0}}/4&[2Pi(r=RandomReal)[]]+.5

```

Try it online!

A bit longer but using the direct `Sqrt[1-r^2]` distribution on the 2D disc, then rotating and translating the disc into 3D.
> 1 votes

# Answer
# 05AB1E, ~~14~~ 17 bytes

```
₄L¨₄/Ωx¦1αsD.5+¦)

```

Port of *@Bubbler*'s approach, so make sure to upvote him!

Try it online.
This approach uses random integers in the range \\$(0,1)\\$.

The footer of the TIOs (`=O,`) is to verify the result equals `1.5`, which will `=` (print without popping); `O` (sum); `,` (pop and print).

**Explanation:**

```
₄L            # Push a list in the range [1,1000]
  ¨           # Remove the last value to make the range [1,1000)
   ₄/         # Divide each value by 1000 to make the range [0.001,1) in increments of 0.001
     Ω        # Pop and push a random value of this list
              # (NOTE: 05AB1E doesn't have a random builtin within the range [0,1))
      x       # Double this value without popping
       ¦      # Remove the first digit (the integer portion)
        1α    # And take the absolute difference with 1
      s       # Swap to take the original random value again
       D      # Duplicate it
        .5+   # Add 0.5 to it
           ¦  # And remove the first digit (the integer portion)
            ) # Then wrap all (three) values on the stack into a list
              # (after which this list is output implicitly as result)

```

---

```
₄L₄/3ãʒO3;α_}Ω

```

Try it online (way too slow for TIO, so will use \\$10^{-1}\\$ accuracy instead of \\$10^{-3}\\$ by replacing the s (1000) with `T`s (10)).
This approach uses random integers in the range \\$(0,1\]\\$.

This previous **14 bytes** answer above unfortunately didn't had marginal distribution. The \\$x,y\\$ values had the same distribution, but the \\$z\\$ values were always slightly larger in terms of marginal distribution. Here for example the distribution for the \\$x,y,z\\$ values with steps of \\$0.1\\$. These total values will be larger for the actual steps of \\$0.001\\$ of course, but the \\$x,y\\$ values will always be the same, and \\$z\\$ unfortunately always slightly larger.

```
₄L            # Push a list in the range [1,1000]
  ₄/          # Divide each value by 1000 to make the range [0.001,1] in increments of 0.001
    3ã        # Cartesian product of 3, to create all possible triplets of these values
      ʒ       # Filter these triplets by:
       O      #  Sum the three values
        3;α   #  Take the absolute difference with 3/2
           _  #  And check if it's equal to 0
      }Ω      # After the filter: pop and push a random triplet from this filtered list
              # (which is output implicitly as result)

```
> 1 votes

# Answer
# Ruby, 25 bytes

```
p x=rand,(x+0.5)%1,-2*x%1

```

Try it online!

Based on the same method as most other answers.
> 0 votes

# Answer
# Jelly, 12 bytes

```
ȷX÷¤._;Ḥ;N%1

```

Try it online!

A niladic link that returns a list of 3 floats, accurate to within \\$\pm 10^{-3}\\$, that is 3 decimal digits, and summing to 1.5. Footer demonstrates the sum.

Uses the same method developed by Bubbler.
> 0 votes

# Answer
# Perl 5, 50 bytes

```
$x=rand;$f=$x<.5;say for$x,$x-.5+$f,3/2-2*$x+.5-$f

```

Try it online!

This answer takes seriously the first word of the question: output (as a verb). Many other answers here moves the output part outside of the byte count :-)
> 0 votes

---
Tags: code-golf, random
---


# Question
Title: Probabilistically fair prize splitting for two-player coin toss
## Introduction

> Adam (A) and Bubbler (B) are playing coin toss, where the one who wins 5 times first would win the prize of $32. If the game is aborted when the scores are `A:B = 4:3`, how should they distribute the prize? Assume the coin toss is fair, so the winning chance of either player is 1/2 for each game.

The answer is:

> Adam should take $24 and Bubbler should take $8. Possible cases are as follows:
>
> ```
> A wins (score 5:3, chance 1/2): A wins the prize
> B wins (score 4:4) then A wins (score 5:4, chance 1/4): A wins the prize
> B wins (score 4:4) then B wins (score 4:5, chance 1/4): B wins the prize
>
> ```
>
> Therefore, the chance of A winning is `3/4` and that of B is `1/4`.

## Challenge

In order to do the fair splitting of prizes, we should compute the chance of winning the prize for each player. Given the following information,

* `X`, how many times a player should win coin toss to win the prize
* `Wa`, how many times player A has already won
* `Wb`, how many times player B has already won

compute the chance of **player A** winning the prize.

## Input and output

You can assume the three input numbers `X`, `Wa`, `Wb` satisfy the following:

* All numbers are non-negative integers.
* `X > max(Wa, Wb)`, i.e. the game hasn't finished already.

You can choose to output a fraction or a floating-point number.

## Scoring and winning criterion

Standard rules apply. Shortest code in bytes wins.

## Test cases

```
X Wa Wb => Expected output
--------------------------
5  4  3 =>  3/4  = 0.75
5  3  4 =>  1/4  = 0.25
1  0  0 =>  1/2  = 0.5
4  3  1 =>  7/8  = 0.875
4  2  1 => 11/16 = 0.6875
6  4  2 => 13/16 = 0.8125

```

# Answer
# , ~~36~~ 32 bytes

```
function(X,A,B)pbeta(.5,X-A,X-B)

```

Try it online!

The closed formula from this answer suggested a natural probability distribution to use -- this is a Negative Binomial with \\$X - W\_b - 1\\$ failures and \\$X - W\_a\\$ successes, i.e., the probability that there are \\$X - W\_a\\$ "successes" before there are \\$X - W\_b\\$ "failures".

Further identities reduce the CDF of the negative binomial to the CDF of a beta distribution or in terms of the (regularized) incomplete beta function.
> 9 votes

# Answer
# Wolfram Language (Mathematica), 44 bytes

```
Binomial[g=#-#2+t,k]~Sum~{k,0,t=#-#3-1}/2^g&

```

Try it online!

Not super short, but uses an algorithm that might lead to shorter code in other languages: the code calculates the sum of binomial coefficients  which is the closed form for the result of the path-counting algorithms in other solutions.
> 5 votes

# Answer
# Python 2, ~~62~~ 56 bytes

```
f=lambda n,a,b:a<n>b and(f(n,a+1,b)+f(n,a,b+1))/2.or a>b

```

Try it online!

Returns a float. Uses a recursive approach.

Ungolfed:

```
def f(n,wa,wb):
    if wa<n and wb<n:
        return (f(n, wa+1, wb) + f(n, wa, wb+1))/2.0
    elif wa==n: return 1
    else: return 0

```
> 4 votes

# Answer
# MATL, 24 bytes

```
x"TF1GEZ^!Ys@+1G<~s]P>Ym

```

Try it online! Or verify all test cases.

Input is `X`, then `[Wa Wb]`. Output is a floating-point number.

### How it works

This enumerates all possible paths of length `2*X` that emanate from the initial conditions defined by `Wa` and `Wb`. This length is enough to ensure that someone wins (actually length `2*X-Wa-Wb-1` would suffice).

For each path, the code determines who wins as follows. It keeps a cumultive sum of score for each player, computes how long each player has had score `X` or more along the path, and the winner is the player who has maintained that condition for longer. This is equivalent to, but golfier than, asking who reached `X` earlier in that path. Note that there can be no ties.

The result is the proportion of paths in which player A wins.

```
x      % Implicit input: X. Delete it
"      % Implicit input: [Wa Wb]. For each
  TF   %   Push [0 1]
  1G   %   Push X
  E    %   Multiply by 2
  Z^   %   Cartesian power of [0 1] with exponent 2*X. Gives a matrix with each
       %   Cartesian tuple contained in a row. Rows are in lexicographical order
       %   Each column is a step in the path, containing 1 if the user wins or 0
       %   otherwise
  !    %   Transpose. Each tuple is now a column
  Ys   %   Cumulative sum of each column. This is the accumulated gain along each
       %   path. Note that the matrix has more than one row; otherwise the
       %   cumulative sum would work along the single row
  @    %   Push Wa (first iteration) or Wb (second iteration)
  +    %   Add. This gives the total accumulated score along each path, including
       %   the initial score
  1G   %   Push X
  <~   %   Not less than?
  s    %   Sum of each column. This indicates for how long the score X has been
       %   reached, or exceeded, in each path
]      % End
P      % Flip. This reverses the results for player B, to reflect the fact that
       % the paths of the two users are complementary: user B increases their
       % score when user A doesn't. Reversing the vector is equivalent to
       % replacing each path by its complement, thanks to the lexicographical
       % order of the Cartesian tuples
>      % Greater than? This indicates for which paths player A wins
Ym     % Mean. Implicit display

```
> 3 votes

# Answer
# Jelly,  ~~17 16~~  14 bytes

-2 thanks to Kevin Cruijssen

```
_µS’2*ḶB§‘>ḢÆm

```

A dyadic Link accepting the end-goal, `X`, on the left and the current state `[Wa,Wb]` on the right which yields a float of A's chances.

**Try it online!**

### How?

Forms all binary strings of \\$X-Wa+X-Wb-1\\$ bits, treating 1s as a win for A and 0s as a win for B. Identifies those with at least \\$X-Wa\\$ 1s and takes the mean (i.e. winCount / total).

```
_µS’2*ḶB§‘>ḢÆm - Link: X, [Wa, Wb]
_              - subtract (vectorises)   -> V=[X-Wa, X-Wb]
 µ             - start a new monadic chain, f(V)
  S            - sum                          X-Wa+X-Wb
   ’           - decrement                    X-Wa+X-Wb-1
    2*         - two raised to that power     2^(X-Wa+X-Wb-1)
      Ḷ        - lowered range                [0,1,2,3,4,...,2^(X-Wa+X-Wb-1)-1]
       B       - to binary (vectorises)       [[0],[1],[1,0],[1,1],[1,0,0],...,[1,1,...,1]]
        §      - sums                         [0,1,1,2,1,...,X-Wa+X-Wb-1]
         ‘     - increment (vectorises)       [1,2,2,3,2,...,X-Wa+X-Wb]
           Ḣ   - head (V)                     X-Wa
          >    - greater than? (vectorises) A=[0>=X-Wa,1>=X-Wa, ...]
            Æm - mean                         A's win probability

```
> 3 votes

# Answer
# MATL, 11 bytes

```
.5ii-Z}3$Yg

```

Try it online!

This is a port of my R answer. Thanks to Luis Mendo for helping golf it down.

```
.5     # push .5
ii     # push both inputs, X, and [Wa, Wb]
-      # subtract, so stack is [.5, [X - Wa, X - Wb]]
Z}     # split array onto stack
       # so stack is [.5, X - Wa, X - Wb]
3$Yg   # (regularized) incomplete beta function with 3 arguments
       # implicitly output the probability
```

Also a nice short Octave solution:

# Octave, 27 bytes

```
@(X,A,B)betainc(.5,X-A,X-B)

```

Try it online!
> 3 votes

# Answer
# Jelly, 12 bytes

```
_Ä’Żc@SH⁹¡ʋ/

```

Try it online!

A dyadic link taking the number to win as left argument and the coin tosses won so far by players b and a respectively as the right argument.

Based on the formula described by @GregMartin so be sure to upvote his answer too!

## Explanation

```
_            | Subtract
 Ä           | Cumulative sum
  ’          | Decrease by 1
          ʋ/ | Reduce using the following as a dyad (left argument represents X - Wb - 1; right argument represents 2X - Wa - Wb - 1)
   Ż         | - Range from 0..left argument
    c@       | - Number of combinations for each using right argument as n
      S      | - Sum
       H⁹¡   | - Half the number of times indicated by the right argument

```

# Jelly, 16 bytes

```
MḢ’¹2Ṭ+Çɗ€ÆmƊ}Ị?

```

Try it online!

An alternative Jelly answer that uses a recursive approach. A full program that takes as its argument a list of `Wb, Wa, n` and returns the answer as a float.

## Explanation

```
M                | Indices of maximum
 Ḣ               | Head
  ’              | Subtract 1
              Ị? | If absolute of this less than or equal to one:
   ¹             | Then: Return this value
            Ɗ}   | Else following as a monad applied to the original argument to this link:
    2            | - Literal 2
        ɗ€       | - Apply the following to the implicit range 1..2 with the original argument as the right argument
     Ṭ           |   - Convert to logical list with 1 at the relevant index
      +          |   - Add to the original argument (effectively increments Wa for 1 and Wb for 2)
       Ç         |   - Call this link with the updated argument
          Æm     | - Arithmetic mean

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 32 bytes

```
Beta[.5,a=#-#2,b=#-#3]/a~Beta~b&

```

Try it online!

Yet another port of the negative binomial CDF approach suggested by this answer.
> 2 votes

# Answer
# Charcoal, 36 bytes

```
Ｎθ≔Ｅ⁻θＮ⁰ηＦＥ⁻θＮ¹ＦＬη«≔⊘⁺ι§ηκι§≔ηκι»Ｉ⊟η

```

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

```
Ｎθ

```

Input the desired number of coin tosses.

```
Ｅ⁻θＮ⁰η

```

Calculate the number of remaining tosses player A needs, and create an array of that length of zeros. The (1-indexed) `n`th entry represents that the probability of `A` winning given that he still has `n` tosses remaining and `B` initially has no tosses remaining.

```
ＦＥ⁻θＮ¹

```

Loop over the number of remaining tosses player B needs. Start with the probability of `A` winning given that he still has `0` tosses remaining and `B` has `m` tosses remaining as `1`.

```
ＦＬη«

```

Loop over the probabilities.

```
≔⊘⁺ι§ηκι

```

Average the current probability (representing the case where `A` wins this toss) with the probability from the array (representing the case where `B` wins this toss).

```
§≔ηκι

```

Save this new probability in the array.

```
»Ｉ⊟η

```

Output the last probability calculated, which is for `n=X-Wa,m=X-Wb`.
> 1 votes

# Answer
# JavaScript (Node.js), 44 bytes

```
a=>g=(b,c)=>a==b||a>c&&(g(b+1,c)+g(b,c+1))/2

```

Try it online!
> 1 votes

# Answer
# Java (JDK), 77 bytes

```
double f(int x,int a,int b){return(a<x&b<x?f(x,a+1,b)+f(x,a,b+1):a>b?2:0)/2;}

```

Try it online!

## Credits

## Iterative version, 89 bytes

```
(x,a,b)->{int r=0,i=1<<x*2>>a-~b,n=i;for(;i-->0;)r+=x.bitCount(i)<x-a?0:1;return 1.*r/n;}

```

Try it online!
> 1 votes

# Answer
# Perl 6, 45 bytes

```
{m:g/\-//$_}o{[X+] .[1],|(^2 xx+^.sum)}o&[X-]

```

Try it online!

Takes arguments as `f((a, b), x)`. Counts `2x-a-b-1`-bit numbers with popcount less than `x-b`.

### Explanation

```
                                        &[X-]  # Compute a-x, b-x
             {                        }o  # Feed into block
                          ^2            # Range 0..1
                             xx         # repeated
                               +^.sum   # ~(a-x+b-x) = 2x-a-b-1 times
                        |(           )  # flattened
                   .[1]   # b-x
              [X+]     ,  # Cartesian product with addition,
                          # computes popcount(i)-(x-b) for all i
{          }o  # Feed into block
 m:g/\-/  # Regex match '-' chars in string representation,
          # counting negative values
        /$_  # Divide by number of values

```
> 1 votes

# Answer
# 05AB1E, 14 bytes

```
-¤sO<oL<2вO›ÅA

```

Inputs in the format and order `[Wa, Wb], X`.

Port of *@JonathanAllan*'s Jelly answer.

Try it online or verify all test cases.

A port of *@GregMartin*'s formula would be 16 bytes:

```
-¤sO<UFXNc}OXoz*

```

Try it online or verify all test cases.

**Explanation:**

```
-               # Subtract each value of the first (implicit) input-pair from the second
                # (implicit) input: [X-Wa,X-Wb]
 ¤              # Push its last value (without popping the list itself): X-Wb
  s             # Swap to get the list again
   O            # Sum them together: 2X-Wa-Wb
    <           # Decrease it by 1: 2X-Wa-Wb-1
     o          # Take 2 to the power this: 2^(2X-Wa-Wb-1)
      L         # Pop and push a list in the range [1,2^(2X-Wa-Wb-1)]
       <        # Decrease each value by 1 to make it [1,2^(2X-Wa-Wb-1))
        2в      # Convert each to a binary-list
          O     # Sum each inner list of bits
           ›    # Check for each if it's larger than the X-Wb: [X-Wb>1,X-Wb>2,...]
            ÅA  # Take the arithmetic mean of that list
                # (which is output implicitly as result)

-¤sO<           # The same as above
     U          # Pop and store this 2X-Wa-Wb-1 in variable `X`
      F         # Loop `N` in the range [0,X-Wb):
         c      #  Take the binomial coefficient (a.k.a. number of combinations) of:
       X        #   The 2X-Wa-Wb-1 of variable `X`
        N       #   And the loop-index `N`
      }O        # After the loop: sum all values on the stack
        X       # Push 2X-Wa-Wb-1 from variable `X` again
         o      # Take 2 to the power this: 2^(2X-Wa-Wb-1)
          z     # Take the invert of this: 1/(2^(2X-Wa-Wb-1))
           *    # And multiply it with the sum
                # (after which this is output implicitly as result)

```
> 1 votes

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


title: Python Code Reviewer

text:
# Question
Title: Python Code Reviewer
## Task

Your mission is to create a program that reviews Python code. The solution can be written in any language!

It must take input that contains python code. The program must add `# This is not pythonic!` before each block of non-whitespace lines.

## Input

* The data can be entered via stdin.
* The data will contain at least 3 lines with one blank one in between them.

**Minimum input example.**

```
print "Hello World!"

Print "Bye World!"

```

**Sample Input**

```
from os.path import abspath

lines = []
with open(__file__, 'r') as f:
    for line in f:
        lines.append(line)

if lines is not None:

    newLines = []
    hasReviewedBlock = False

    for line in lines:
        if len(line) > 1: # \n
            if hasReviewedBlock == False:
                newLines.append("# This is not pythonic!\n")
                hasReviewedBlock = True
        else:
            hasReviewedBlock = False

        newLines.append(line)
    with open("d:/test.py", 'w') as f:
        for line in newLines:
            f.write(line);

```

## Output

Output has to be written to STDOUT or closest alternative.

## Sample Output

```
# This is not pythonic!
from os.path import abspath

# This is not pythonic!
lines = []
with open(__file__, 'r') as f:
    for line in f:
        lines.append(line)

# This is not pythonic!
if lines is not None:

# This is not pythonic!
    newLines = []
    hasReviewedBlock = False

# This is not pythonic!
    for line in lines:
        if len(line) > 1: # \n
            if hasReviewedBlock == False:
                newLines.append("# This is not pythonic!\n")
                hasReviewedBlock = True
        else:
            hasReviewedBlock = False

# This is not pythonic!
        newLines.append(line)
    with open("d:/test.py", 'w') as f:
        for line in newLines:
            f.write(line);

```

## Scoring:

Lowest number of bytes wins. -5 bytes if your program can be used as valid input.

# Answer
> 4 votes
# awk, 64 56 54 bytes

```
/^$/{i=0}/./{if(!i++)print"# This is not pythonic!"}1

```

**Test:**

```
echo '/^$/{i=0}/./{if(!i++)print"# This is not pythonic!"}1' > solution.awk
awk -f solution.awk < pyth.py
awk -f solution.awk < pyth.py

```

**Explanation:**

`/^$/` \- matches empty line,

`/./` \- matches non-empty line,

`1` \- matches each line. No body is equivalent to `{print;}` \- each line of input is printed.

# Answer
> 3 votes
# Pyth, ~~39~~ ~~38~~ 37 bytes

```
tjbm|d+b"# This is not pythonic!"+k.z

```

Live demo.

## Explanation

```
tjbm|d+b"# This is not pythonic!"+k.z
                                 +k.z    Prepend the empty line to the string
   m                                     For each line
    |d                                   If it's non-empty, return the same line
      +b"# This is not pythonic!"        Else, return a line break followed by the required text
 jb                                      Join via line breaks
t                                        Remove the unneeded preceding line break

```

# 38-byte version

```
tjbm?dd+b"# This is not pythonic!"+k.z

```

# 39-byte version

```
jbtsm?dd,d"# This is not pythonic!"+k.z

```

~~No doubt there's still golfing left to do.~~

# Answer
> 2 votes
## AutoIt - 139

```
$1='# This is not pythonic!'
ConsoleWrite($1&@CRLF&StringRegExpReplace(FileRead($CmdLine[1]),'(*BSR_ANYCRLF)(^\R|\R(?=\R))',"\0"&@CRLF&$1))

```

I'm assuming the first line cannot be empty as by your specification:

> The data will contain at least 3 lines with one blank one in between them.

This program is called like this:

```
compiled.exe pycode.py > output.txt

```

The RegEx can be optimized for sure. Works for `CRLF` only.

# Answer
> 2 votes
# Python 3, 86 bytes - 5 = 81

```
import re

print(re.sub(r"(^\n*|\n\n+)",r"\1# This is not pythonic\n",open(0).read()))

```

Try it online!

---

# Python 3, 94 bytes - 5 = 89

```
p=''

for c in open(0).read().splitlines():print("# This is not pythonic!\n"*(p==''!=c)+c);p=c

```

Try it online!

# Answer
> 2 votes
# Wren, 73-5 = 68 bytes

Luckily enough, Wren has an automatic WYSIWYG that gains the bonus.

```
Fn.new{|i|("

"+i).split("

").join("

# This is not pythonic!
")[2..-1]}

```

Try it online!

## Explanation

Fn.new{|i|    // In this case we define a new
              // anonymous function with the operand i
          ("

"+i)          // We prepend the input with 2 newlines
    .split("

")            // Split the input by newlines,
              // including the preceding newlines
              // that we first prepended
  .join("

# This is not pythonic!
")            // Join the input with 2 newlines
              // , the comment, and another trailing newline
  [2..-1]}    // Slice the input so that the preceding
              // 2 newlines are not present in the final output
```
</code></pre>

# Answer
> 2 votes
# Perl 6, 40 - 5 = 35 bytes

```
{S:g/^|"

"<(/# This is not pythonic!
/}

```

Try it online!

The bonus is rather weird, but it didn't cost me any bytes to add.

### Explanation

```
{S:g/        /   /}  # Substitute all instances of
     ^                 # The start of the string
      |"  "            # or two newlines
           <(          # But don't actually replace, just append
              ...    # With the given string

```

# Answer
> 1 votes
# CJam, 41 bytes

```
"# This is not pythonic!":TNqN/{_{T}|}%N*

```

Try it online

Alternate solution that handles multiple empty lines in succession, as well as empty lines at the start. This is 44 bytes, and will become my solution depending on how the pending clarifications turn out:

```
qN/{_L!e&{"# This is not pythonic!"\}&:L}%N*

```

# Answer
> 1 votes
# JavaScript (ES6), 70

Test running the snippet below.

```
f=p=>alert((r='# This is not pythonic!\n')+p.replace(/\n\n+/g,x=>x+r))

//// TEST CASES /////

t1=`print "Hello World!"

Print "Bye World!"`
f(t1)

t2=`from os.path import abspath

lines = []
with open(__file__, 'r') as f:
    for line in f:
        lines.append(line)

if lines is not None:

    newLines = []
    hasReviewedBlock = False

    for line in lines:
        if len(line) > 1: # \n
            if hasReviewedBlock == False:
                newLines.append("# This is not pythonic!\n")
                hasReviewedBlock = True
        else:
            hasReviewedBlock = False

        newLines.append(line)
    with open("d:/test.py", 'w') as f:
        for line in newLines:
            f.write(line);`
f(t2)
```

---
Tags: code-golf, python
---


# Question
Title: Shortest Solution in Python 3 for Caught Speeding - CodingBat
I am trying to find the shortest code in **python 3**, to solve this problem:

You are driving a little too fast, and a police officer stops you.

Write code to take two integer inputs, first one corresponds to speed, seconds one is either 1 or 0, corresponding to True and False respectively to indicate whether it is birthday. Then compute the result, encoded as an int value:

0=no ticket,

1=small ticket,

2=big ticket.

If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.

```
input:
60
0
Output:
0

input:
65
0
Output:
1

input:
65
1
output:
0

```

Here's my shortest solution (`57 chars`). Is there any way I can make it shorter in Python?

```
print(min(2,max(0,(int(input())-5*int(input())-41)//20)))

```

Reference: *Problem inspired from this*

# Answer
> 15 votes
# Python 3, 32 bytes

```
lambda a,b:(a-b*5>60)+(a-b*5>80)

```

Try it online!

---

# Python 3, <sup>~~50~~</sup> 49 bytes

If io must be done with stdin and stdout

```
a,b=map(int,open(0));print((a-b*5>60)+(a-b*5>80))

```

Try it online!

-1 byte thanks to @dingledooper

# Answer
> 2 votes
# Python 3, ~~51~~ 45 bytes

```
lambda a,b:min(2,max(0,(a//1-5*b//1-41)//20))

```

Try it online!

I was able to shave 6 bytes from your approach by using everyone's favourite python golfing keyword: `lambda`.

This turns your program into an anonymous function, which then can be called in the footer of a program.

Edit: I know that this question is way old, but I only just recently thought of using `//1` to convert things to an integer instead of using `int(...)`.

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


# Question
Title: Count up from 0 to 2017 without numbers in your source
This question was profoundly inspired by Joe Z's question.

But, with a twist...

So, now that it's almost 2017, it's time for a code question involving the number 2017.

Your task is to make a program that **counts up from 0, printing each number until it reaches 2017.** without using any of the characters `012345678` or `9` in your code; and without using any variables such as the date or time or a random number.

# Acceptable Output

The output of your code must follow the following format:

```
[number]
[number]
[number]
etc.
```

A number, then a line feed, then repeat.

> The shortest code (counting in bytes) to do so in any language in which numbers are valid tokens wins.

# Example Output:

```
0
1
2
3
4
...
2016
2017

```

# Answer
# Jelly, 6 bytes

```
“¬×’ḶY

```

Try it online!

Explanation:

```
“¬×’ḶY Main link. Arguments: 0
“¬×’              2018
    Ḷ             Range [0..z)
     Y            Join z by newlines

```
> 3 votes

# Answer
## PowerShell v2+, 15 bytes

```
''..+[char]'ߡ'

```

UTF-8 code point `2017`, `ߡ`, functions as our upper bound. We turn it from a string into a `char` with `['']`, then to an int with `+`. The lower bound `''` is implicitly cast to `0`. Thus, this is the range operator `..` from `0` to `2017`. Default `Write-Output` prints each number with newlines between.
> 5 votes

# Answer
# APL (Dyalog APL), 13 bytes

Requires `⎕IO←0` which is default on many systems.

```
⍳⎕UCS'ߢ'

```

TryAPL online!

N first indices, where N is

`⎕UCS` the Unicode code point of

`'ߢ'` this character
> 3 votes

# Answer
## Java, 99 bytes

Hobbyist programmer here. This is my first golf so apologies if I mess things up. Of course since I wrote in Java my code is going to be very large, but I think this may be as far as Java can go.

Golfed:

```
interface D{static void main(String[]z){for(int i='a'-'a';i<'ÿ'*''+'é';)System.out.println(i++);}

```

Ungolfed:

```
interface D{
    static void main(String[]z){
        for(int i='a'-'a';i<'ÿ'*''+'é';) //Between the seemingly empty quotes is an enquiry character with an ASCII value of 7, which has been included in the byte count and post.
            System.out.println(i++);
    }
}

```

Explanation: This solution abuses the interaction Java's compiler has with chars. Since Java interprets ASCII characters as bytes, I can use that fact to do arithmetic without actually ever using a number. The y with a diaeresis ASCII 255, enquiry is 7, and the acute e is 233 (so I can have 2017 be included). Hopefully this isn't too cheaty to do!
> 3 votes

# Answer
# 05AB1E, 8 bytes

```
žCžw<-Ý»

```

Try it online!
> 2 votes

# Answer
# MATL, ~~15~~ 11 bytes

*4 bytes saved thanks to @Luis*

```
'? 'pQQ:q"@

```

**Try it Online!**
> 2 votes

# Answer
# Labyrinth, 49 43 40 bytes

```
))::+:#:*:
@        (
(\"))****(
{ }
)!:

```

Try it online!
> 2 votes

# Answer
# , 29 bytes, 78 characters

Not going to win, but I had fun writing it. 7 uses a 3-bit character set that packs 8 characters into 3 bytes. Here's the program in octal encoding (which is most natural for the language):

```
770267133177162277266362217240522405240540562240540554240524052405052405405513

```

and here's how it looks on disk (via an `xxd` dump); looking on the right, we can verify that the file contains no digits:

```
00000000: fc2d cb67 f392 fd6c f247 a82a 5055 0582  .-.g...l.G.*PU..
00000010: e4a0 b05b 1415 4154 1455 0582 d2         ...[..AT.U...

```

Try it online!

Underload is the brainfuck of stack-based languages, and 7 is a variant of Underload modified to provide I/O capabilities and to reduce the size of the command set. (The command set had to be modified to allow for things like outputting mismatched parentheses.) So this is an example of how to write this program in a very primitive and low-level language.

Here's how the program works:

```
77026

```

We start by pushing the stack element `02`, escaped once (thus it'll still appear as `02` on the stack; normally there's one level of unescaping). To push a stack element in 7, you precede it with a `7`, and enclose any parts you want to escape in `7``6`.

```
7 133  17 716 22 77266 36
        ( ( )    (( ))  )

```

The rest of the program is all stored in one large stack element. (In 7, there's no way to write code that runs immediately; you have to start by pushing it as a literal to the stack, then rely on it getting appended to the program implicitly when the program runs out of space.) We start by discarding the large stack element in question (`13`), then outputting the element below (`3`); that's `02`. The first output of the program sets the output format the program uses. In this case, we're using output format 0, "integers". That accounts for (and removes) the zero. The output format we're using works by counting the number of 7s and 1s in the output string, and subtracting the number of 6s and 0s, to produce the integer to output; in this case, the string `2` has no 0s, 1s, 6s, or 7s, so it outputs `0`. Finally, a trailing 2 (in this output format) produces a newline (the output would "naturally" be space-separated). After that, we push a large literal to the stack. This will eventually be used as a loop body, so we'll consider it when it runs.

```
22 1724052240524054056 2240540554240524052405052405405

```

Some people here may be used to Underload numerals from a previous challenge. 7 numerals are fairly similar. In the linked challenge, the only characters used were `:` and `*`; numbers represented like that can translate into 7 directly, with `2` serving the role of `:` and `405` serving the role of `*` (note that it's actually equivalent to Underload's `~*`, but the two act identically in this context). Thus, given a number *n*, you can add 1 to it using `2*n*405`, and you can multiply two numbers by appending them to each other; the null string is 1. One thing the linked challenge *didn't* mention, though, is exponentiation. This works a little differently in 7 than in Underload, but the same basic principles are in use in each case. Additionally, in 7, you can handle addition via putting code between the `4` and `05` (something that's more verbose in Underload because you can't put code *inside* the `*`). So we can restructure this part of the program like this:

```
2
   2
    17         start a new number (=1)
      2405     ×2                 (=2)
      2        ×(1          (=1)
         2405     ×2        (=2)
         2405     ×2        (=4)
      405       +1          (=5)) (=10)
     6         end of the new number
     2         ×(1          (=1)
        2405      ×2        (=2)
     405        +1          (=3)) (=3)
    5          exponentiate (10 ^ 3 = 1000)
   4           +(1          (=1)
     2405         ×2        (=2)
     2405         ×2        (=4)
     2405         ×2        (=8)
   05           )                 (=1008)
   2405        ×2                 (=2016)
405            +1                 (=2017)

```

The rest of the program is:

```
5 13

```

The `5` starts a loop, running the stack literal we pushed earlier 2017 times. Finally, the `13` pops the top stack element, meaning that the stack is now empty and the program ends.

So what does the loop body do? Here's how it decodes:

```
716      Append a 1 to TOS
22       Make two more copies of the TOS
77266    Append a 2 to TOS
3        Output TOS, discard top two stack elements

```

Appending a 1 will increase the numerical value (initially zero) that numeric output will see the stack as having. We make two temporary copies, and append a 2 (to provide the newline required by the question). Then we output it, discarding the temporary copies in the process. Doing this 2017 times will thus count from 1 to 2017. We outputted the 0 earlier, thus completing the program.
> 2 votes

# Answer
# \>\<\> (Fish) 19 bytes

```
iaa,+:n:"#:"*d-=?;ao!

```

very simple, uses ascii chars to generate the number 2017 then compares to an increasing counter that gets printed.

i is input but without one becomes -1 a = 10 so aa, is 1 (10 div 10) "#:" becomes (# multiply :) which makes 2030 which we take 13 (d) from to make 2017 (This number is a prime so we can't save bytes here).
> 2 votes

# Answer
## Java, 147 bytes

Call with no `cmd` args

```
class t{public static void main(String[]a){int i=a.length,j=++i,h;j+=i--;h=j*j*j*j*j;j=h*j*j*j*j*j*j-(--h);j++;for(;i<j;)System.out.println(i++);}}

```
> 2 votes

# Answer
## Python 3, 32 bytes

```
print(*range(ord('ߢ')),sep='\n')

```
> 2 votes

# Answer
## (K+R)eg, 9 bytes

```
ߡï(.\
,

```

Explanation:

```
ߡ      # Push 2017
 ï     # Count all the way from 0
       # Due to the irritating output-without-newline:
  (    # Repeat the length of the stack times:
   .   # Output the top of the stack
    \ ,# Output 1 newline

```

TIO
> 2 votes

# Answer
## JavaScript (ES6), 52 bytes

```
for(n=x=+[],i=++x+x+''+n;n<i+i-x-x;)console.log(n++)

```

There's not much to say about it:

```
for(
  n = x = +[],              // n = x = 0
  i = ++x + x + '' + n;     // i = 1 + 1 + '' + 0 = "20"
  n < i + i - x - x;        // n < "2020" - 1 - 1 <=> n < 2018
)
console.log(n++)

```
> 1 votes

# Answer
# Stax, 6 bytes

```
ÇîHtUá

```

Run and debug it

Use packing to avoid appearance of the digits.
> 1 votes

# Answer
# Japt `-R`, ~~5~~ 4 bytes

```
#ߢo

```

Test it
> 0 votes

# Answer
## `n` `d`, 7 bytes

```
♦kb-╖úÜ

```

## Explanation

Uncompressed:

2018   M % Foreach in the range 1..2018:
    a1-  % Return the current item - 1

Flags:n  % Join the output with newlines
```

> 0 votes

---
Tags: restricted-source, code-golf
---


title: Stewie's sequence: + * - / + * - /

text:
# Question
Title: Stewie's sequence: + * - / + * - /
Let's use the four basic operations, addition `+`, multiplication `*`, subtraction `-` and division `/` (float, not integer).

***Stewie's sequence*** is defined as follows:

```
x = [x(1), x(2)]    // Two initial numbers (one indexed)
x(3) = x(1) + x(2)
x(4) = x(2) * x(3)
x(5) = x(3) - x(4)
x(6) = x(4) / x(5)
x(7) = x(5) + x(6)
... and so on.

```

**Challenge:**

Take two non-negative integers (`x(1), x(2)`), and one positive integer `N` as input.

`x(1)` and `x(2)` will be the two first numbers of your sequence, and `N` will be the length of the sequence you must output. (You can choose to have the list 0-based, in which case `N` will be one less than the length).

* You can not assume that `x(2) >= x(1)`.
* `N` will always be `>2` if 1-based, (`>1` if 0-based).
* You do not have to handle division by zero errors.
    + Note the 2nd test case. You will not get `0, 1`, and `N=6` as input, since that will result in division by zero, but you must support `0, 1` and `N=5`.
* Assume only valid input will be given.
* The input and output can be on any convenient format, but you must support at least 3 digits after the decimal points if the output is non-integer.

**Test cases:**

```
1 3
8
1, 3, 4, 12, -8, -1.5, -9.5, 14.25

0 1
5
0, 1, 1, 1, 0     // N=6 would give division by zero error. You don't need to handle that case.

1 0
9
1, 0, 1, 0, 1, 0, 1, 0, 1

6 3
25
6, 3, 9, 27, -18, -1.5, -19.5, 29.25, -48.75, -0.6, -49.35, 29.61, -78.96, -0.375, -79.335, 29.7506, -109.086, -0.272727, -109.358, 29.825, -139.183, -0.214286, -139.398, 29.8709, -169.269

```

# Answer
> 3 votes
# MATL, ~~19~~ ~~18~~ 17 bytes

```
q:"y'+*-/'@)hyhUV

```

Input is in the format: `N` (0-based), `x(1)`, `x(2)` (as strings); all separated by newlines.

Try it online! Or verify all test cases (slightly modified code; output sequences separated by a blank line).

### Explanation

MATL doesn't have a proper `eval` function, but `U` (`str2num`) can evaluate numeric expressions with infix operators.

Each new term is computed and pushed onto the stack, keeping the previous terms. The entire stack is printed at the end.

```
q          % Implicitly input N (0-based). Subtract 1
:"         % Repeat that many times
  y        %   Duplicate x(n-1), where n is the number of already computed terms
           %   In the first iteration, which corresponds to n=2, this implicitly
           %   inputs x(1) and x(2) as strings (and then duplicates x(1))
  '+*-/'   %   Push this string
  @)       %   Push iteration number and apply as modular index into the string.
           %   So this gives '+' in the first iteration, '*' in the second etc
  h        %   Concatenate horizontally. This gives a string of the form
           %   '*x(n-1)+', where '+' is the appropriate operator
  &y       %   Duplicate x(n)
  hh       %   Concatenate horizontally. This gives a string of the form
           %   'x(n-1)+x(n)'
  U        %   Convert to number. This evaluates the string
  V        %   Convert back to string. This is the new term, x(n+1)
           % Implicitly end loop and display stack

```

# Answer
> 9 votes
## Haskell, ~~69~~ ~~68~~ 64 bytes

```
x#n=take n$x++zipWith3 id(cycle[(+),(*),(-),(/)])(x#n)(tail$x#n)

```

`x1` and `x2` are taken as a list. Usage example: `[1,3] # 8` -\> `[1.0,3.0,4.0,12.0,-8.0,-1.5,-9.5,14.25]`.

Laziness makes it possible to define an infinite recursive list where we take the first n elements.

### Haskell, 66 bytes

```
(h%g)y x=x:g(h x y)y
a=(+)%b
b=(*)%c
c=(-)%d
d=(/)%a
(.a).(.).take

```

Different approach, slightly longer. Argument order is `N`, `x2`, `x1`. Usage example: `( (.a).(.).take ) 8 3 1` -\> `[1.0,3.0,4.0,12.0,-8.0,-1.5,-9.5,14.25]`.

Defines 4 functions `a`, `b`, `c` and `d` which take two arguments `y`, `x` and make a list by putting `x` in front of a call to the next function with `y` as the second argument and `x op y` as the first. For example `a` is: `a y x = x : (b (x+y) y)`, `b` does multiplication: `b y x = x : (c (x*y) y)`, etc.

Edit: @Michael Klein saved a byte in the 1st variant (`#`). Luckily I also found one byte for the second variant, so both have the same length again.

Edit II: @Zgarb found 2 bytes in the second version to save, and I 4 in the first, so they are no longer of the same length.

# Answer
> 6 votes
# ES6 (Javascript), ~~79~~, ~~67~~, 65 bytes

UPDATE

* minus 2 bytes, by starting with i=2, as suggested by @ETHProductions
* Saved 3 bytes, thanks to excellent advice from @Neil !

**Golfed**

```
S=(n,a,i=2)=>i<n?S(n,a,a.push(eval(a[i-2]+"-/+*"[i%4]+a[i-1]))):a

```

**Test**

```
S=(n,a,i=2)=>i<n?S(n,a,a.push(eval(a[i-2]+"-/+*"[i%4]+a[i-1]))):a

>S(8,[1,3])
Array [ 1, 3, 4, 12, -8, -1.5, -9.5, 14.25 ]

>S(5,[0,1])
Array [ 0, 1, 1, 1, 0 ]

>S(9,[1,0])
Array [ 1, 0, 1, 0, 1, 0, 1, 0, 1 ]

>S(25,[6,3])
Array [ 6, 3, 9, 27, -18, -1.5, -19.5, 29.25, -48.75, -0.6, ...]

```

# Answer
> 5 votes
# Python 3, ~~90~~ ~~80~~ 74 bytes

xnor's probably going to come and destroy this solution...

```
def F(s,n,i=2):
 while i<n:s+=eval('%s'*3%(s[-2],'-/+*'[i%4],s[-1])),;i+=1

```

The function modifies the list passed to it. Use like this:

```
s = [1,3]
F(s,8)

```

**Try on repl.it!**

*-6 bytes thanks to Copper*

# Answer
> 5 votes
# Perl 6,  ~~75 71~~  61 bytes

```
->\a,\b,\c{$_=[|(&[+],&[*],&[-],&[/])xx*];(a,b,{.shift.($^a,$^b)}...*)[^c]}

```

Test it

```
{$_=[|(&[+],&[*],&[-],&[/])xx*];($^a,$^b,{.shift.($^a,$^b)}...*)[^$^c]}

```

Test it

```
{($^a,$^b,{(&[+],&[*],&[-],&[/])[$++%4]($^a,$^b)}...*)[^$^c]}

```

Test it

## Expanded:

```
{ # bare block lambda with placeholder parameters ｢$a｣ ｢$b｣ ｢$c｣

  # generate sequence
  (
    # initialize sequence
    $^a, # declare and use first argument
    $^b, # second argument

    {  # bare block lambda with two placeholder parameters ｢$a｣ ｢$b｣

      (

        &[+], &[*], &[-], &[/] # the four operators

      )[             # index into the list of operators

         $++        # increment (++) an anonymous state variable ($)
         % 4        # modulo 4

      ]( $^a, $^b ) # and use it on the previous two values in sequence

    }

    ...  # repeat that until

    *    # indefinitely

  )[     # take only

    ^    # upto and excluding:     ( Range object )
    $^c  # third argument

  ]
}

```

# Answer
> 4 votes
# Mathematica, 68 bytes

```
(±1=#;±2=#2;±n_:=1##[#-#2,#/#2,+##][[n~Mod~4]]&[±(n-2),±(n-1)];±#3)&

```

Barely snuck into 3rd place! Unnamed function of three arguments, which uses a helper unary operator `±` such that `±n` is exactly the nth element x(n) of the Stewie sequence. The first two arguments are x(1) and x(2), and the third argument is the N indicating which x(N) we output.

Direct implementation, using a mod-4 calculation to choose which binary function to apply to the previous two terms. Picking the correct binary function, which is what `1##[#-#2,#/#2,+##]` helps with, uses a few of these fun Mathematica golfing tricks.

# Answer
> 4 votes
# x86-64 machine code, 34 bytes

Calling convention = x86-64 System V x32 ABI (register args with 32-bit pointers in long mode).

The function signature is `void stewie_x87_1reg(float *seq_buf, unsigned Nterms);`. The function receives the x0 and x1 seed values in the first two elements of the array, and extends the sequence out to at least N more elements. The buffer must be padded out to 2 + N-rounded-up-to-next-multiple-of-4. (i.e. `2 + ((N+3)&~3)`, or just N+5).

Requiring padded buffers is normal in assembly for high-performance or SIMD-vectorized functions, and this unrolled loop is similar, so I don't think it's bending the rules too far. The caller can easily (and should) ignore all the padding elements.

Passing x0 and x1 as a function arg not already in the buffer would cost us only 3 bytes (for a `movlps [rdi], xmm0` or `movups [rdi], xmm0`), although this would be a non-standard calling convention since System V passes `struct{ float x,y; };` in two separate XMM registers.

This is `objdump -drw -Mintel` output with a bit of formatting to add comments

```
0000000000000100 <stewie_x87_1reg>:
       ;; load inside the loop to match FSTP at the end of every iteration
       ;; x[i-1] is always in ST0
       ;; x[i-2] is re-loaded from memory
 100:   d9 47 04                fld    DWORD PTR [rdi+0x4]
 103:   d8 07                   fadd   DWORD PTR [rdi]
 105:   d9 57 08                fst    DWORD PTR [rdi+0x8]
 108:   83 c7 10                add    edi,0x10            ; 32-bit pointers save a REX prefix here

 10b:   d8 4f f4                fmul   DWORD PTR [rdi-0xc]
 10e:   d9 57 fc                fst    DWORD PTR [rdi-0x4]

 111:   d8 6f f8                fsubr  DWORD PTR [rdi-0x8]
 114:   d9 17                   fst    DWORD PTR [rdi]

 116:   d8 7f fc                fdivr  DWORD PTR [rdi-0x4]
 119:   d9 5f 04                fstp   DWORD PTR [rdi+0x4]

 11c:   83 ee 04                sub    esi,0x4
 11f:   7f df                   jg     100 <stewie_x87_1reg>
 121:   c3                      ret

0000000000000122 <stewie_x87_1reg.end>:
## 0x22 = 34 bytes

```

This C reference implementation compiles (with `gcc -Os`) to somewhat similar code. gcc picks the same strategy I did, of keeping just one previous value in a register.

```
void stewie_ref(float *seq, unsigned Nterms)
{
    for(unsigned i = 2 ; i<Nterms ; ) {
        seq[i] = seq[i-2] + seq[i-1];       i++;
        seq[i] = seq[i-2] * seq[i-1];       i++;
        seq[i] = seq[i-2] - seq[i-1];       i++;
        seq[i] = seq[i-2] / seq[i-1];       i++;
    }
}

```

I did experiment with other ways, including a two-register x87 version that has code like:

```
; part of loop body from untested 2-register version.  faster but slightly larger :/
; x87 FPU register stack    ;       x1, x2   (1-based notation)
fadd    st0, st1            ; x87 = x3, x2
fst     dword [rdi+8 - 16]  ; x87 = x3, x2

fmul    st1, st0            ; x87 = x3, x4
fld     st1                 ; x87 = x4, x3, x4
fstp    dword [rdi+12 - 16] ; x87 = x3, x4
; and similar for the fsubr and fdivr, needing one fld st1

```

You'd do it this way if you were going for speed (and SSE wasn't available)

Putting the loads from memory inside the loop instead of once on entry might have helped, since we could just store the sub and div results out of order, but still it needs two FLD instructions to set up the stack on entry.

I also tried using SSE/AVX scalar math (starting with values in xmm0 and xmm1), but the larger instruction size is killer. Using `addps` (since that's 1B shorter than `addss`) helps a tiny bit. I used AVX VEX-prefixes for non-commutative instructions, since VSUBSS is only one byte longer than SUBPS (and the same length as SUBSS).

```
; untested.  Bigger than x87 version, and can spuriously raise FP exceptions from garbage in high elements
addps   xmm0, xmm1      ; x3
movups  [rdi+8 - 16], xmm0
mulps   xmm1, xmm0      ; xmm1 = x4,  xmm0 = x3
movups  [rdi+12 - 16], xmm1
vsubss  xmm0, xmm1, xmm0      ; not commutative.  Could use a value from memory
movups  [rdi+16 - 16], xmm0
vdivss  xmm1, xmm0, xmm1      ; not commutative
movups  [rdi+20 - 16], xmm1

```

---

Tested with this test-harness:

```
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int main(int argc, char**argv)
{
    unsigned seqlen = 100;
    if (argc>1)
        seqlen = atoi(argv[1]);
    float first = 1.0f, second = 2.1f;
    if (argc>2)
        first = atof(argv[2]);
    if (argc>3)
        second = atof(argv[3]);

    float *seqbuf = malloc(seqlen+8);  // not on the stack, needs to be in the low32
    seqbuf[0] = first;
    seqbuf[1] = second;

    for(unsigned i=seqlen ; i<seqlen+8; ++i)
        seqbuf[i] = NAN;

    stewie_x87_1reg(seqbuf, seqlen);
//  stewie_ref(seqbuf, seqlen);
    for (unsigned i=0 ; i< (2 + ((seqlen+3)&~3) + 4) ; i++) {
        printf("%4d: %g\n", i, seqbuf[i]);
    }

    return 0;
}

```

Compile with `nasm -felfx32 -Worphan-labels -gdwarf2 golf-stewie-sequence.asm &&`
`gcc -mx32 -o stewie -Og -g golf-stewie-sequence.c golf-stewie-sequence.o`

Run the first test-case with `./stewie 8 1 3`

If you don't have x32 libraries installed, use `nasm -felf64` and leave gcc using the default `-m64`. I used `malloc` instead of `float seqbuf[seqlen+8]` (on the stack) to get a low address without having to actually build as x32.

---

Fun fact: YASM has a bug: it uses a rel32 jcc for the loop branch, when the branch target has the same address as a global symbol.

```
global stewie_x87_1reg
stewie_x87_1reg:
   ;; ended up moving all prologue code into the loop, so there's nothing here
.loop:

...
sub    esi, 4
jg     .loop

```

assembles to ... `11f: 0f 8f db ff ff ff jg 100 <stewie_x87_1reg>`

# Answer
> 3 votes
# 05AB1E, ~~21~~ ~~19~~ 18 bytes

Input is taken in the order **N**(0-based), **x(2)**, **x(1)**.
Saved 1 byte thanks to *carusocomputing*.

```
GUDXsX"/+*-"Nè.V})

```

Try it online!

**Explanation**

```
 G                   # for N in [0 ... n-1] do:
  U                  # save top element of stack in X
   D                 # duplicate top of stack
    X                # push X
     s               # swap top 2 elements on stack
      X              # push X
       "/+*-"Nè      # index into the string with the current iteration number
               .V    # evaluate
                 }   # end loop
                  )  # wrap stack in list

```

We iteratively build the stack with the latest element in the sequence on top, while keeping all previous elements in order.
Then we wrap the stack in a list at the end to display all values at once.

# Answer
> 3 votes
# Haskell, 60 bytes

```
g(o:z)a b=a:g z b(o a b)
p=(+):(*):(-):(/):p
(.g p).(.).take

```

Try it online!

Ungolfed:

```
ungolfed :: Int -> Double -> Double -> [Double]
ungolfed len x1 x2 = take len $ go (cycle [(+),(*),(-),(/)]) x1 x2
    where go (f:fs) x y = x : go fs y (f x y)

```

Knowing `\x -> f x == f`, `\x -> f $ g x == f . g`, and some other patterns, you can transform a normal (point-full) function into a point-free one:

```
f0 len x1 x2 = take len $ go p x1 x2
f1 len = \x1 x2 -> take len $ go p x1 x2
f2 len = \x1 -> take len . go p x1
f3 len = (take len .) . go p
f4 = \len -> (. go p) (take len .)
f5 = \len -> (. go p) ((.) (take len))
f6 = \len -> (. go p) . (.) $ take len
f7 = \len -> ((. go p) . (.) . take) len
f8 = (. go p) . (.) . take

```

`\x y -> f $ g x y == (f.) . g` is also a common pattern.

You could also read this backwards for adding back arguments to a point-free function.

# Answer
> 2 votes
## Common Lisp, 158

```
(lambda(x y n)(loop repeat n for a = x then b for b = y then r for o in '#1=(+ * - / . #1#)for r =(ignore-errors(funcall o a b))collect(coerce a'long-float)))

```

Not really competitive, but I like how it is is expressed quite naturally:

```
(lambda (x y n)
  (loop
    repeat n
    for a = x then b
    for b = y then r
    for o in '#1=(+ * - / . #1#)
    for r = (ignore-errors (funcall o a b))
    collect (coerce a 'long-float)))

```

We ignore errors when computing R, which makes R (and then B) possibly take the NIL value. That allows to output the current result even if the next value is undefined. Then, eventually the loop will fail, but that's within the rules.

## Tests

We name the function `F` and verify that the expected values are approximately equal to the tested one.

```
(loop
  for (args expected)
    in
  '(((1 3 8)
     (1 3 4 12 -8 -1.5 -9.5 14.25))

    ((0 1 5)
     (0 1 1 1 0))

    ((1 0 9)
     (1 0 1 0 1 0 1 0 1))

    ((6 3 25)
     (6 3 9 27 -18 -1.5 -19.5 29.25 -48.75 -0.6 -49.35 29.61 -78.96 -0.375 -79.335 29.7506 -109.086 -0.272727 -109.358 29.825 -139.183 -0.214286 -139.398 29.8709 -169.269)))

  for result = (apply #'f args)
  always (every (lambda (u v) (< (abs (- u v)) 0.001)) result expected))

=> T

```

The reason for the approximate test is because the computed values are a little more precise than required; here, for `(f 6 3 25)`:

```
(6.0d0 3.0d0 9.0d0 27.0d0 -18.0d0 -1.5d0 -19.5d0 29.25d0 -48.75d0 -0.6d0
 -49.35d0 29.61d0 -78.96d0 -0.375d0 -79.335d0 29.750625d0 -109.085625d0
 -0.2727272727272727d0 -109.35835227272727d0 29.825005165289255d0
 -139.18335743801654d0 -0.21428571428571427d0 -139.39764315230224d0
 29.870923532636194d0 -169.26856668493843d0)

```

# Answer
> 2 votes
# dc, ~~112~~ ~~110~~ 108 bytes

```
5k?sarfsmsn[pSnla1-Sa]sh[lmlndSm]sv[lvx/lhx]sb[lvx+lhx]sc[lvx*lhx]sd[lvx-lhx]se[lcx2la>d2la>e2la>b2la>j]dsjx

```

Sometimes `dc` answers can be super long, and sometimes they can be super short. It all just depends on the challenge at hand as is the case with many other languages. Anyways, this prompts for a space-separated one-indexed command line input of 3 integers, `x(1), x(2), N`, upon invocation, and outputs each element of the sequence on separate lines with non-integer outputs containing 5 digits after the decimal point.

For example, the input `6 3 25` results in the following output:

```
6
3
9
27
-18
-1.50000
-19.50000
29.25000
-48.75000
-.60000
-49.35000
29.61000
-78.96000
-.37500
-79.33500
29.75062
-109.08562
-.27272
-109.35834
29.82420
-139.18254
-.21428
-139.39682
29.86995
-169.26677

```

# Answer
> 2 votes
# Perl, 62 + 3 (`-pla` flag) = 65 bytes

```
push@F,eval$F[-2].qw(* - / +)[$_%4].$F[-1]for 3..pop@F;$_="@F"

```

Using:

```
perl -plae 'push@F,eval$F[-2].qw(* - / +)[$_%4].$F[-1]for 3..pop@F;$_="@F"' <<< '1 3 8'

```

# Answer
> 2 votes
# 05AB1E, 12 bytes

```
λ£"-/+*"Nè.V

```

Try it online!

# Answer
> 1 votes
# Bash, 224 bytes (NO CONTEST)

A tremendously large implementation in *BASH*.

Takes the task quite literally, and does everything in one continuous pipe, w/o any unholy control flow structures or recursion.

**Input**

> $1,$2 - initial elements
>
> $3 - target sequence size

**Golfed**

```
{ echo "a[0]=$1;a[1]=$2;a[0];a[1]";paste <() <(seq 2 $[$3-1]) <(seq 0 $[$3-3]) <(printf '%.0s+*-/' `seq $[$3/4]`|fold -1|head -$[$3-2]) <(seq 1 $[$3-2]);}|sed -r '1 ! s/(.+)\s(.+)\s(.+)\s(.)/a[\1]=a[\2]\3a[\4];a[\1];/'|bc -l

```

**Less Golfed**

```
{
 echo "a[0]=$1;a[1]=$2;a[0];a[1]";
 paste <() <(seq 2 $[$3-1]) <(seq 0 $[$3-3]) <(printf '%.0s+*-/' `seq $[$3/4]`|fold -1|head -$[$3-2]) <(seq 1 $[$3-2]);
}\
|sed -r '1 ! s/(.+)\s(.+)\s(.+)\s(.)/a[\1]=a[\2]\3a[\4];a[\1];/' \
|bc -l

```

**Test**

```
>./stewie.sh 1 3 8
1
3
4
12
-8
-1.50000000000000000000
-9.50000000000000000000
14.25000000000000000000

```

**Pipeline Stages**

Generate a table of element indices + op, for an each output sequence element (one per line):

```
...
2   0   +   1
3   1   *   2
4   2   -   3
5   3   /   4
6   4   +   5
7   5   *   6
...

```

Use *sed* to convert this into a linear *bc* program:

```
...
a[2]=a[0]+a[1];a[2];
a[3]=a[1]*a[2];a[3];
a[4]=a[2]-a[3];a[4];
a[5]=a[3]/a[4];a[5];
a[6]=a[4]+a[5];a[6];
a[7]=a[5]*a[6];a[7];
...

```

feed this to *bc* and let it do all the job

# Answer
> 1 votes
# Ruby, 79 bytes

```
->(b,c,d){a=[b,c];(d-2).times{|i|a<<a[i].send(%i{+ * - /}[i%4],a[i+1]).to_f};a}

```

I suspect this is very far off from optimal (and I haven't looked at the other answers yet), but it's fun nonetheless.

I wanted to have some fun with `Enumerable#cycle`, but sadly, it's 4 fewer characters to just use `%4`.

# Answer
> 1 votes
# C++14, 118 bytes

```
[](auto&v,int N){for(int i=0;++i<N-1;){auto p=v.rbegin(),q=p+1;v.push_back(i%4?i%4<2?*q+*p:i%4<3?*q**p:*q-*p:*q/ *p);}

```

As unnamed lambda modifying its input. Requires `v` to be a `vector<double>` or `vector<float>`.

Ungolfed and usage:

```
#include<iostream>
#include<vector>

auto f=
[](auto&v,int N){
  for(int i=0; ++i<N-1;){
    auto p=v.rbegin(),q=p+1;
    v.push_back(
      i%4 ?
        i%4<2 ? *q+*p :
          i%4<3 ? *q**p : *q-*p
      : *q/ *p
    );
  }
};

int main(){
  std::vector<double> v={1,3};
  f(v,8);
  for (auto x:v) std::cout << x << ", ";
  std::cout << "\n";
}

```

# Answer
> 1 votes
# Japt, 20 bytes

```
@OxVs2n)q"-/+*"gY}hV

```

Try it

# Answer
> 1 votes
# , ~~<sup>49</sup>~~ ~~<sup>33</sup>~~ 29 bytes

```
[$_2&(],(-,%,+,*)/@{.{~4|#@])

```

Try it online!

*-4 bytes thanks to FrownFrog*

# Answer
> 1 votes
# PowerShell, ~~66~~ ~~60~~ 58 bytes

<sup>-8 bytes thanks to mazzy</sup>

```
param($a,$b)3..$a|%{$b+=$b[-2,-1]-join"*-/+"[$_%4]|iex}
$b

```

Try it online!

Builds `x(n)` in place by making a string out of `x(n-2)` and `x(n-1)`, joined by the operator we need (determined by modulo math using the index we get for free from iterating up), and feeds it into `i`nvoke`Ex`pression. We then spit out the final array.

# Answer
> 0 votes
# Pyth - 20 bytes

Outputting all `n` costs me.

```
u+Gvj@"+*-/"H>2GttEQ

```

Doesn't work online cuz of eval.

# Answer
> 0 votes
# Ceylon, 195 bytes

```
Float[]s(Integer a,Integer b,Integer n)=>loop([a.float,b.float,[Float.divided,Float.plus,Float.times,Float.minus].cycled.rest])(([x,y,o])=>[y,(o.first else nothing)(x)(y),o.rest]).take(n)*.first;

```

Formatted and commented:

```
// Print the first n entries of the Stewies sequence with given starting entries.
//
// Question:  http://codegolf.stackexchange.com/q/101145/2338
// My answer: http://codegolf.stackexchange.com/a/101251/2338

// Declare a function `s` which takes three integers, and returns a tuple
// of floats. (The more common syntax for the return value is [Float*],
// but Float[] is shorter.)
Float[] s(Integer a, Integer b, Integer n)
       // it is implemented by evaluating the following expression for each call.
         =>
        // start a loop with ...
        loop([
              // ... float versions of the integers, and ...
              a.float, b.float,
              // ... an infinite sequence of the four operators, ever repeating.
              // I needed the `.rest` here so the whole thing gets a {...*} type
              // instead of {...+}, which doesn't fit to what o.rest returns.
              // Each operator has the type Float(Float)(Float), i.e. you apply
              // it twice to one float each to get a Float result.
              [Float.divided, Float.plus, Float.times, Float.minus].cycled.rest])
               // in each iteration of the loop, map the triple of two numbers
               // and a sequence of operators to a triple of ...
            (([x, y, o]) => [
               // the second number,
                y,
               //the result of the first operator with both numbers
               // (using this "else nothing" here to convince the
               //  compiler that o.first is not null),
                   (o.first else nothing)(x)(y),
               // and the sequence of operators without its first element.
               // (that one unfortunately has a {...*} type, i.e. a possibly
               //  empty sequence.)
                                                 o.rest])
            // now we got an infinite sequence of those triples.
            // We just want the first n of them ...
                .take(n)
            // and of each triple just the first element.
            // (The *. syntax produces a tuple, non-lazily.
            //  We could also have used .map((z) => z.first)
            //  or .map(Iterable.first) or .map((z) => z[0]), each of
            //  which would return a (lazy) sequence, but they all would be
            //  longer.)
                *.first;

```

Example usage:

```
shared void run() {
    print(s(1, 3, 8));
    print(s(0,1,11));
    print(s(1,0,9));
    print(s(6, 3, 29));
}

```

Example output:

```
[1.0, 3.0, 4.0, 12.0, -8.0, -1.5, -9.5, 14.25]
[0.0, 1.0, 1.0, 1.0, 0.0, Infinity, Infinity, Infinity, NaN, NaN, NaN]
[1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0]
[6.0, 3.0, 9.0, 27.0, -18.0, -1.5, -19.5, 29.25, -48.75, -0.6, -49.35, 29.61, -78.96000000000001, -0.37499999999999994, -79.33500000000001, 29.750625, -109.08562500000001, -0.2727272727272727, -109.35835227272727, 29.825005165289255, -139.18335743801651, -0.2142857142857143, -139.39764315230224, 29.870923532636194, -169.26856668493843, -0.17647058823529413, -169.44503727317374, 29.90206540114831, -199.34710267432206]

```

The second example shows how this would handle division by zero. The last example shows that the results deviate a bit depending on which kind of arithmetic (and rounding) one is using ... I think Ceylon's 64 bit floating point arithmetic is a bit nearer to what it should be than what was posted in the question.

# Answer
> 0 votes
**Clojure, 99 bytes**

```
#(let[ops[+ * - /]](take %3(map first(iterate(fn[[a b i]][b((ops i)a b)(mod(inc i)4)])[%1 %2 0]))))

```

This version is nicer to use in practice but has 110 bytes:

```
(defn f[a b n](let[ops[+ * - /]](take n(map first(iterate(fn[[a b i]][b((ops i)a b)(mod(inc i)4)])[a b 0])))))

```

I had trouble fuzing iterated function and a cyclical sequence of operations so I had to use a counter instead. Also tried using a FSM transition table like `{+ * * - - / / +}` but I couldn't squeeze it to less code.

Could be expressed as an anonymous function

Un-golfed:

```
(defn f [a b n]
  (let [ops [+ * - /]]
    (->> [a b 0]
         (iterate (fn [[a b i]]
                    [b
                     ((ops i) a b)
                     (mod (inc i) 4)]))
         (map first)
         (take n))))

```

Must be called with floats like `(f 6.0 3.0 25)` as otherwise you get rational numbers out. Alternatively the iteration could be started from `[a (float b) 0]` which brings some extra characters.

# Answer
> 0 votes
# Octave, 91 bytes

```
@(x,n)eval 'for i=3:n,x(i)=eval([(n=@num2str)(x(i-2)),"*-/+"(mod(i,4)+1),n(x(i-1))]);end,x'

```

Try it online!

Some golfs:

* No parentheses for the first `eval` call
* No concatenations for the first `eval` call
* Inline assignment of `*-/+` (not possible in MATLAB)
* Combined `'` and `"` to avoid escaping the apostrophes (not possible in MATLAB)
* Storing `n=@num2str` since it's used twice (not possible in MATLAB)

# Answer
> 0 votes
# cQuents, 19 bytes

```
=A,B&Y+Z,YZ,Y-Z,Y/Z

```

Try it online!

# Explanation

Receives three inputs, `A B n`

```
=A,B                   first two terms in sequence are A and B
    &                  output first n terms of sequence
     Y+Z,YZ,Y-Z,Y/Z    next terms are Y+Z, then Y*Z, ..., cycling back to beginning after 4th
                       Y and Z are the previous two terms in the sequence

```

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


title: Make a random drum loop

text:
# Question
Title: Make a random drum loop
Do randomly generated drum loops sound good?

A **drum loop** is a \\$5\times 32\\$ matrix \\$A\\$ of \\$1\\$s and \\$0\\$s such that

1. \\$A\_{1,1}=A\_{1,17}=A\_{2,9}=A\_{2,25}=1\\$,
2. for each \\$i\\$, the \\$i\\$th row has exactly \\$f(i)\\$ different \\$1\\$s, where \\$ f(1)=3, f(2)=2, f(3)=6, f(4)=8, f(5)=5\\$,
3. for each \\$j\equiv 1\bmod 4\\$, the \\$j\\$th column has exactly one \\$1\\$, and
4. for each \\$j\not\equiv 1\bmod 4\\$, the \\$j\\$th column has at most one \\$1\\$.

Here, the rows provide instructions for each of five drums, with each column representing a beat. In particular, the first row corresponds to a kick, while second row corresponds to a snare.

Write the shortest code that draws a matrix uniformly from the set of drum loops.

Feel free to use your code to draw a random drum loop, implement the drum loop on this website, and then post a link to your creation in your post. (Note that we only use the first 5 rows of this online beat maker.)

**Edit 1:** To be clear, we are using 1-based indexing: the row indices are \\$\\{1,\ldots,5\\}\\$ and the column indices are \\$\\{1,\ldots,32\\}\\$.

**Edit 2:** Judging by the current submissions, the answer to my original question appears to be "yes": randomly generated drum loops *do* sound good. Here are links to the current examples:

# Answer
# C (gcc), ~~413 394 389 379 378 360 342 327 307 299 298~~ 293 bytes

```
#define F;for(b[8]=b[v=24]=3,n=0;n
#define B,b[n]==
a[]=L"14444448888888822222",b[32],r[24],n,k,j,t=20,v;main(i){srand(&i)F<v;*b=b[16]=1)r[n++]=n/3-~n F<4;a[k]=a[t])b[i=4+n++*8]=a[k=rand()%t--]-48 F<16;r[j]=r[v])b[r[j=rand()%v--]]=a[n++]-48 F<32;n++)printf("%d%d%d%d%d\n"B 1 B 3 B 4 B 8 B 2);}

```

Try it online!

```
#define F;for(b[8]=b[v=24]=3,n=0;n
#define B,b[n]==
a[]=L"14444448888888822222",b[32],r[24],n,k,j,t=20,v;main(i){srand(time(0))F<v;*b=b[16]=1)r[n++]=n/3-~n F<4;a[k]=a[t])b[i=4+n++*8]=a[k=rand()%t--]-48 F<16;r[j]=r[v])b[r[j=rand()%v--]]=a[n++]-48 F<32;n++)printf("%d%d%d%d%d\n"B 1 B 3 B 4 B 8 B 2);}

```

try it online -earlier algorithm 307 bytes

Many thanks to @ceilingcat for more byte savings (360 to 342 - then 342 to 328 and 327 to 307 - then modified algorithm from 328 to 299 and 298 to 293).

Compiles ok without `#include<stdio.h>` using the `-w` compiler flag, thanks to @Arnaud for pointing this out.

As written it generates a fresh sequence each time. If we are allowed manual intervention of a new number in `srand` to generate a different drum sequence with say `srand(6);` then we can save 16 bytes.

Thanks to @Arnaud who made asked the question about generating the transpose matrix, which is what this program does. Thanks also for suggesting the change from `int` to `char` for `a[20]` that saves 15 bytes. Also thanks for @Post Rock Garf Hunter who figured out a way to remove white space near the `B`s and then saved more bytes fixing up the #defines so that `F` is included in `R`. \`#define' tokens often seem to need whitespace so they are cleanly identified.

This code works on `tio.run`, but elsewhere may need to include `time.h`.

# How the program works

logic:

* **setup**
* 4 sounds are fixed (at 1,9,17,25)
* remaining sounds to be distributed randomly are in `a[20]`
* `b[32]` holds output - one cell for each beat (1 to 32, but in C of course 0 to 31)
* 4 of the `b` cells must have something (at 5,13,21,29)
* remaining sounds randomly scattered to empty cells
* `r[24]` holds list of empty cells (2,3,4, 6,7,8 etc. in C 0,1,2, 4,5,6 etc.)
* **execute**
* put in 4 fixed sounds
* choose random sound from `a` to put in each of 4 cells with sounds
* choose random cell from `r` to put in random sound from remaining `a` sounds (simplification to algorithm is possible here by putting remaining sounds one by one from 1 to 16 (or 0 to 15) in a random cell, but this gave more bytes..., but now thanks to @ceilingcat this is now smaller see tio.run link for details)
* print result

this is a long version of the code without the `#define` and other space savers to show the logic, but with small differences e.g. in final version `a` is `char *` not `int *`

```
#include<stdio.h>
#include<stdlib.h>
int main()
{
  int a[20]={1,4,4,4,4,4,4,8,8,8,8,8,8,8,8,2,2,2,2,2},
    b[32]={},r[24],n,k,j,t=20,v=24;
  time_t q;srand(time(&q));
//random initialization

  for(n=0;n<24;n++n=0;n<v;n++)r[n]=n+n/3+1;
// set up r with list of cells that don't definitely have sound 012,456 etc.

  b[0]=b[16]=1;b[8]=b[24]=16;
//put in fixed sounds

  for (n=0;n<4;n++)
    {k=rand()%t--;b[4+n*8]=a[k];a[k]=a[t];}
//choose a random sound from a to put in each of 4 cells that must  have sound
// each sound selected is then replaced by the sound at the end of the list
// and the length of the list is reduced by one

  for (n=0;n<16;n++)
    {k=rand()%t--;j=rand()%v--;b[r[j]]=a[k];a[k]=a[t];r[j]=r[v];}
// random cell from remaining `r` cells and random sound are selected
// again after selection from list final item replaces selected and length
// reduced by one

  for (n=0;n<32;n++)
    {printf("%d%d%d%d%d\n",(b[n]==1),(b[n]==16),(b[n]==4),(b[n]==8),(b[n]==2));}
 // print out 0 and 1 from logical tests to print transpose matrix
  return 0;
}

```
> 3 votes

# Answer
# JavaScript (ES6),  ~~194 193~~  189 bytes

Returns \\$M^T\\$.

```
_=>(g=n=>n?g(/1/.test(c=m[R()*32|0])?n:n-=c[h()]=1):m)(16,a=[1,,6,8,5],R=Math.random,h=_=>a[y=R()*5|0]?a[y]--&&y:h(),m=[...Array(32)].map((_,x)=>(c=[0,0,0,0,0],x&3?0:c[x&7?h():x/8&1]=1,c)))

```

Try it online!

## How?

**Note**: *Columns* and *rows* in the following explanation refer to the matrix described in the challenge. They are stored the other way around in this implementation.

### Initialization

We define an array \\$a\\$ holding the number of hits that need to be added to each row, ignoring the 4 fixed positions.

```
a = [ 1, , 6, 8, 5 ]

```

We define the helper function \\$h\\$ that picks a random row among those that are not completely filled, and updates \\$a\\$ accordingly.

```
h = _ => a[y = R() * 5 | 0] ? a[y]-- && y : h()

```

We define a matrix \\$m\\$ of \\$32\times5\\$ filled with \\$0\\$'s, except the columns such that \\$x\equiv 0\pmod 4\\$ (using 0-indexing) which are initialized according to the rules described in the challenge.

```
m = [...Array(32)]          // set up 32 columns
  .map((_, x) => (          // for each column at position x:
    c = [0, 0, 0, 0, 0],    //   start with all values set to 0
    x & 3 ?                 //   if x mode 4 is not equal to 0:
      0                     //     do nothing
    :                       //   else:
      c[                    //     update c:
        x & 7 ?             //       if x mod 8 is not equal to 0:
          h()               //         use a random row
        :                   //       else:
        x / 8 & 1           //         fixed position: use either row 0 or 1,
                            //         depending on the parity of floor(x / 8)
      ] = 1,                //     set the hit
    c                       //   yield the final column
  ))                        // end of map()

```

### Main loop

We randomly add the \\$16\\$ remaining hits on empty columns (which implies \\$x\not\equiv 0\pmod 4\\$) until all rows are filled.

```
( g = n =>                  // n = total number of hits to add
  n ?                       // if n is not equal to 0:
    g(                      //   do a recursive call:
      /1/.test(             //     test whether
        c = m[R() * 32 | 0] //     a randomly selected column c
      ) ?                   //     contains any '1'; if it does:
        n                   //       just pass n unchanged to try again
      :                     //     else:
        n -= c[h()] = 1     //       set the hit on this column, on a random row
                            //       and decrement n
    )                       //   end of recursive call
  :                         // else:
    m                       //   we're done: return m[]
)(16)                       // initial call to g with n = 16

```
> 3 votes

# Answer
# 05AB1E, 65 bytes

```
31Ý©8ˆ24ˆ40¯ǝ0ˆ16ˆ®¯KΩˆ48¯¦¦ǝ•Wk¤]•3ôεćи}˜.ržw8и«®¯K.r.¡4Ö}é˜ǝb€¦

```

Outputs as a transposed list of strings.

Try it online. (The footer pretty-prints this as the intended rows/columns. Feel free to remove the footer to see the actual result.)

**Explanation:**

```
31Ý                # Push a list in the range [0,31]
   ©               # Store it in variable `®` (without popping)
8ˆ                 # Add 8 to the global array
  24ˆ              # Add 24 to the global array as well
     40¯ǝ          # Replace the values at the indices of the global array with 40
0ˆ                 # Add 0 to the global array
  16ˆ              # Add 16 to the global array as well
     ®             # Push the [0,31] list from variable `®` again
      ¯K           # Remove all values of the global array (the [0,8,16,24])
        Ω          # Pop and push a random index from this list
         ˆ         # Add it to the global array as well
            ¯¦¦    # Push the global array with the first two (8,24) removed
          48   ǝ   # Replace the values at the remaining three indices with 48
•Wk¤]•             # Push compressed integer 533636834
      3ô           # Split it into parts of size 3: [533,636,834]
        ε          # Map over each integer
         ć         #  Extract head; pop and push remainder and head
          и        #  Repeat the remainder the head amount of times
                   #   i.e. 533 becomes [33,33,33,33,33]
        }˜         # After the map: flatten the list of list of integers
          .r       # And randomly shuffle it
            žw8и   # Then push a list of 8 32s
                «  # And merge it to the end of the list
®                  # Push the [0,31] list from variable `®` again
 ¯K                # Remove all indices stored in the global array
                   # (the [0,8,16,24] and one random index)
   .r              # Randomly shuffle these remaining indices
     .¡            # Group the remaining indices by:
       4Ö          #  Where this (0-based) index is divisible by 4
                   #  (which would be i % 4 == 1 for the corresponding 1-based index)
     }é            # After the group by, sort the two inner lists by length,
                   # so the indices divisible by 4 are before the other indices
       ˜           # And flatten it to a single list
ǝ                  # Then insert the shuffled integers at those shuffled indices
 b                 # Convert each integer to a binary string
                   # (32=100000;33=100001;34=100010;36=100100;40=101000;48=110000)
  €¦               # And then remove the leading "1" from each
                   # (after which the resulting list is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•Wk¤]•` is `533636834`.
> 1 votes

# Answer
# Jelly, 43 bytes

```
32s8Zs4ZḢ;FẊḣ⁴ƲƊḢŒœ;FẊ$ƲFṙ-“¥©€Þı‘œṖ;¹Ṭz0ZṖ

```

Try it online!

A niladic link that returns a 32x5 matrix of 1s and 0s representing the drum loop. The footer simply prints it concatenated and separated by newlines.

## Explanation

```
32                                          | 32
  s8                                        | Split into groups of 8
    Z                                       | Transpose
     s4                                     | Split into groups of 4
       Z                                    | Transpose
               Ɗ                            | Following as a monad:
        Ḣ                                   | - Head
         ;    Ʋ                             | - Concatenate to following as a monad:
          F                                 |   - Flatten
           Ẋ                                |   - Shuffle list
            ḣ⁴                              |   - First 16
                       Ʋ                    | Following as a monad:
                Ḣ                           | - Head
                 Œœ                         | - Odd/even indexed items
                   ;  $                     | - Concatenate to:
                    F                       |   - Remainder of list flattened
                     Ẋ                      |   - Shuffled
                        F                   | Flatten
                         ṙ-                 | Rotate right 1 item
                           “¥©€Þı‘œṖ        | Split list before positions 4, 6, 12, 20, 25
                                    ;¹      | Concatenate to 32 (because 32 was the beginning of this niladic link)
                                      Ṭ     | Convert from lists of numeric indices to logical lists with 1s at those positions
                                       z0   | Transpose with 0 as filler
                                         Z  | Transpose
                                          Ṗ | Remove last (the sixth list introduced with the 32 above)

```
> 1 votes

# Answer
# Python 3, 180 bytes

```
from random import*
r=range
s=sample
a=s(s([x for x in r(32)if x%4],16)+[x*8+4 for x in r(4)],20)
print([[i in t for i in r(32)]for t in[[0,16,a[0]],[8,24],a[1:7],a[7:15],a[15:]]])

```

Try it online!

Prints a logical matrix representing the drum loop.
> 1 votes

# Answer
# Python 3, <sup>~~400~~ \\$\cdots\\$ ~~361~~</sup> 338 bytes

```
from random import*
r=randrange
p=65537
def h(b=p):
 while b==p:b=p|1<<r(32)
 l=[b,16777472]
 for i in[6,8,5]:
  while bin(b).count('1')!=i:b=sum(1<<r(32)for j in[1]*i)
  l+=[b]
 return l
g=1
while g:
 l,g=h(),0
 for i in range(32):
  b=sum(j&1<<i!=0for j in l)
  if i%4:g|=b>1
  else:g|=b!=1
for i in l:print(f"{bin(i)[2:]:>032}"[::-1])

```

Try it online!

Full program outputs a \\$5\times32\\$ matrix of \\$1\\$s and \\$0\\$s. Bit slow at times (\\$\sim15\\$ seconds), but you can't rush the creative process! :P
> 0 votes

# Answer
# , 138 bytes

```
s=sample
y=s(c(8*0:3+5,s((1:32)[-(4*0:7+1)],16)))
z=matrix(0,5,32)
z[1,c(1,17,y[1])]=z[2,c(9,25)]=z[3,y[2:7]]=z[4,y[8:15]]=z[5,y[16:20]]=1

```

Try it online!

A full program that implicitly prints the drum loop as a matrix of 1s and 0s.

# Alternative using a third party package:

## \+ DescTools, 130 bytes

```
s=sample
y=s(c(8*0:3+5,s((1:32)[-(4*0:7+1)],16)))
sapply(list(c(1,17,y[1]),c(9,25),y[2:7],y[8:15],y[16:20]),DescTools::Unwhich,32)

```

RDRR it!

A full program that implicitly prints a logical matrix (in the transposed form).
> 0 votes

---
Tags: code-golf, random, combinatorics, music
---


title: What's the Mayan date?

text:
# Question
Title: What's the Mayan date?
Just over seven years ago, everybody suddenly stopped talking about the Maya people. It is time to rectify that!

For clarification, I am talking about the Mesoamerican Long Count Calendar. Your program will have as input a date in the Gregorian Calendar, and as output the corresponding date from the aforementioned Mesoamerican calendar.

That calendar counts days since August 11, 3114 BCE. It divides that number of days into periods of different lengths. There's the single day, the Winal (20 days), the Tun (18 Winal, or 360 days), the K'atun (20 Tun, 7200 days), and the B'ak'tun (20 K'atun, 144 000 days).

So you have your number of days since the epoch, then you find out how many of each period fit in there. Let's take William the Conqueror's coronation date of December 25, 1066. We're not bothering with the Julian Calendar here - we're using the Proleptic Gregorian Calendar for dates in the distant past (including the Maya epoch): basically the system of leap days every four years, except years divisible by 100 but not by 400, which I trust you're all familiar with.

Between Christmas Day in 1066 and the Maya epoch date of August 11, 3114 BCE, there's 1526484 days. In that number, you can fit 10 periods of 144000 days, so that's our B'ak'tun. The remainder, 86484, can fit 12 periods of 7200 days, so that's the K'atun. The remainder is 84. That's less than 360, so our Tun is 0. You can fit 4 Winal though, leaving a remainder of 4 days.

Now concatenate all those numbers with full stops in between, in decreasing order of period length. The date of 25 December 1066 becomes 10.12.0.4.4.

(luckily, Wolfram|Alpha can verify it too)

### Specification

Your program will take as input a date in the Gregorian Calendar, between January 1, 1 AD (7.17.18.13.3), and 31 December, 3999 AD (18.0.15.17.6). The date can be in any format you want (my test cases will be using ISO 8601) as long as it is in the Gregorian calendar.

That means, valid input formats include (but are not limited to) "22 MAR 2233", "7/13/2305", "20200107T000000Z", and "2020-01-07T00:00:00+00:00", even an array like "\[7\], \[1\], \[2020\]", depending on what your language parses the most easily or what approach you want to use. It is not allowed however to include any information beyond year, month, day of the month, time (has to be 00:00:00) and time zone (has to be GMT). Once I start allowing the day of the year, the Unix timestamp, a full-fledged DateTime data object (which contains a host of other values) or some other date tracking scheme, this issue would no longer be about converting a Gregorian date into a Mayan date, but only about representing a Mayan date. So basically, just stick with a primitive or a list of primitives for input.

It will output a string containing the corresponding Mayan date, as discussed above. It has to be a single string of numbers separated by periods; an int array is not allowed. Using a built-in Maya converter in your language (though I would be surprised if it had one) is not permitted either.

The question is tagged , so the shortest program in byte count wins!

### Test cases

```
Gregorian; Mayan
1-1-1; 7.17.18.13.3
1-1-2; 7.17.18.13.4
1066-12-25; 10.12.0.4.4
2000-2-29; 12.19.7.0.1
2012-12-21; 13.0.0.0.0
2020-1-5; 13.0.7.2.11
2100-3-1; 13.4.8.8.6
2154-4-11; 13.7.3.6.10
3999-12-31; 18.0.15.17.6

```

# Answer
# 05AB1E, ~~54~~ 52 bytes

```
365*Š3‹¹α4т‚DPª÷®β•ë˜¿•ºS₂+²£`•H`Ø•OŽQív₂y-‰R`})R'.ý

```

Try it online!

First step: compute the day number.

```
365                # literal 365
   *               # multiply
                   #  => 365*year is left on the stack for now
Š                  # get the other two inputs
                   #  => day is left on the stack
3‹                 # is month less than 3? (returns 0 or 1)
  ¹α               # absolute difference with year
    4              # literal 4
     т             # 100
      ‚            # pair the two: [4, 100]
       DP          # product of (a copy of) the pair: 400
         ª         # append it to to the pair: [4, 100, 400]
          ÷        # int divide the year by each of those numbers
           ®β      # convert from base -1: y/4 - y/100 + y/400
                   #  => number of leap days is left on the stack
•ë˜¿•              # compressed integer 15254545
     º             # mirrored: 1525454554545251
      S            # split to a list of digits
       ₂+          # add 26 to each: [27, 31, 28, 31, 30, ...]
         ²£        # month first values of that list
           `       # dump all on the stack
                   #  => days in previous months is left on the stack
•H`Ø•              # compressed integer 1136750
                   #  => gregorian-mayan offset is left on the stack
O                  # sum the stack, giving the # of days since 0.0.0.0.0

```

Second step: convert that number to the appropriate notation.

```
ŽQí                # compressed integer 6866
   v      }        # for each digit:
    ₂y-            #  26 - digit (20, 18, 20, 20)
       ‰R`         #  divmod, reverse, then dump
                   #  (pushes the mod then the div)
           )       # wrap the stack in an array
            R      # reverse
             '.ý   # join by "."

```
> 3 votes

# Answer
# Python 3, ~~149~~ \\$\cdots\\$ ~~145~~ 140 bytes

```
from datetime import*
def f(d):
 n,s=(date(*d)-date(1,1,1)).days+1137143,""
 for i in[144000,7200,360,20,1]:s+=f".{n//i}";n%=i
 return s[1:]

```

Try it online!

Takes Gregorian date as `[year, month, day]` list and returns Mayan date as `f"{B'ak'tun}.{K'atun}.{Tun}.{Winal}.{Day}"`(loosely as a python f-string).
> 6 votes

# Answer
# JavaScript (ES6), 96 bytes

*Assumes that the system is set up to UTC time (as the TIO servers are)*

Takes input as 3 distinct parameters `(year, month, day)`.

```
(y,m,d)=>[144e3,7200,360,20,1].map(k=>n/(n%=k,k)|0,n=new Date(y+4e3,m-1,d+395335)/864e5).join`.`

```

Try it online!

### How?

We can't safely pass a year \\$y\<100\\$ to the `Date` constructor, as it gets interpreted as \\$1900+y\\$. To work around this issue, we add \\$4000\\$ to the year. We make sure to use a multiple of \\$400\\$ so that we have the same properties regarding leap years.

The remaining number of days to reach Epoch from August 11, 3114 BCE + 4000 years is \\$395335\\$.
> 4 votes

# Answer
# JavaScript (Node.js), 74 bytes

```
d=>(i=5,g=(a,m=20-8%--i)=>i?g(a/m|0)+'.'+a%m:a)(new Date(d)/864e5+1856305)

```

Try it online!

Input as `yyyy-MM-dd` format string.

Thanks Arnauld, save 4 bytes.
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 186 ~~163~~ bytes

```
string f(int[]t){int x,n=(int)(new DateTime(t[0],t[1],t[2])-new DateTime(1,1,1)).TotalDays+1137143;return string.Join(".",new[]{144000,7200,360,20,1}.Select(e=>{x=n/e;n%=e;return x;}));}

```

Try it online!

Edit: Use `int[]` as input instead of DateTime to meet the specification better. Thanks @keizerharm for the hint
> 2 votes

# Answer
# C (GCC) ~~239~~ 200

-39 bytes ceilingcat

```
#define S d/m;d%=m;m
l(y){y=y%(y%25?4:16)<1;}b,k,t;D(y,m,d){for(d+=1137110+L" ?[z˜·ÕôēıŐŮ"[m-1]+(m>2?l(y):0);--y;d+=365+l(y));m=144e3;b=S=7200;k=S=360;t=S=20;y=S=1;printf("%d.%d.%d.%d.%d",b,k,t,y,d);}

```

Try it online!
> 1 votes

---
Tags: code-golf, number, date
---