title: Is it an elementary matrix?

text:
# Question
Title: Is it an elementary matrix?
Consider a linear system of equations, in \\$n\\$ unknowns, expressed as

$$A \textbf x = \textbf b$$

where \\$A \in M\_{n,n}(\mathbb Z)\\$ is an \\$n \times n\\$ matrix of integers, \\$\textbf x\\$ is a column vector of unknowns \\$(x\_1, x\_2, \dots, x\_n)\\$ and \\$\textbf b = (b\_1, b\_2, \dots, b\_n)\\$ is a column vector of integers.

We can consider the "augmented" matrix of this system as

$$A' = \begin{pmatrix} a\_{11} & \cdots & a\_{1n} & b\_1 \\ a\_{21} & \cdots & a\_{2n} & b\_2 \\ \vdots & \ddots & \vdots & \vdots \\ a\_{n1} & \cdots & a\_{nn} & b\_n \end{pmatrix} $$

That is, the matrix \\$A\\$ but with an additional column vector \\$\textbf b\\$ as its final column. Let the \\$i\\$th row of \\$A'\\$ be represented as \\$R\_i\\$

There are three elementary row operations we can do to the rows of \\$A'\\$ that leave the solution set \\$\textbf x\\$ unchanged:

* Swapping the order of two rows (\\$R\_i \leftrightarrow R\_j\\$)
* Multiplying a row by a constant \\$\lambda\\$ (\\$R\_i \to \lambda R\_i\\$)
* Adding a multiple of row to a given row (\\$R\_i \to R\_i + \lambda R\_j\\$)

For example, we can say that the two following matrices are equivalent under these row operations:

$$ \begin{pmatrix} 7 & 0 & 0 \\ -3 & -1 & 7 \\ 8 & 0 & -9 \\ \end{pmatrix} \equiv \begin{pmatrix} 8 & 0 & -9 \\ 5 & -1 & -2 \\ 1 & 0 & 0 \\ \end{pmatrix} $$

(The specific row operations here are \\$R\_1 \to \frac 1 7 R\_1\\$, \\$R\_1 \leftrightarrow R\_3\\$, \\$R\_2 \to R\_2 + R\_1\\$)

---

Consider the \\$n\times n\\$ identity matrices:

$$ I\_1 = \begin{pmatrix} 1 \end{pmatrix} \\ I\_2 = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \\ I\_3 = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{pmatrix} \\ \vdots $$

i.e. a given cell \\$(I\_n)\_{ij}\\$ is \\$1\\$ if \\$i = j\\$ and \\$0\\$ otherwise.

We'll say that an integer matrix is an "elementary matrix" if it is **exactly one** elementary row operation away from the identity matrix. For example, the following are all elementary matrices (with the row operation shown)

$$\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \tag{$R\_1 \leftrightarrow R\_2$}$$ $$\begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 3 \\ 0 & 0 & 1 \end{pmatrix} \tag{$R\_2 \to R\_2 + 3R\_3$}$$ $$\begin{pmatrix} -5 \end{pmatrix} \tag{$R\_1 \to -5R\_1$}$$ $$\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & -1 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} \tag{$R\_2 \to R\_2 - R\_4$}$$ $$\begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \tag{$R\_1 \to R\_1$}$$

However, none of these matrices are elementary matrices, as they all require 2 or more row operations from an identity matrix (some row operations shown):

$$\begin{pmatrix} 0 & 2 \\ 1 & 0 \end{pmatrix} \tag{$R\_1 \leftrightarrow R\_2$, $R\_1 \to 2R\_1$}$$ $$\begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{pmatrix}$$ $$\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 1 & 0 & 0 \end{pmatrix} \tag{$R\_2 \leftrightarrow R\_4$, $R\_3 \leftrightarrow R\_4$}$$

---

You are to take a square \\$n \times n\\$ integer matrix and indicate whether it is an elementary matrix or not. This indication can either be:

* Two consistent distinct values to indicate whether the input is or isn't an elementary matrix (e.g. `True`/`False`, `1`/`0`, `"a"`/`7`, etc.)
* Two classes of values, which are naturally interpreted as truthy and falsey values in your language (e.g. `0` and non-zero integers, and empty vs non-empty list etc.)

You may take input in any standard manner or format, including taking \\$n\\$ as an optional input. This is , so the shortest code in bytes wins.

## Test cases

| Input | Output |
| --- | --- |
| ``` 0 1<br>1 0 ``` | `True` |
| ``` 1 0 0<br>0 1 3<br>0 0 1 ``` | `True` |
| ``` -5 ``` | `True` |
| ``` 1 0 0 0<br>0 1 0 -1<br>0 0 1 0<br>0 0 0 1 ``` | `True` |
| ``` 1 0<br>0 1 ``` | `True` |
| ``` 0 0 0<br>0 1 0<br>0 0 1 ``` | `True` |
| ``` 0 2<br>1 0 ``` | `False` |
| ``` 1 2 3<br>4 5 6<br>7 8 9 ``` | `False` |
| ``` 1 0 0 0<br>0 0 1 0<br>0 0 0 1<br>0 1 0 0 ``` | `False` |
| ``` 2 0 0<br>0 0 1<br>0 1 0 ``` | `False` |
| ``` 1 1 1<br>0 1 0<br>0 0 1 ``` | `False` |

# Answer
# Python 3 \+ numpy, 84 bytes

```
lambda m:sum(m!=eye(len(m)))-3*all((m*m==m)*(m@m==eye(len(m))))<2
from numpy import*

```

Try it online!

I'll get things started. No idea how good this is.

Criterion: If the matrix differs from the identity in one or zero places return True. Otherwise allow up to four if the matrix has only ones and zeroes and is its own inverse.

Not 100% sure this is tight.
> 8 votes

# Answer
# Charcoal, ~~41~~ 31 bytes

```
⊙θ⊙θ¬‹⁼κμΣＥθΣＥν¬⁼π⁼ξ⎇⁼ρκμ⎇⁼ρμκρ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if elementary, nothing if not. Explanation: There must be a pair of rows such that the number of differences between the input and the identity matrix with the pair of rows swapped must not exceed zero if the rows are different or one if the rows are the same (i.e. there can be one difference between the input and the identity matrix).

```
⊙θ⊙θ                            Any two rows satisfy
      ⁼κμ                       Same rows
    ¬‹                          Is not less than
          Ｅθ Ｅι                 Map over input matrix
                 π              Current element
               ¬⁼               Does not equal
                  ⁼ξ            Identity matrix
                    ⎇⁼ρκμ⎇⁼ρμκρ With rows swapped
         Σ  Σ                   Take the sum
                                Implicitly print

```
> 3 votes

# Answer
# JavaScript (ES6), 92 bytes

Returns a Boolean value.

```
m=>m.some((P,p)=>m.some((Q,q)=>m.map((r,y)=>(y-p?y-q?r:P:Q).map(v=>e+=v!=!y--),e=p!=q)|e<2))

```

Try it online!

### Commented

```
m =>                // m[] = input matrix
m.some((P, p) =>    // for each row P[] at position p in m[]:
  m.some((Q, q) =>  //   for each row Q[] at position q in m[]:
    m.map((r, y) => //     for each row r[] at position y in m[]:
      (             //       select the relevant row:
        y - p ?     //         if y is not equal to p:
          y - q ?   //           if y is not equal to q:
            r       //             use r[]
          :         //           else:
            P       //             use P[] (swapped with Q[])
        :           //         else:
          Q         //           use Q[] (swapped with P[])
      ).map(v =>    //       for each value v in this row:
        e +=        //         increment e if ...
          v != !y-- //           ... v is not equal to the expected
                    //           value in the identity matrix
      ),            //       end of inner map()
      e = p != q    //       start with e = 1 if two rows were
                    //       actually swapped, or 0 otherwise
    )               //     end of outer map()
    | e < 2         //     yield true if e is less than 2
  )                 //   end of inner some()
)                   // end of outer some()

```
> 3 votes

# Answer
# Core Maude, ~~315~~ ~~302~~ ~~286~~ ~~277~~ ~~276~~ ~~273~~ 268 bytes

```
mod E is pr LIST{Int}. ops e i : Int ~> Int . var A B N X Y Z :[Int]. ceq e(N
X A Y B Z)= 1 if(size(X)rem N + size(Y)rem N)size(A)size(B)i(N 0)X B Y A Z =
0 N N i(N(N ^ 2)). ceq e(N X A Y)= 1 if i(N 0)X I:Int Y := i(N(N ^ 2)). eq
i(N s A)= i(N A)(0 ^(A rem s N)). endm

```

The result is obtained by reducing the `e` function with the width \\$n\\$ prepended to the matrix as a flattened list. The output is either the constant `1` for true, or an error term of sort `[List{Int}]` for false.

### Example Session

```
Maude> --- True
> red e(
>     2
>     0 1
>     1 0
> ) .
result NzNat: 1
Maude>
> --- True
> red e(
>     3
>     1 0 0
>     0 1 3
>     0 0 1
> ) .
result NzNat: 1
Maude>
> --- True
> red e(
>     1
>     -5
> ) .
result NzNat: 1
Maude>
> --- True
> red e(
>     4
>     1 0 0 0
>     0 1 0 -1
>     0 0 1 0
>     0 0 0 1
> ) .
result NzNat: 1
Maude>
> --- True
> red e(
>     2
>     1 0
>     0 1
> ) .
result NzNat: 1
Maude>
> --- True
> red e(
>     3
>     0 0 0
>     0 1 0
>     0 0 1
> ) .
result NzNat: 1
Maude>
> --- False
> red e(
>     2
>     0 2
>     1 0
> ) .
result [List{Int}]: e(2 0 2 1 0)
Maude>
> --- False
> red e(
>     3
>     1 2 3
>     4 5 6
>     7 8 9
> ) .
result [List{Int}]: e(3 1 2 3 4 5 6 7 8 9)
Maude>
> --- False
> red e(
>     4
>     1 0 0 0
>     0 0 1 0
>     0 0 0 1
>     0 1 0 0
> ) .
result [List{Int}]: e(4 1 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0)

```

### Ungolfed

```
mod E is
    pr LIST{Int} .

    ops e i : Int ~> Int .

    var A B N X Y Z : [Int] .

    ceq e(N X A Y B Z) = 1
        if (size(X) rem N + size(Y) rem N) size(A) size(B) i(N 0) X B Y A Z
            = 0 N N i(N (N ^ 2)) .
    ceq e(N X A Y) = 1
        if i(N 0) X I:Int Y := i(N (N ^ 2)) .

    eq i(N s A) = i(N A) (0 ^ (A rem s N)) .
endm

```

We guess a partition of the input list into three or five (possibly empty) sublists, and then attempt to perform the inverse of one of the three row operations.

* Swapping is undone by picking two rows and swapping them.
* Multiplying and adding rows is undone by picking a single element and ignoring it — it either corresponds to the single \\$1\\$ in the row that was multiplied by \\$\lambda\\$, or the single \\$1\\$ in a *different* row that was added.

---

Saved 13 bytes by simplifying the identity matrix function, by recognizing that the \\$1\\$ occurs every \\$(n + 1)\\$ entries.

Saved 16 more bytes by collapsing multiplying and adding into a single case and changing the signature to only one list argument with length prepended.

Saved ~~9~~ 10 more bytes by combining conditions into one list equality.

Saved 3 more bytes using `0 ^ X` to do the equivalent of `!x` in C — i.e., convert non-zero to zero and zero to one. Maude's convention is that \\$x ^ 0 = 1\\$ even for \\$x = 0\\$.

Saved 5 more bytes by removing the base case for `i` and handling it in the pattern matches.
> 3 votes

# Answer
# Desmos, 117 bytes

```
K=[0...W^2]
J=K[(L-0^{mod(K,W+1)})^2>0]
n(L)=L.length

f(L,W)=\{n(J)<2,32=n(\mod(J,W).\unique)^23^{L[J+1]^2}.\total\}

```

This turned out pretty well, considering Desmos's limitations.

The blank line indicates that the subsequent line (`f(L,W)=...`) should be pasted including a leading newline.

Takes input as a flattened list and the width of the matrix.

Returns 1 if the matrix is elementary, otherwise NaN (shown as "undefined")

Try it on Desmos!

### How it works

It's not clear that this golfy approach works, so I'll start with a line-by-line explanation of what the code does, then give a proof of its correctness in the next section.

```
# K: indices of the list L, 0-indexed
#    this has one element more than L, but it gets ignored because
#    operations applied element-wise use the smallest length
K=[0...W^2]

# J: 0-indexed positions in L whose entries differ from the W×W identity matrix
J = K[ # filter K for elements where:
  (    # the corresponding entries differ from the identity matrix:
    L -            # value of L minus
    0^{mod(K,W+1)} # 1 if on main diagonal (mod(K,W+1)=0) else 0
  )^2>0 # this difference must be nonzero; (a-b)^2 > 0 ⟺ a ≠ b
]

# n: helper function to give the length
n(L)=L.length

# f: return 1 if the matrix is elementary, otherwise NaN
f(L,W) = \{
  # If 0 or 1 positions differ from the identity matrix, return 1
  n(J)<2,
  # If the following is true, return 1:
  32 = # 32 is equal to
    n(\mod(J,W).\unique)^2 * # the number of columns containing at least one entry
                             # differing from the identity matrix, squared
    3^{L[J+1]^2}.\total # the total of 3^{e_j} for each entry e_j differing from identity
\}

```

### Proof of correctness

As observed in the other answers, "multiplying a row by a constant" and "adding a multiple of a row to another row" give either the same identity matrix (multiplying by 1 or adding 0 times a row to another row) or the identity matrix with exactly one entry changed. This is handled by `n(J)<2`.

The only condition left to check is swapping two rows.

**Claim:** `32 = n(\mod(J,W).\unique)^2 * 3^{L[J+1]^2}.\total` if and only if L differs from an identity matrix by swapping two rows

**Proof (backward direction):** Assume L differs from an identity matrix by swapping two rows. Then exactly two columns contain entries different from the identity, so `n(\mod(J,W).\unique) = 2`. Additionally, the entries in `L` that are different than the identity must be exactly `0,0,1,1`, so `3^{L[J+1]^2}.\total = 3^0 + 3^0 + 3^1 + 3^1 = 8`. Hence `n(\mod(J,W).\unique)^2 * 3^{L[J+1]^2}.\total = 2^2 * 8 = 32` as desired.

**Proof (forwards direction):** Assume `32 = n(\mod(J,W).\unique)^2 * 3^{L[J+1]^2}.\total`, and assume for sake of contradiction that L does *not* differ from an identity matrix by swapping two rows.

Since each factor is a non-negative integer, we must have that `n(\mod(J,W).\unique)^2` is a factor of 32, so `n(\mod(J,W).\unique)` is a factor of 4.

*Case 1:* Assume `n(\mod(J,W).\unique)=1`, so all incorrect entries are in a single column. Then we must have `3^{L[J+1]^2}.\total = 32/1^2 = 32`. Since all incorrect entries are in a single column, there could be at most 1 incorrect value of `0`. Hence we must have `32` written as a sum of powers of `3` with at most 1 copy of `3^0`; this is impossible since 32 is 2 mod 3, contradiction.

*Case 2:* Assume `n(\mod(J,W).\unique)=2`, so all incorrect entries are in two columns. Then we must have `3^{L[J+1]^2}.\total = 32/2^2 = 8`. Since all incorrect entries are in a single column, there could be at most 2 incorrect values of `0`. Hence we must have `8` written as a sum of powers of `3` with at most 2 copies of `3^0`: the only way to have this is `3^0 + 3^0 + 3^1 + 3^1`, which can only occur when L differs from an identity matrix by swapping two rows, contradiction.

*Case 3:* Assume `n(\mod(J,W).\unique)=4`, so there are at least 4 incorrect entries. We must have `3^{L[J+1]^2}.\total = 32/4^2 = 2`, but this can't happen because `3^{L[J+1]^2}.\total` is the sum of at least 4 terms which are each at least 1, contradiction.

In all cases, there is a contradiction, so L must differ from an identity matrix by swapping two rows, as desired.
> 3 votes

# Answer
# 05AB1E, ~~21~~ 19 bytes

```
δQαDΘO0K22SQsĀ˜O!Θ~

```

Can probably be a golfed a bit more.. Not too happy about the `ΘO0K22SQ`.

Try it online or verify all test cases.

**Explanation:**

```
δQ         # Push an identity matrix of the same size as the input-matrix:
δ          #  Apply on the rows of the (implicit) input-matrix double-vectorized:
 Q         #   Equality check
α          # Take the absolute difference of the values of this identity matrix
           # with the values of the input-matrix at the same positions
 D         # Duplicate this
  ΘO0K22SQ # Check that there are exactly two rows containing exactly two 1s:
  Θ        #  Check for each value if it's equal to 1 (1 if 1; 0 otherwise)
   O       #  Sum each row to get the amount of 1s per row
    0K     #  Remove all 0s from the sums
      22SQ #  And check if this is equal to [2,2]
 s         # Swap so the duplicated list is at the top again
  Ā˜O!Θ    # Check that there are either 0 or 1 cell values changed:
  Ā        #  Check for each whether it's NOT 0 (0 if 0; 1 otherwise)
   ˜       #  Flatten the matrix
    O      #  Get the sum of this list
     !     #  Get the factorial of it (0 to 1; 1 remains 1; >=2 just becomes larger)
      Θ    #  Check if this is equal to 1
~          # Bitwise-OR to check if either of the two checks is 1
           # (after which this is output implicitly as result)

```
> 2 votes

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


title: BitCycle Metagolf

text:
# Question
Title: BitCycle Metagolf
# Background

BitCycle is a two-dimensional Turing-complete programming language involves moving bits around a playfield.

Because I am too lazy to write BitCycle programs myself, you will be writing a program which outputs BitCycle programs for me! Unfortunately, the storage space on my computer is only about a bit, so you will have to make the BitCycle programs as small as possible.

# How does BitCycle Work?

In BitCycle, a program is a 2D grid of characters (the playfield), implicitly right-padded with spaces to form a full rectangle. During execution, bits move around this playfield, encountering various devices that can trigger various effects. All bits move at the same time, which is once per tick.

A `0` or `1` in the program places a single bit of the specified type on the playfield at the start of execution, moving east.

The device `!` is a sink. Any bit that hits it is output and removed from the playfield. For simplicity, your outputted program can only contain **exactly one sink**. Also, programs will be ran with the `-u` (unsigned integers) flag, which basically indicates that the program will output a positive integer based on how many `1`'s it receives before the program terminates. Passing a `0` into a sink will have other effects on the output, but for simplicity, outputted BitCycle programs **should only pass `1`'s into the sink**, or else the submission is invalid.

The devices `<`, `^`, `>`, and `v` change a bit's direction unconditionally. For example, if a bit hits a `<`, it will start travelling to the left. The device `+` is a conditional direction change. An incoming 0 bit turns left; an incoming 1 bit turns right.

The devices `\` and `/` are splitters. When the first bit hits them, they reflect it 90 degrees, like the mirrors in \>\<\>. After one reflection, though, they change to their inactive forms `-` and `|`, which pass bits straight through.

The device `=` is a switch. The first bit that hits it passes straight through. If that bit is a `0`, the switch becomes `{`, which redirects all subsequent bits to the west (like `<`). If the bit is a `1`, the switch becomes `}`, which redirects all subsequent bits to the east (like `>`).

The device `~`, dupneg, creates a negated copy of each incoming bit: if the bit is `0`, then the copy is `1`, and vice versa. The original bit turns right, and the copy turns left relative to its current direction of travel.

All splitters and switches on the playfield reset to their original states whenever one or more collectors come open (see below).

Any letter except `V`/`v` is a collector. A collector maintains a queue of bits. It has two states, closed (represented by an uppercase letter) and open (represented by the corresponding lowercase letter). In both states, bits that hit the collector are added to the end of its queue. When the collector is closed, bits stay in the queue. When it is open, bits are dequeued (one per tick) and sent out eastward from the collector. An open collector stays open until all its bits have been dequeued (including any that may have come in while it was open), at which point it switches back to closed.

There may be multiple collectors with the same letter. Each collector has a separate queue.

When there are no bits moving on the playfield (i.e. all the bits are in collectors), the program finds the earliest-lettered collector with a nonempty queue. All collectors with that letter will then open.

Once a collector is open, it stays open until its queue is emptied; but a closed collector will only open when there are no bits active on the playfield.

When any bit hits the device `@`, the program terminates. The program also terminates if there are no bits remaining, either on the playfield or in collectors. All unassigned characters are no-ops.

Two or more bits can occupy the same space at the same time. The ordering between them if they hit a collector, splitter, switch, or sink simultaneously is undefined (**use at your own risk**). Because different implementations of BitCycle deal with undefined behavior in different ways, your outputted BitCycle programs all have to run correctly on Try It Online!.

(Reference: GitHub Page for BitCycle)

# Challenge

Given a positive integer as input, your program should output a valid BitCycle program (with the restriction of only having one sink) which outputs the input number and halts under the `-u` flag. Total score will be calculated by the sum of the lengths of the output BitCycle programs when your program is ran against the test cases shown below. **Please provide your submission's score when answering.**

**If it is suspected that someone is hardcoding the output for this specific test suite, I can change existing test cases or even add new ones.**

# Test Suite

```
1
6
20
45
47
127
128
277
420
523
720
1000
2187
2763
4096
4555
7395
8718
9184
9997

```

# Note

The challenge can be trivially solved by printing out the appropriate amount of `1`'s followed by a `!`. For example, `5` can be outputted as follows:

```
11111!

```

In order to be competitive, your program should aim to output BitCycle programs that are generally shorter than programs generated by this trivial method (especially for larger input numbers). In other words, **your score should be less than 51983** (the score obtained when using the trivial method).

---

This is **not** , so don't feel obliged to golf your code in any way!

# Answer
# Python, scores 1186

Generates a binary to unary converter with a few tricks shortening specific bit patterns.

```
import re

def f(n):
    if n < 40:
        return n*'1' + '!'
    d = [x.replace('0', '') for x in bin(n)[2:]]
    q = d[1] == '1'
    del d[1]
    return '\n'.join([
        ' '*q + re.sub(r'(?<!^) >v ', ' >v', '>v'.join(d).replace(*'1 ').replace(*' 1', 1))+'~',
        '1'*q + re.sub(r'(?<!^)1~>1', '1~>', '~>'.join(d))+'+',
        ' '*q + re.sub(r'(?<!^) >\^ ', '1>^', '>^'.join(d).replace(*'1 ').replace(*' 1', 1))+'!'
    ])

```

Try it online and verify all cases!

Converts the number to binary and constructs the program from doublers:

```
>v
~>
>^

```

This doubles the number of bits moving east on the middle row. In the end all bits have to be converted to 1's, which can be done with

```
v~
>+
 !

```
> 4 votes

---
Tags: code-challenge, metagolf, test-battery
---


title: Subtract the next numbers

text:
# Question
Title: Subtract the next numbers
# Description

Subtract the next P numbers from a N number. The next number of N is N + 1.

Look at the examples to get what I mean.

# Examples:

```
Input: N=2,P=3
Calculate: n - (n+1) - (n+2) - (n+3)     //Ending with 3, because P=3
Calculate: 2 -  2+1  -  2+2  - 2+3       //Replacing N with 2 from Input
Calculate: 2 -  3    -  4    - 5
Output: -10

Input: N=100,P=5
Calculate: n - (n+1) - (n+2) - (n+3) - (n+4) - (n+5)
Calculate: 100-  101 -  102  -  103  -  104  - 105
Output: -415

Input: N=42,P=0
Calculate: n
Calculate: 42
Output: 42

Input: N=0,P=3
Calculate: n - (n+1) - (n+2) - (n+3)
Calculate: 0 -  1    -  2    -  3
Output: -6

Input: N=0,P=0
Calulate: n
Calculate: 0
Output: 0

```

# Input:

**N**: Integer, positive, negative or 0

**P**: Integer, positive or 0, not negative

# Output:

Integer or String, leading 0 allowed, trailing newline allowed

# Rules:

* No loopholes
* This is code-golf, so shortest code in bytes wins
* Input and Output must be as described

# Answer
> 15 votes
# 05AB1E, ~~5~~ 3 bytes

Saved 2 bytes thanks to Adnan

```
Ý+Æ

```

**Explanation**

Takes P then N as input.

```
       # implicit input, ex 5, 100
Ý      # range(0,X): [0,1,2,3,4,5]
 +     # add: [100,101,102,103,104,105]
  Æ    # reduced subtraction: 100-101-102-103-104-105

```

# Answer
> 17 votes
# Python 2, ~~26 24~~ 23 bytes

-2 bytes thanks to @Adnan (replace `p*(p+1)/2` with `p*-~p/2`)
-1 byte thanks to @MartinEnder (replace `-p*-~p/2` with `+p*~p/2`

```
lambda n,p:n-p*n+p*~p/2

```

Tests are on **ideone**

# Answer
> 11 votes
## CJam, 8 bytes

```
{),f+:-}

```

Test suite.

Too bad that the closed form solution is longer. :|

### Explanation

```
),  e# Get range [0 1 ... P].
f+  e# Add N to each value to get [N N+1 ... N+P].
:-  e# Fold subtraction over the list, computing N - (N+1) - (N+2) - ... - (N+P).

```

# Answer
> 11 votes
## Haskell, 21 bytes

```
a#b=foldl1(-)[a..a+b]

```

# Answer
> 10 votes
## Javascript (ES6), ~~20~~ ~~19~~ 18 bytes

```
n=>p=>n+p*(~p/2-n)

```

*Saved 1 byte by currying, as suggested by Zwei*
*Saved 1 byte thanks to user81655*

### Test

```
let f =
n=>p=>n+p*(~p/2-n)

console.log(f(2)(3))
console.log(f(100)(5))
console.log(f(42)(0))
console.log(f(0)(3))
console.log(f(0)(0))
```

# Answer
> 8 votes
# Haskell, ~~19~~ 18 bytes

```
n#p=n+sum[-n-p..n]

```

Previous 19 bytes solutions

```
n#p=n-n*p-(p*p+p)/2
n#p=n-sum[n+1..n+p]

```

# Answer
> 8 votes
# Jelly, 4 bytes

```
r+_/

```

Try it online!

### How it works

```
r+_/  Main link. Arguments: n, p

 +    Yield n+p.
r     Range; yield [n, ..., n+p].
  _/  Reduce by subtraction.

```

# Answer
> 7 votes
# C#, 21 20 bytes

*Edit: Saved one byte thanks to TheLethalCoder*

```
N=>P=>N-P++*(N+P/2);

```

**Try it online!**

Full source, including test cases:

```
using System;

namespace substract
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,Func<int,int>>s=N=>P=>N-P++*(N+P/2);
            Console.WriteLine(s(2)(3));     //-10
            Console.WriteLine(s(100)(5));   //-415
            Console.WriteLine(s(42)(0));    //42
            Console.WriteLine(s(0)(3));     //-6
            Console.WriteLine(s(0)(0));     //0

        }
    }
}

```

# Answer
> 5 votes
# Perl, ~~23~~ 22 bytes

Includes +1 for `-p`

Give n and p (in that order) on separate lines of STDIN:

```
subtract.pl
2
3
^D

```

`subtract.pl`:

```
#!/usr/bin/perl -p
$_-=eval"+2+\$_++"x<>

```

(using `''` quotes to save the `\` invokes a 2 byte penalty because it can't be combined with `-e`)

Same idea and length:

```
#!/usr/bin/perl -p
$_+=eval"-1-++\$_"x<>

```

Surprisingly doing the actual calculation is shorter than using the direct formula (these `$`'s really hurt for arithmetic)

# Answer
> 5 votes
## C++, ~~54~~ 51 bytes

```
  [](int N,int P){int F=N;while(P--)F-=++N;return F;}

```

~~\[\](int N,int P){int F;for(F=N;P;F-=++N,P--);return F;}~~

## Test:

```
#include <iostream>
int main(void)
{
    int N, P;
    std::cin >> N >> P;
    auto f = [](int N,int P){int F=N;while(P--)F-=++N;return F;};
    std::cout << f(N,P) << std::endl;
    return 0;
}

```

# Answer
> 5 votes
## Mathematica, 15 bytes

```
#2-##-#(#+1)/2&

```

An unnamed function that receives `P` and `n` as its parameters in that order.

Uses the closed form solution `n - n*p - p(p+1)/2`.

# Answer
> 4 votes
## Pyke, 6 bytes

```
m+mhs-

```

Try it here!

```
m+     -    map(range(input_2), +input_1)
  mh   -   map(^, +1)
    s  -  sum(^)
     - - input_1 - ^

```

# Answer
> 4 votes
# Brachylog, ~~19~~ 17 bytes

```
hHyL,?+y:Lx+$_:H+

```

### Explanation

```
hH                  Input = [H, whatever]
 HyL,               L = [0, …, H]
     ?+             Sum the two elements in the Input
       y            Yield the range from 0 to the result of the sum
        :Lx         Remove all elements of L from that range
           +        Sum the remaining elements
            $_      Negate the result
              :H+   Add H

```

# Answer
> 4 votes
# MATL, 5 bytes

```
:y+s-

```

Inputs are `P` and then `N`.

Try it at MATL Online!

### Explanation

```
:     % Take P implicitly. Range [1 2 ... P]
      %     Stack: [1 2 ... P]
y     % Take N implicitly at the bottom of the stack, and push another copy
      %     Stack: N, [1 2 ... P], N
+     % Add the top two arrays in the stack , element-wise
      %     Stack: N, [N+1 N+2 ... N+P]
s     % Sum of array
      %     Stack: N, N+1+N+2+...+N+P
-     % Subtract the top two numbers
      %     Stack: N-(N+1+N+2+...+N+P)
      % Implicitly display

```

# Answer
> 4 votes
# Forth, 36 bytes

Simple computation of `n - (p*n + (p^2+p) / 2)`

```
: f 2dup dup dup * + 2/ -rot * + - ;

```

**Try it online**

# Answer
> 3 votes
# Fourier, 34 bytes

```
I~No~OI~P>0{1}{@P+N(N^~NO-N~ON)Oo}

```

**Try it online!**

# Answer
> 3 votes
## Batch, 30 bytes

```
@cmd/cset/a%1-(%1*2+%2+1)*%2/2

```

Takes `n` and `p` as command-line parameters and prints the result without a trailing newline.

# Answer
> 3 votes
## S.I.L.O.S, 80 bytes

```
GOTO b
lbla
n+1
m-n
i-1
GOTO d
lblb
readIO
n=i
m=n
readIO
lbld
if i a
printInt m

```

Try it online with test cases:
2,3
100,5
42,0
0,3
0,0

# Answer
> 3 votes
# R, ~~17~~ 14 bytes

```
N-N*P-sum(0:P)

```

Thanks to billywob for golfing away 3 bytes. Previous answer:

```
N-sum(N+if(P)1:P)

```

Note that 1:0 expands to the vector (1,0) so we need the if(P) condition (or to use `seq_len`, but that is more bytes). Without the condition, we would get the wrong output if P=0.

If P is zero, then the sum expands to `sum(N+NULL)`, then to `sum(numeric(0))`, which is zero.

# Answer
> 3 votes
# Java, ~~67~~, 63 bytes

Golfed:

```
int x(int n,int p){return-((p%2<1)?p*p/2+p:p/2*(p+2)+1)+n-p*n;}

```

Ungolfed:

```
int x(int n, int p)
{
    return -((p%2<1) ? p*p/2+p : p/2 * (p+2) + 1) + n - p*n;
}

```

Basically I did some math on the formula. The `n - p*n` part takes care of the all `n`'s in the formula. Then I used a super fun property of summing together linearly increasing set of integers (arithmetic series): I used the sum of first and last integer and then multiply it by `set.length / 2` (I also check for the parity and handle it appropriately).

Try it: https://ideone.com/DEd85A

# Answer
> 3 votes
# Java 7, ~~43~~ 40 bytes

```
int c(int n,int p){return n-p*n+p*~p/2;}

```

# Java 8, 19 bytes

```
(n,p)->n-p*n+p*~p/2

```

Shamelessly stolen from *@JonathanAllan*'s amazing Python 2 formula.

**Original answer (~~61~~ 60 bytes):**

```
int c(int n,int p){int r=n,i=1;for(;i<p;r-=n+++i);return r;}

```

**Ungolfed & test cases:**

Try it here.

```
class M{
  static int c(int n, int p){
    return n - p*n + p*~p / 2;
  }

  public static void main(String[] a){
    System.out.println(c(2, 3));
    System.out.println(c(100, 5));
    System.out.println(c(42, 0));
    System.out.println(c(0, 3));
    System.out.println(c(0, 0));
  }
}

```

**Output:**

```
-10
-415
42
-6
0

```

# Answer
> 3 votes
# PHP, 33 Bytes

```
$n-=$n*$p+array_sum(range(0,$p));

```

# Answer
> 3 votes
# Jelly, 7 bytes

```
RS+×_×-

```

Arguments are `P, N`
Test it on **TryItOnline**

How?

```
RS+×_×-  - takes two arguments: P, N
R        - range(P): [1,2,3, ... ,P]
 S       - sum: 1+2+3+ ... +P
   ×     - multiply: P*N
  +      - add: 1+2+3+ ... +P + P*N
    _    - subtract: 1+2+3+ ... +P + P*N - N
      -  - -1
     ×   - multiply: (1+2+3+ ... +P + P*N - N)*-1
                   = -1-2-3- ... -P - P*N + N
                   = N - (N+1) - (N+2) - (N+3) - ... - (N+P)

```

# Answer
> 3 votes
# Pyth - 6 bytes

```
-F}Q+E

```

Test Suite.

# Answer
> 2 votes
## Labyrinth, 15 bytes

```
?:?:}*-{:)*#/-!

```

or

```
??:}`)*{:)*#/-!

```

Uses the closed form solution `n - n*P - P*(P+1)/2`.

# Answer
> 2 votes
# php, 38 bytes

```
<?=$argv[1]*(1-$a=$argv[2])-$a++*$a/2;

```

# Answer
> 2 votes
# Burlesque, 12 bytes

```
perz?+{.-}r[

```

Try it online!

```
pe     #Read input as P, N
rz     #Range (0,N)
?+     #Add P to each
{.-}r[ #Reduce via subtraction

```

# Answer
> 2 votes
# Vyxal, 4 bytes

```
+ṡƒ-

```

Try it Online!

Port of Jelly answer.

## How?

```
+ṡƒ-
+ṡ   # Inclusive range [a, a + b]
  ƒ- # Reduce by subtraction

```

# Answer
> 2 votes
# TI-Basic, 17 bytes

```
Prompt N,P
N-NP-.5(P²+P

```

Alternatives:

```
Prompt N,P
N-P(P/2+.5+N

```

```
Prompt N,P
N-NP-.5P(P+1

```

```
Prompt N,P
N-.5P(2N+P+1

```

# Answer
> 1 votes
# Pyth, 11 bytes

```
Ms+Gm_+GdSH

```

A function `g` that takes input of `n` and `p` via argument and prints the result. It can be called in the form `gn p`.

Try it online

**How it works**

```
Ms+Gm_+GdSH  Function g. Inputs: G, H
M            g=lambda G,H:
         SH   1-indexed range, yielding [1, 2, 3, ..., H]
    m_+Gd     Map lambda d:-(G+d) over the above, yielding [-(G+1), -(G+2), -(G+3),
              ..., -(G+H)]
  +G          Add G to the above, yielding [G, -(G+1), -(G+2), -(G+3), ..., -(G+H)]
 s            Reduce on addition with base case 0, yielding G-(G+1)-(G+2)-(G+3)...
              -(G+H)
              Implicitly print

```

# Answer
> 1 votes
# C89, ~~38~~, ~~35~~, 33 bytes

```
h(n,p,r)int*r;{*r=n-p++*(n+p/2);}

```

Test it on Coliru.

# Answer
> 1 votes
# Maple, 19 bytes

```
n-sum(i,i=n+1..n+p)

```

Usage:

```
> f:=(n,p)->n-sum(i,i=n+1..n+p);
> f(2, 3);
  -10
> f(100,5);
  -415
> f(42,0);
  42

```

# Answer
> 1 votes
# Perl 6, 21 bytes

```
{$^n-[+] $n^..$n+$^p}

```

## Explanation:

```
# bare block lambda with two placeholder parameters ｢$n｣ and ｢$p｣
{
  $^n -
      # reduce using ｢&infix:<+>｣
      [+]
          # a Range that excludes ｢$n｣ and has ｢$p｣ values after it
          $n ^.. ($n + $^p)
}

```

# Answer
> 1 votes
# Java 8, 25 bytes

```
(n,p)->n-(p*n+p*(p+1)/2);

```

# Ungolfed test program

```
public static void main(String[] args) {

    BiFunction<Integer, Integer, Integer> f = (n, p) -> n - (p * n + p * (p + 1) / 2);
    System.out.println(f.apply(100, 5));
}

```

# Answer
> 1 votes
# Scala, 41 bytes

```
def?(n:Int,p:Int)=n-(1 to p).map{n+_}.sum

```

Testing code:

```
println(?(2,3))
println(?(100,5))
println(?(42,0))
println(?(0,3))
println(?(0,0))

// Output
-10
-415
42
-6
0

```

# Answer
> 1 votes
# Clojure/Clojurescript, 30 bytes

```
#(reduce -(range %(+ 1 % %2)))

```

The straightforward approach is shorter than the mathematically clever ones.

# Answer
> 1 votes
# Julia: 17-18 bytes (13 as program with terminal inputs)

As per suggestion in comments that "function or program" form is needed:

* as function: 17 characters, 18 bytes if you count ∘ as multibyte

```
n∘r=2n-sum(n:n+r)

```

usage: `5∘3` outputs `-16`
* as program, passed initial parameters from terminal: 13 bytes:

```
2n-sum(n:n+r)

```

usage: `julia -E 'n,r=5,3;include("codegolf.jl")'`

# Answer
> 1 votes
# Excel, 20 bytes

Subtract the next `B1` integers from `A1`:

```
=A1-B1*(A1+(B1+1)/2)

```

# Answer
> 1 votes
# GolfScript, 11 bytes

Formula stolen elsewhere...

```
~1$1$)2/+*-

```

Try it online!

## Explanation

This just boils down to

```
A-B*(A+(B+1)/2)

```

Converted to postfix.

# GolfScript, 15 bytes

```
~),{1$+}%{-}*\;

```

Try it online!

## Explanation

```
~               # Evaluate the input
 ),             # Generate inclusive range
   {1$+}%       # Add each item by the other input
         {-}*   # Reduce by difference
             \; # Discard the extra other input

```

# Answer
> 1 votes
# Keg, `-hr`, ~~8~~ 6 bytes

```
+ɧ^∑$-

```

Try it online!

No formula, just a for loop!

# Answer
> 1 votes
## `d`, ~~6~~ 4 bytes

Surprised to see that it's not short at all. (Although it at least ties with Jelly...)

```
7▄i←

```

## Explanation

Uncompressed:

```
+.@-R
+     % Generate b+a
 .    % Generate range(a,b+a)
  @-R % Reduce via subtraction

```

# Answer
> 1 votes
# Japt, 5 bytes

```
ôV r-

```

Try it

```
ôV r-     :Implicit input of integers U=N & V=P
ôV        :Range [U,U+V]
   r-     :Reduce by subtraction

```

# Answer
> 1 votes
# Demsos, 20 bytes

```
f(n,p)=n-p(p/2+.5+n)

```

Other 20-byters:

```
f(n,p)=n-pn-p(p+1)/2
f(n,p)=n-pp/2-.5p-np
f(n,p)=n-.5p(2n+p+1)
f(n,p)=n-pn-.5pp-.5p

```

Try it on Desmos!

With the sum function, it's 27 bytes:

```
f(n,p)=n-∑_{x=n+1}^{n+p}x

```

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

```
{-/x+!y+1}

```

Try it online!

Quick.

# Answer
> 1 votes
# Python 3, 43 bytes

```
lambda n,p:n-sum([n+i+1 for i in range(p)])

```

Try it online!

Explanation:

```
lambda n,p:                                  # Lambda header
                 [n+i+1 for i in range(p)]   # Next P numbers
             sum(                          ) # Sum each number
           n-                                # Subtract from N for final result

```

# Answer
> 1 votes
# Ly, 14 bytes

```
n0ns-0Rl0I*-&+

```

Try it online!

This relies on the fact that for X=starting number and Y=iterator, the answer is:

`X - (X*Y) - sum([1..Y])`

It uses the `R` command to generate the range of negative numbers.

```
n              - read starting number onto the stack
 0n            - push "0", read iteration count onto the stack
   s           - save iteration count
    -          - convert to negative number
     0         - push "0" to set ending number
      R        - generate a range of negative numbers
       l       - load the iterator count
        0I     - copy the starting number
          *    - multiple to get base number common to all decrements
           -   - convert to negative (relies on "0" from range)
            &+ - sum the stack, answer prints automatically

```

# Answer
> 0 votes
# APL (Dyalog Unicode), 12 bytes

```
⊣-(+/(⍳⊢)+⊣)

```

Try it online!

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


title: Sums of 100 Rolls of Two Six Sided Dice

text:
# Question
Title: Sums of 100 Rolls of Two Six Sided Dice
Suppose you have two six-sided dice. Roll the pair 100 times, calculating the sum of each pair. Print out the number of times each sum occurred. If a sum was never rolled, you must include a zero or some way to identify that that particular sum was never rolled.

Example Output: \[3, 3, 9, 11, 15, 15, 11, 15, 7, 8, 3\]

The number of times a sum was rolled is represented in the sums index - 2

In this example, a sum of two was rolled 3 times (\[2-2\]), a sum of three 3 times (\[3-2\]), a sum of four 9 times (\[4-2\]), and so on. It does not matter the individual dice rolls to arrive at a sum (5 and 2 would be counted as the same sum as 6 and 1)

"Ugly" outputs are fine (loads of trailing zeros, extra output, strange ways of representing data, etc.) as long as you explain how the data should be read.

# Answer
# Jelly, ~~13~~ 12 bytes

```
³Ḥ6ẋX€+2/ṢŒr

```

A niladic link. Output format is a list of lists of `[value, count]`.

(Zero rolls means no such entry is present in the output - e.g. an output of`[[6, 12], [7, 74], [8, 14]]` would identify that only sums of six, seven and eight were rolled.)

**Try it online!**

### How?

```
³Ḥ6ẋX€+2/ṢŒr - Main link: no arguments
³            - 100
 Ḥ           - double = 200
  6          - 6
   ẋ         - repeat -> [6,6,6...,6], length 200
    X€       - random integer from [1,z] for €ach (where z=6 every time)
       2/    - pairwise reduce with:
      +      -   addition (i.e. add up each two)
         Ṣ   - sort
          Œr - run-length encode (list of [value, length] for each run of equal values)

```
> 5 votes

# Answer
# Python 2, ~~84~~ ~~77~~ 76 bytes

*-7 bytes thanks to @JonathanAllan*
*-1 byte thanks to @FelipeNardiBatista*

```
from random import*
a=[0]*13
exec'a[%s]+=1;'%('+randint(1,6)'*2)*100
print a

```

Try it online!

The output has two leading zeros
> 4 votes

# Answer
# Perl 6, 30 bytes

```
bag [Z+] (^6).pick xx 100 xx 2

```

`(^6).pick` is a random number from zero through five. `xx 100` makes a hundred-element list of such numbers. `xx 2` produces two such lists. `[Z+]` zips those two lists with addition, producing a hundred-element list of two-die rolls. Finally, `bag` puts that list into a bag, which is a collection with multiplicity. Example REPL output:

```
bag(1(4), 9(4), 0(4), 4(14), 5(18), 3(9), 10(2), 6(19), 7(13), 2(3), 8(10))

```

That means 1, 9, and 0 occurred four times each, four occurred fourteen times, etc. Since the "dice" in this code produce a number from 0-5, add two to each of these numbers to get the rolls a pair of standard 1-6 dice would produce.
> 3 votes

# Answer
# 05AB1E, ~~21~~ 19 bytes

-2 bytes thanks to @Emigna

```
TÝÌтF6Lã.RO¸ì}{γ€g<

```

Try it online!

```
TÝÌтF6Lã.RO¸ì}{γ€g<
TÝÌ                   Range from 2 to 12
   тF                 100 times do:
     6L                 Range from 1 to 6
       ã                Cartesian product (creates all possible pairs of 1 and 6)
        .RO             Choose random pair and sum
           ¸ì           Prepend result to initial list
             }        end loop
              {γ€g<   Sort, split on consecutive elements, count and decrement

```
> 3 votes

# Answer
## CJam, ~~18~~ 20 bytes

```
100{;6mr6mr+))}%$e``

```

Try it online!
> 2 votes

# Answer
# Mathematica, 50 bytes

```
r:=RandomInteger@5
Last/@Tally@Sort@Table[r+r,100]

```

Straightforward implementation. If any sum is never achieved, the `0` is omitted from the list.
> 2 votes

# Answer
# MATL, 17 bytes

```
6H100I$Yrs!11:Q=s

```

Output is a list of 11 numbers (some of them possibly 0) separated by spaces, indicating the number of times for each pair from 2 to 12.

Try it online!

For comparison, the theoretical average number of times each pair will appear on average can be computed as `6:gtY+36/100*`.

If the number of rolls is increased the obtained values approach the theorerical ones. See for example the obtained and theoretical values with 10000 rolls.
> 2 votes

# Answer
# , ~~45~~ ~~37~~ 35 bytes

```
`[`=sample;table(6[100,T]+6[100,T])

```

Try it online!

*-7 bytes thanks to Jarko Dubbledam*
> 2 votes

# Answer
# JavaScript, ~~72~~ 70 bytes

Outputs an array of *up to* 11 elements for each of the roll counts. Except for the first element, if the count is `0` then the element will be empty or, if it's at the end of the array, omitted completely.

```
f=(a=[n=0])=>n>99?a:f(a,a[x=(g=_=>Math.random()*6|0)()+g(++n)]=-~a[x])

```

Try it online!
> 1 votes

# Answer
# PHP, 53 Bytes

prints an associative array. key is result of two dices and value is the count of these results

```
for(;$i++<100;)$r[rand(1,6)+rand(1,6)]++;print_r($r);

```

Try it online!
> 1 votes

# Answer
# q/kdb+, ~~31~~ ~~28~~ 25 bytes

**Solution:**

```
sum!:[11]=/:sum(2#100)?'6

```

**Example:**

```
q)sum!:[11]=/:sum(2#100)?'6
1 3 5 11 16 21 16 9 8 9 1i

```

**Explanation:**

Roll a dice `100?6` , roll a dice again and add the vectors together. Then see where each results matches the range 0..10, then sum up all the trues in each list:

```
sum til[11]=/:sum(2#100)?'6 / ungolfed solution
                 (2#100)    / 2 take 100, gives list (100;100)
                        ?'6 / performs rand on each left-each right, so 100 & 6, 100 & 6
              sum           / add the lists together
    til[11]                 / the range 0..10
           =/:              / apply 'equals?' to each right on left list
sum                         / sum up the results, e.g. how many 1s, 2s, 3s.. 12s

```

**Notes:**

'Golfing' is mostly swapping out `q` keywords for the `k` equivalents, namely `each` and `til`.
> 1 votes

# Answer
# S.I.L.O.S, 99 bytes

```
i=100
lbla
x=rand*6+rand*6
a=get x
a+1
set x a
i-1
if i a
lblb
c=get b
printInt c
b+1
d=11-b
if d b

```

Try it online!

Rolls the dice, and stores them in the first 11 spots of the heap, then just iterates through the heap printing each counter. This is one of the first recorded uses of the rand keyword combined with an assignment operator.

It is worth noting, that a few modifications can be made to output a histogram of the rolls.

Unfortunately it must be run from the offline interpreter.

```
i=4000
lbla
x=rand*6+rand*6
a=get x
a+1
set x a
i-1
if i a
canvas 1100 1000 Output
lblb
c=get b
printInt c
d=c*1
y=1000-d
x=b*100
newObj 0 100 d
moveObj b x y
b+1
d=11-b
if d b
wait 10000

```
> 1 votes

# Answer
**Elixir, ~~157~~ 118 bytes**

```
l=&Enum.random(1..&1)
p=fn(o,s)->y=l.(6)+l.(6)
s=List.update_at(s,y,&(&1+1))
if Enum.sum(s)<100 do s=o.(o,s) end
s end

```

Tried something harder than Jelly.

Explanation:

1. Define function that returns a random number between 1 and 6 inclusive.
2. Define the function anonymously and let `y` be the variable with the roll sum.
3. update the appropriate place in the list by adding 1.
4. if we are 100 rolls in, quit. Else call yourself again passing in yourself and the updated list.
5. return the updated array.

Should be called like `p.(p,[0,0,0,0,0,0,0,0,0,0,0,0,0])`. It will raise a warning, but it will return the desired array with 13 elements, the first 2 should be ignored.
> 1 votes

# Answer
# Java 8, 104 bytes

A lambda returning an `int[]` of frequencies. Assign to `Supplier<int[]>`.

```
()->{int o[]=new int[11],i=0;while(i++<100)o[(int)(Math.random()*6)+(int)(Math.random()*6)]++;return o;}

```

Try It Online

## Ungolfed lambda

```
() -> {
    int
        o[] = new int[11],
        i = 0
    ;
    while (i++ < 100)
        o[(int) (Math.random() * 6) + (int) (Math.random() * 6)]++;
    return o;
}

```
> 1 votes

# Answer
## Javascript ~~85~~ 75 characters

Thanks Shaggy!

```
a=[]
for(i=100;i--;)a[o=(f=_=>Math.random()*6|0)()+f()]=(a[o]|0)+1
alert(a)

```

### History

### 85

```
a={}
f=_=>Math.random()*6
for(i=0;i++<100;)a[o=-~f()-~f()]=(a[o]||0)+1
console.log(a)

```
> 0 votes

# Answer
## QBIC, 45 bytes

```
[100|h=_r1,6|+_r1,6|-2┘g(h)=g(h)+1][0,z|?g(b)

```

Explanation:

```
[100|         FOR a = 1 to 100
h=_r1,6|       set h to a random value between 1-6
 +_r1,6|       + another rnd(1,6) (2, 3 ... 11, 12)
 -2            - 2 (index: 0 ... 10
┘             Syntactic linebreak
g(h)          When using array parenthesis on an undefined array,
              it is interpreted as an array with 10 indexes of all zeroes.
    =         Of array g, set the value of index h (0 ... 11)
      g(h)+1  to one higher (all indices start out as 0)
              Note that we need to track 11 values. Fortunately, QBasic'set
              empty, 10-sized array has 11 indices, because of base 0 / base 1 ambiguity.
]             NEXT set of dice
[0,z|         FOR b = 0 to 10
?g(b)           PRINT the tracker array

```
> 0 votes

# Answer
# APL, 14 bytes

```
,∘≢⌸+/?100 2⍴6

```

Presents data as a table with the left column representing the sum and the right representing the number of occurrences.

**Explained**

```
        100 2⍴6  ⍝ create an 2×100 array of 6
       ?         ⍝ roll for each cell from 1 to 6
     +/          ⍝ sum every row
   ⌸            ⍝ for every unique sum
,∘≢              ⍝ get the sum and the number of indexes

```

---

**Previous post:**

### APL, ~~36~~ 31 bytes

*5 bytes saved thanks to @Adám*

```
(11⍴⍉⌽f)[⍋11⍴⍉f←,∘≢⌸+/?100 2⍴6]

```

**Explanation**

```
f←,∘≢⌸+/?100 2⍴6
          100 2⍴6    ⍝ create an 2×100 array of 6
         ?           ⍝ roll for each cell from 1 to 6
       +/            ⍝ sum every row
     ⌸              ⍝ for every unique sum
  ,∘≢                ⍝ get the sum and the number of indexes

(11⍴⍉⌽f)[⍋11⍴⍉f]  ⍝ ⍋x returns the indexes of the sorted x in the current x
                     ⍝ x[y] find the yth elements of x
                     ⍝ x[⍋y] reorders x the same way that would be required to sort y

            11⍴⍉f   ⍝ the column of sums - see below
 11⍴⍉⌽f            ⍝ the column of counts - see below

```

**How does `11⍴⍉⌽f` works?**

```
⍝ ⌽ - Reverses the array
⍝ ⍉ - Transposes the array

  ⍝   f
 9 14   ⍝ Sum - Occurences
 4  9
 7 17
 8 18
 6 15
 5  7
10  3
11  5
 3  6
 2  2
12  4

  ⍝   ⍉f
 9 4  7  8  6 5 10 11 3 2 12  ⍝ Sum
14 9 17 18 15 7  3  5 6 2  4  ⍝ Occurences

  ⍝   ⍉⌽f
14 9 17 18 15 7  3  5 6 2  4  ⍝ Occurences
 9 4  7  8  6 5 10 11 3 2 12  ⍝ Sum

```
> 0 votes

# Answer
## \>\<\>, 93 bytes

```
00[0[v
v 1\v/4
v 2xxx5
v 3/^\6
>l2(?^+]laa*=?v0[
  /&1+&\ v1&0]<
=?/ :?!\}>:@@:@
oa&0n&}< ^+1

```

Try it online, or watch it at the fish playground!

The ugly output format is a sequence of numbers separated by newlines, where the *n*th number says how many times the sum was *n* — it's ugly because it prints forever, for all positive integers *n*, although most of the lines will be 0. (The TIO link is modified to stop after *n*=12, at the cost of 5 bytes.)

The fish playground is fairly slow — it takes about three and a half minutes to print up to *n*=12 at top speed — so you may want to modify it to roll 10 pairs of dice instead of 100 by changing the `aa*` in the 5th line to `a` (that is, `a` followed by two spaces).

The random dice rolls are done by this bit:

```
1\v/4
2xxx5
3/^\6

```

The `x`s change the fish's direction randomly. Assuming that's implemented with equal probabilities, it's clear that the die roll result is a uniform distribution by symmetry.

Once the fish has rolled 100 pairs of dice, it counts how many times the sum was *n* with this bit (unwrapped for clarity, and starting in the top left):

```
v       /&1+&\
>:@@:@=?/ :?!\}
^   +1oa&0n&}<

```

We keep *n* at the front of the stack, and use the register to count the number of times *n* appears.
> 0 votes

# Answer
# Perl 5, 64 bytes

```
map$s{2+int(rand 6)+int rand 6}++,1..100;say"$_ $s{$_}"for 2..12

```

Try it online!

Output format:

`<sum> <# rolls>`

For sums with zero rolls, the rolls column is blank.
> 0 votes

# Answer
# PHP, 65 bytes

```
while($i++<100)${rand(1,6)+rand(1,6)}++;for(;++$k<13;)echo+$$k,_;

```

prints a leading `0_` and then the occurences of 2 to 12, followed by an underscore each.
Run with `-nr` or try it online.
> 0 votes

# Answer
# K (oK), ~~24~~ 22 bytes

**Solution:**

```
+/(!11)=/:+/(2#100)?'6

```

Try it online!

**Explanation:**

`k` 'port' of my `q` solution. Evaluation occurs right-to-left, hence brackets around the til (`!`)

```
+/(!11)=/:+/(2#100)?'6 / the solution
            (2#100)    / the list (100;100)
                   ?'6 / take 6 from each left/each right (roll the dice twice)
           +/          / sum rolls together
  (!11)                / til, performs range of 0..n-1, thus 0..10
       =/:             / equals each right (bucket the sum of the rolls)
+/                     / sum up to get counts per result

```

**Edits:**

* -2 bytes switching the each-left for an each-both, and the each-left + flip for each-right
> 0 votes

# Answer
# Pyth, 21 bytes

```
V100aY,O6O6)VTlfqsTNY

```

Outputs each step in the creation of the rolls, then outputs frequency of each sum 0 - 10 on a separate line.

---

```
V100aY,O6O6)VTlfqsTNY Full program, no input, outputs to stdout
V100                  For N from 0 to 100
    a ,O6O6           Append a pair of random ints below 6
     Y                To a list Y, initialized to the empty list
           )          Then
            VT        For N from 0 to 10
              f     Y Print Y filtered to only include pairs
                q  N  For which N is equal to
                 sT   The sum of the pair

```
> 0 votes

# Answer
# Java (OpenJDK 8), 95 bytes

```
a->{int r[]=new int[11],i=0,d=0;for(;i++<200;)r[d+=Math.random()*6]+=i%2<1?1-(d=0):0;return r;}

```

Try it online!

## Explanations

```
a->{
  int r[] = new int[11],     // Rolls or result
      i   = 0,               // Iteration
      d   = 0;               // Dice accumulator
  for (;i++<200;)
    r[d+=Math.random()*6] += // Accumulate a new die and start an addition
     i % 2 < 1               // Accumulate up to two dice
       ? 1 - (d = 0)         // If we're at 2 dice, reset the accumulator and add 1
       : 0;                  // If we only have one die, add 0
  return r;
}

```
> 0 votes

# Answer
# Vyxal, 9 bytes

```
₁ƛ6℅6℅+;Ċ

```

Try it Online!

Returns a list of `[roll, count]`. If a roll total didn't happen, then it isn't included in the list.

## Explained

```
₁ƛ6℅6℅+;Ċ
₁ƛ        # for each item in range(1, 100 + 1):
  6℅6℅    #   push a random number from range(1, 6 + 1) and then another random number from that range
      +   #   and add them together
       ;  # end map - this leaves 100 random dice rolls in a list.
        Ċ # get the count of each item

```
> 0 votes

# Answer
# Burlesque, 18 bytes

```
1J6rn200.+2CO)++f:

```

Try it online!

```
1J6rn # Infinite random d6 rolls
200.+ # Take first 200
2CO   # Chunks of 2
)++   # MapSum
f:    # Frequency list

```
> 0 votes

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


title: Graphical Hello World

text:
# Question
Title: Graphical Hello World
In this challenge, you will create the shortest graphical program that displays exactly "**Hello, world!**"

You will need **no input**.

You might be asking yourself, "what does he mean by graphical?" Well, by graphical, I mean **not writing to stdout.** For example, look at my ES6 answer, which makes an alert box pop up rather than the traditional hello world where you do write to stdout:

```
alert('Hello, world!')

```

That doesn't write to stdout. Which is what I am challenging you to do today.

### Formatting

This is an example post in markdown for the ES6 snippet I posted above:

```
# JavaScript (ES6), 22 bytes

    alert('Hello, world!')

```

View an example post.

# Answer
> 7 votes
# Minecraft Command Blocks, 47 bytes

```
summon cow ~ ~ ~ {CustomName:'"Hello, world!"'}

```

Spawns a cow with the name `Hello, world!`

# Answer
> 0 votes
# JavaScript (ES6), 22 bytes

```
alert('Hello, world!')

```

This is an example for my question.

# Answer
> 0 votes
# PHP (8.1), 20 bytes

```
echo'Hello, world!';

```

---
Tags: graphical-output, hello-world
---


title: Shuffle an array, a little bit

text:
# Question
Title: Shuffle an array, a little bit
Given some input array `a = [a1, a2, ..., an]` and a positive integer `k`, shuffle the input array `a` such that no entry is farther than `k` from its initial position.

### Example

Given the array `[1, 2, 3, 4, 5, 6]` and `k = 1`, this means the entry `3` can be at following positions:

```
[*, 3, *, *, * ,*]
[*, *, 3, *, *, *]   (original position)
[*, *, *, 3, *, *]

```

### Details

* Uniform randomness over all permissible permutations is *not* required, but
* You can assume the input array is limited to the range `[1, n]` (or `[0, n-1]`, where `n` is the length).
* all permissible permutations must have a nonzero probability of occurring.
* Instead of shuffling an input array, you can also just take `k` and the length of the array `n` (or `n+-1` alternatively) as an input, and output a permutation in a suitable encoding (i.e as a list of indices etc). For this you can use 0 or 1 based indexing.
* Instead of `k` you can also take `k-1` or `k+1` as an input if it is more suitable.
* You can assume that `0 < k < [length of array]`.
* Alternatively to sampling one random permutation you can also output *all* permissible permutations.

# Answer
> 6 votes
# , 47 bytes

```
\(n,k){while(any(abs((a=sample(n))-1:n)>k))0
a}
```

Attempt This Online!

Takes the length `n` and the maximum distance allowed `k` and returns a permutation on `1:n` by rejection sampling.

Footer computes 10000 iterations of `f(6,1)` and tabulates the results for each index to give a rough distribution.

# Answer
> 4 votes
# 05AB1E, ~~9~~ ~~7~~ 6 bytes

```
œʒāα@P

```

1-based input-list, and outputs all possible permutations. Outputting a random one would be 2 bytes longer by adding a trailing .

Try it online.

**Explanation:**

```
œ       # Push a list of permutations of the first (implicit) input-list
 ʒ      # Filter this list of permutations by:
  ā     #  Push a list in the range [1,length] (without popping)
   α    #  Get the absolute difference between the values at the same positions
    @   #  Check for each whether the second (implicit) input is >= the value
     P  #  Product to check if all are truthy
        # (after which the filtered list is output implicitly)

```

# Answer
> 2 votes
# JavaScript (ES6),  ~~89~~  87 bytes

Expects `(array)(k)`.

```
a=>g=k=>a.every((v,i)=>!(1/b[j=i+Math.random()*(k-~k)-k|0])/a[j]&&[b[j]=v],b=[])?b:g(k)

```

Try it online!

### Commented

```
a =>                   // a[] = input array
g = k =>               // k = max. distance
a.every((v, i) =>      // for each value v at position i in a[]:
  !(                   //   abort if:
    1 / b[             //     - b[j] is already defined
      j = i +          //       where j is randomly chosen in
      Math.random() *  //       [i-k .. i+k]
      (k - ~k) - k | 0 //
    ]                  //   or:
  ) / a[j] &&          //     - a[j] is not defined
  [                    //   otherwise:
    b[j] = v           //     set b[j] to v and keep going
  ],                   //
  b = []               //   start with b[] = empty array
) ?                    // end of every; if sucessful:
  b                    //   return b[]
:                      // else:
  g(k)                 //   try again

```

# Answer
> 2 votes
# Ruby, ~~72~~ ~~64~~ ~~63~~ 62 bytes

Lambda that accepts length of array minus one `n-1`, and minimum illegal distance for an element to be moved `k+1`.

```
->n,k{a=*0..n;a.shuffle!.all?{(a.index(_1)-_1).abs<k}||redo;a}

```

Attempt This Online!

*-8 bytes thanks to @Dingus*

# Answer
> 2 votes
# Jelly, 9 bytes

```
Œ!ạJ{Ṁ<ʋƇ

```

A dyadic Link that accepts the length, `n`, on the left and the minimum illegal distance, `k+1`, on the right and yields a list of all permutations as 1-indexed indices.

**Try it online!**

### How?

```
Œ!ạJ{Ṁ<ʋƇ - Link: n; k+1
Œ!        - all permutations of [1..n]
        Ƈ - filter keep those for which:
       ʋ  -   last four links as a dyad - f(P, k+1):
    {     -     use k+1 with:
   J      -       range of length -> I = [1..k+1]
  ạ       -     P absolute difference I (vectorises) -> distances
     Ṁ    -     maximum
      <   -     is less than k+1?

```

# Answer
> 2 votes
# Python 3, <sup>~~104~~ ~~94~~</sup> 92 bytes

## Code

```
lambda l,k:[p for p in permutations(l)if all(-k<p[i]-i<k for i in l)]
from itertools import*

```

Takes as input:

* The list `[0, 1, ..., n-2, n-1]` where `n` is the length of the list
* `k+1`

Outputs all possible permutations.

Try it online!

## Explanation

* Uses `itertools.permutations` to get all permutations of the list.
* Only adds each one to the output list if `-k<p[i]-i<k` is `True` for every index `i` and value `p[i]` in the permutation.

# Answer
> 2 votes
# Vyxal `r`, ~~17~~ ~~13~~ 11 bytes

```
ʁṖ'→ƛ←ḟε;G≥

```

Try it Online!

*-4 bytes thanks to emanresu A*

*-1 byte thanks to Aaroneous Miller*

# Answer
> 1 votes
# Python3, 178 bytes:

```
lambda a,k:f([*enumerate(a)],k,a,0,[])
def f(a,k,l,j,c):
 if len(a)==j:yield c;return
 for x,y in a:
  if abs(x-j)<=k and(C:=list.count)(l,y)>C(c,y):yield from f(a,k,l,j+1,c+[y])

```

Try it online!

# Answer
> 1 votes
# Charcoal, 29 bytes

```
ＮθＦＮ⊞υ⁰Ｗ⊙υ∨⊖№υλ‹θ↔⁻κλＵＭυ‽ＬυＩυ

```

Try it online! Link is to verbose version of code. Outputs a random permissible permutation. Explanation:

```
Ｎθ

```

Input `k`.

```
ＦＮ⊞υ⁰

```

Input `n` and create an illegal permutation (unless `n=1`, in which case there is only one permutation).

```
Ｗ⊙υ∨⊖№υλ‹θ↔⁻κλ

```

Repeat until the permutation is both legal and permissible...

```
ＵＭυ‽Ｌυ

```

... randomise the permutation.

```
Ｉυ

```

Output the permissible permutation.

# Answer
> 1 votes
# Python, 106 bytes

```
from random import*
f=lambda L,k:(shuffle(Z:=L[::])or all([k>abs(s-n)for n,s in zip(L,Z)])and Z or f(L,k))
```

Attempt This Online!

Returns a new list. Requires the input list to be in the format `[1,2,...,n-1,n]` where `n` is the length of the list. Taking `k+1` as an input

# Answer
> 1 votes
# Factor \+ `math.combinatorics math.unicode`, 66 bytes

```
[ iota dup [ v- vabs [ >= ] with ∀ ] 2with filter-permutations ]

```

Try it online!

Takes \\$k\\$ and a length \\$l\\$ and outputs all zero-indexed sets of indices of length \\$l\\$ that satisfy the distance constraint given by \\$k\\$.

# Answer
> 1 votes
# Haskell (Lambdabot), 72 bytes

Operator `#` that accepts length of array minus one `n-1`, and minimum illegal distance for an element to be moved `k+1`.

```
n#k=[x|x<-permutations[0..n],all(\y->abs(fromJust(elemIndex y x)-y)<k)x]
```

Attempt This Online!

# Answer
> 1 votes
# Vyxal, 8 bytes

```
Ṗ'ż-ȧ⁰≤A

```

Try it Online!

Port of 05AB1E.

## How?

```
Ṗ'ż-ȧ⁰≤A
Ṗ        # All permutations of the (implicit) first input
 '       # Filter by:
  ż      #  Length range [1, length]
   -ȧ    #  Absolute differences of values in the same positions
     ⁰≤  #  For each, is it less than or equal to the second input?
       A #  Are they all truth?

```

\`\`\`

---
Tags: code-golf, array, random, permutations
---


title: King of the Hill: Greed Control

text:
# Question
Title: King of the Hill: Greed Control
# King of the Hill: Greed Control

## What is Greed Control

Greed control is a **multiplayer** `round-based` game in which in every round, a player bet a number inside a specific range, say 1~100. Say 2 people betted 100, then they'd both get 100/2 which is `50` points in the game. **Basically, the players that choose the same number split the scores evenly (no rounding) and the total of their net score gain is the number they chose**.

After a set number of rounds, players compare scores. The highest score generally wins the game overall.

## Your challenge

Build a bot in `python`, specifically, `python 3` , that when given input, discussed in the section `input`, they give the number as an integer they bet as output. It must be a`function`.

## Input

`information, points, round_number, sum_of_all, user_num`. `information` is a dictionary with integer keys in which each key's value is the number of bots that chose that key's number **last round**. `points` is the list of integers you can choose from. `round_number` is the round number. `sum_of_all` is like `information`, except it is the summation of **all rounds**. `user_num` is the number of players playing.

## We guarantee that

We guarantee that `points` stay the same every round and is strictly increasing, all integers. However, it may not be consecutive.

## Controller function

```

from random import choice

def random_better(information, points, round_number, sum_of_all, user_num):
    return choice(points)

def greedy_better(information, points, round_number, sum_of_all, user_num):
    return points[-1]

def calculator(information, points, round_number, sum_of_all, user_num):
    return sorted(points, key=lambda x:x/(information[x]+0.000000000001))[0]

def smarty(information, points, round_number, sum_of_all, user_num):
    return sorted(points, key=lambda x:x/(information[x]+0.000000000001))[choice(range(1,40))]

users = [random_better, greedy_better, calculator, smarty] * 10

user_names = [user.__name__.replace('_',' ') for user in users]
rounds = 1000
points = sorted(list(range(1,101)))
user_num = len(users)
bots = [user for user in users]
scores = [0.0 for user in users]
information = {i:0 for i in points}
sum_of_all = {i:0 for i in points}
print('\n'*100)

for round_number in range(rounds):
    choices = [bot(information, points, round_number, sum_of_all, user_num) for bot in bots]
    information = {score:choices.count(score) for score in points}
    scores = [scores[index] + choices[index]/information[choices[index]] for index in range(user_num)]

    print(f'\n\n\nRound #{round_number+1} Reports: ')

    print('\nBots Report: ')
    print('\n'.join([f'{user_names[index].ljust(20)} '
                     f'chose {choices[index]} '
                     f'and got {choices[index]/information[choices[index]]} additional points, '
                     f'making it now have {scores[index]} points!!! ' for index in range(user_num)]))

    print('\nDistribution Report: ')
    print('\n'.join([f'The number of bots who chose {num} is: {information[num]}!!! ' for num in points]))

    print('\nLeaderboard Report: ')
    sorted_list = sorted(range(user_num), key=lambda x: -scores[x])

    print(f'\n{user_names[sorted_list[0]].ljust(20)} with {scores[sorted_list[0]]} points, '
          f'\n{user_names[sorted_list[1]].ljust(20)} with {scores[sorted_list[1]]} points, and'
          f'\n{user_names[sorted_list[2]].ljust(20)} with {scores[sorted_list[2]]} points!!! ')

    sum_of_all = {i:sum_of_all[i]+information[i] for i in points}

print('\n\n\nFinal Report Card: \n')
print('\n'.join([f'{user_names[sorted_list[index]].ljust(20)}: '
                 f'{scores[sorted_list[index]]} points. ' for index in range(user_num)]))

```

The first part is imports. You may only depend on default python built-ins or the python standard library. Or if you manage to hide it and I out of coincidence have the package...

The second part is your functions. Naming your function `bot_name_with_underscores` is encouraged.

The third part are game parameters. The number of rounds, the accessible outputs, etc.

The fourth part is **running the program**!!!

An example output is as follows:

```

Round #1 Reports:

Bots Report:
random better        chose 3 and got 1.5 additional points, making it now have 1.5 points!!!
greedy better        chose 10 and got 10.0 additional points, making it now have 10.0 points!!!
calculator           chose 1 and got 1.0 additional points, making it now have 1.0 points!!!
smarty               chose 3 and got 1.5 additional points, making it now have 1.5 points!!!

Distribution Report:
The number of bots who chose 1 is: 1!!!
The number of bots who chose 2 is: 0!!!
The number of bots who chose 3 is: 2!!!
The number of bots who chose 4 is: 0!!!
The number of bots who chose 5 is: 0!!!
The number of bots who chose 6 is: 0!!!
The number of bots who chose 7 is: 0!!!
The number of bots who chose 8 is: 0!!!
The number of bots who chose 9 is: 0!!!
The number of bots who chose 10 is: 1!!!

Leaderboard Report:

greedy better        with 10.0 points,
random better        with 1.5 points, and
smarty               with 1.5 points!!!

Round #2 Reports:

Bots Report:
random better        chose 7 and got 7.0 additional points, making it now have 8.5 points!!!
greedy better        chose 10 and got 5.0 additional points, making it now have 15.0 points!!!
calculator           chose 1 and got 1.0 additional points, making it now have 2.0 points!!!
smarty               chose 10 and got 5.0 additional points, making it now have 6.5 points!!!

Distribution Report:
The number of bots who chose 1 is: 1!!!
The number of bots who chose 2 is: 0!!!
The number of bots who chose 3 is: 0!!!
The number of bots who chose 4 is: 0!!!
The number of bots who chose 5 is: 0!!!
The number of bots who chose 6 is: 0!!!
The number of bots who chose 7 is: 1!!!
The number of bots who chose 8 is: 0!!!
The number of bots who chose 9 is: 0!!!
The number of bots who chose 10 is: 2!!!

Leaderboard Report:

greedy better        with 15.0 points,
random better        with 8.5 points, and
smarty               with 6.5 points!!!

Round #3 Reports:

Bots Report:
random better        chose 4 and got 4.0 additional points, making it now have 12.5 points!!!
greedy better        chose 10 and got 10.0 additional points, making it now have 25.0 points!!!
calculator           chose 1 and got 1.0 additional points, making it now have 3.0 points!!!
smarty               chose 2 and got 2.0 additional points, making it now have 8.5 points!!!

Distribution Report:
The number of bots who chose 1 is: 1!!!
The number of bots who chose 2 is: 1!!!
The number of bots who chose 3 is: 0!!!
The number of bots who chose 4 is: 1!!!
The number of bots who chose 5 is: 0!!!
The number of bots who chose 6 is: 0!!!
The number of bots who chose 7 is: 0!!!
The number of bots who chose 8 is: 0!!!
The number of bots who chose 9 is: 0!!!
The number of bots who chose 10 is: 1!!!

Leaderboard Report:

greedy better        with 25.0 points,
random better        with 12.5 points, and
smarty               with 8.5 points!!!

Round #4 Reports:

Bots Report:
random better        chose 6 and got 6.0 additional points, making it now have 18.5 points!!!
greedy better        chose 10 and got 10.0 additional points, making it now have 35.0 points!!!
calculator           chose 1 and got 1.0 additional points, making it now have 4.0 points!!!
smarty               chose 2 and got 2.0 additional points, making it now have 10.5 points!!!

Distribution Report:
The number of bots who chose 1 is: 1!!!
The number of bots who chose 2 is: 1!!!
The number of bots who chose 3 is: 0!!!
The number of bots who chose 4 is: 0!!!
The number of bots who chose 5 is: 0!!!
The number of bots who chose 6 is: 1!!!
The number of bots who chose 7 is: 0!!!
The number of bots who chose 8 is: 0!!!
The number of bots who chose 9 is: 0!!!
The number of bots who chose 10 is: 1!!!

Leaderboard Report:

greedy better        with 35.0 points,
random better        with 18.5 points, and
smarty               with 10.5 points!!!

Round #5 Reports:

Bots Report:
random better        chose 2 and got 2.0 additional points, making it now have 20.5 points!!!
greedy better        chose 10 and got 10.0 additional points, making it now have 45.0 points!!!
calculator           chose 1 and got 1.0 additional points, making it now have 5.0 points!!!
smarty               chose 6 and got 6.0 additional points, making it now have 16.5 points!!!

Distribution Report:
The number of bots who chose 1 is: 1!!!
The number of bots who chose 2 is: 1!!!
The number of bots who chose 3 is: 0!!!
The number of bots who chose 4 is: 0!!!
The number of bots who chose 5 is: 0!!!
The number of bots who chose 6 is: 1!!!
The number of bots who chose 7 is: 0!!!
The number of bots who chose 8 is: 0!!!
The number of bots who chose 9 is: 0!!!
The number of bots who chose 10 is: 1!!!

Leaderboard Report:

greedy better        with 45.0 points,
random better        with 20.5 points, and
smarty               with 16.5 points!!!

Round #6 Reports:

Bots Report:
random better        chose 3 and got 3.0 additional points, making it now have 23.5 points!!!
greedy better        chose 10 and got 10.0 additional points, making it now have 55.0 points!!!
calculator           chose 1 and got 1.0 additional points, making it now have 6.0 points!!!
smarty               chose 2 and got 2.0 additional points, making it now have 18.5 points!!!

Distribution Report:
The number of bots who chose 1 is: 1!!!
The number of bots who chose 2 is: 1!!!
The number of bots who chose 3 is: 1!!!
The number of bots who chose 4 is: 0!!!
The number of bots who chose 5 is: 0!!!
The number of bots who chose 6 is: 0!!!
The number of bots who chose 7 is: 0!!!
The number of bots who chose 8 is: 0!!!
The number of bots who chose 9 is: 0!!!
The number of bots who chose 10 is: 1!!!

Leaderboard Report:

greedy better        with 55.0 points,
random better        with 23.5 points, and
smarty               with 18.5 points!!!

Round #7 Reports:

Bots Report:
random better        chose 8 and got 8.0 additional points, making it now have 31.5 points!!!
greedy better        chose 10 and got 10.0 additional points, making it now have 65.0 points!!!
calculator           chose 1 and got 1.0 additional points, making it now have 7.0 points!!!
smarty               chose 3 and got 3.0 additional points, making it now have 21.5 points!!!

Distribution Report:
The number of bots who chose 1 is: 1!!!
The number of bots who chose 2 is: 0!!!
The number of bots who chose 3 is: 1!!!
The number of bots who chose 4 is: 0!!!
The number of bots who chose 5 is: 0!!!
The number of bots who chose 6 is: 0!!!
The number of bots who chose 7 is: 0!!!
The number of bots who chose 8 is: 1!!!
The number of bots who chose 9 is: 0!!!
The number of bots who chose 10 is: 1!!!

Leaderboard Report:

greedy better        with 65.0 points,
random better        with 31.5 points, and
smarty               with 21.5 points!!!

Round #8 Reports:

Bots Report:
random better        chose 1 and got 0.5 additional points, making it now have 32.0 points!!!
greedy better        chose 10 and got 5.0 additional points, making it now have 70.0 points!!!
calculator           chose 1 and got 0.5 additional points, making it now have 7.5 points!!!
smarty               chose 10 and got 5.0 additional points, making it now have 26.5 points!!!

Distribution Report:
The number of bots who chose 1 is: 2!!!
The number of bots who chose 2 is: 0!!!
The number of bots who chose 3 is: 0!!!
The number of bots who chose 4 is: 0!!!
The number of bots who chose 5 is: 0!!!
The number of bots who chose 6 is: 0!!!
The number of bots who chose 7 is: 0!!!
The number of bots who chose 8 is: 0!!!
The number of bots who chose 9 is: 0!!!
The number of bots who chose 10 is: 2!!!

Leaderboard Report:

greedy better        with 70.0 points,
random better        with 32.0 points, and
smarty               with 26.5 points!!!

Round #9 Reports:

Bots Report:
random better        chose 3 and got 3.0 additional points, making it now have 35.0 points!!!
greedy better        chose 10 and got 5.0 additional points, making it now have 75.0 points!!!
calculator           chose 1 and got 1.0 additional points, making it now have 8.5 points!!!
smarty               chose 10 and got 5.0 additional points, making it now have 31.5 points!!!

Distribution Report:
The number of bots who chose 1 is: 1!!!
The number of bots who chose 2 is: 0!!!
The number of bots who chose 3 is: 1!!!
The number of bots who chose 4 is: 0!!!
The number of bots who chose 5 is: 0!!!
The number of bots who chose 6 is: 0!!!
The number of bots who chose 7 is: 0!!!
The number of bots who chose 8 is: 0!!!
The number of bots who chose 9 is: 0!!!
The number of bots who chose 10 is: 2!!!

Leaderboard Report:

greedy better        with 75.0 points,
random better        with 35.0 points, and
smarty               with 31.5 points!!!

Round #10 Reports:

Bots Report:
random better        chose 2 and got 2.0 additional points, making it now have 37.0 points!!!
greedy better        chose 10 and got 5.0 additional points, making it now have 80.0 points!!!
calculator           chose 1 and got 1.0 additional points, making it now have 9.5 points!!!
smarty               chose 10 and got 5.0 additional points, making it now have 36.5 points!!!

Distribution Report:
The number of bots who chose 1 is: 1!!!
The number of bots who chose 2 is: 1!!!
The number of bots who chose 3 is: 0!!!
The number of bots who chose 4 is: 0!!!
The number of bots who chose 5 is: 0!!!
The number of bots who chose 6 is: 0!!!
The number of bots who chose 7 is: 0!!!
The number of bots who chose 8 is: 0!!!
The number of bots who chose 9 is: 0!!!
The number of bots who chose 10 is: 2!!!

Leaderboard Report:

greedy better        with 80.0 points,
random better        with 37.0 points, and
smarty               with 36.5 points!!!

Final Report Card:

greedy better       : 80.0 points.
random better       : 37.0 points.
smarty              : 36.5 points.
calculator          : 9.5 points.

```

## If any bot runs into an error,

it fails. So **CHECK IT**!!! Make it **FOOLPROOF**!!!

## Winner

This is .

# May the points be EVER in your favor!

```
Current information:

Final Report Card:

inspector gadget    : 97190.0 points.
greedy better       : 49450.0 points.
crab                : 49450.0 points.
random better       : 48090.0 points.
smarty              : 21715.5 points.
calculator          :   993.5 points.

```

TO REPEAT, THIS IS NOT A DUPE OF Smallest unique number KoTH.

# Answer
> 4 votes
## Crab

```
def crab(a,b,c,d,e):
     return 100

```

If Crab can't get 100 points, nobody can.

Might actually be competitive, as simulationist bots will pick a lower number to maximize points and not share, and other bots probably won't go as riskily to pick 100 every time.

# Answer
> 3 votes
# Inspector Gadget

Assume most players who vote high will give the same answer given the same inputs. Run every bot and pick the highest unpicked number, while also telling later copies of ourselves to not step on our toes by giving them an upper bound, via the shared information dictionary.

```
def inspector_gadget(k,i,tt,e,ns):
    currentpick = 100
    try:
        if "inspector" in k:
            currentpick=k["inspector"]
        currentpick -= 1
        import inspect
        from copy import copy
        users = inspect.stack()[1][0].f_globals["users"]
        picks = []
        for u in users:
            if u == inspector_gadget: continue
            try:
                picks.append(u(copy(k),copy(i),tt,e,copy(ns)))
            except Exception:
                pass
        while currentpick in picks:
         currentpick -= 1
        k["inspector"] = currentpick
        return currentpick
    except Exception as e:
        return currentpick-1

```

---
Tags: king-of-the-hill, python
---


title: Safety in numbers

text:
# Question
Title: Safety in numbers
Write a program to determine if a periodic sequence of positive integers has the property that, for every integer `n` occurring in the sequence, there are never more than `n` other integers between two consecutive occurrences of `n`.

For example, `2, 3, 5, 2, 3, 6, 2, 3, 5, 2, 3, 6, ...` does have this property: every pair of consecutive occurrences of `2` have at most two integers between them (such as `2, 3, 5, 2` and `2, 3, 6, 2`; every pair of consecutive occurrences of `3` have at most three integers between them; and the same for `5` and `6`.

However, `2, 3, 5, 2, 3, 4, 2, 3, 5, 2, 3, 4, ...` does not have this property: two consecutive occurrences of `4`, namely `4, 2, 3, 5, 2, 3, 4`, have more than four integers between them.

**Input**: a reasonable representation of a periodic sequence of positive integers. For example, a finite list such as `{2, 3, 5, 2, 3, 6}` can represent the first infinite sequence `2, 3, 5, 2, 3, 6, 2, 3, 5, 2, 3, 6, ...` above. (For that matter, the problem could be stated for finite lists that wrap around instead of for infinite periodic lists.)

**Output**: a truthy/falsy value.

Truthy examples:

```
{1}
{8, 9}
{2, 3, 4}
{5, 5, 3, 3, 6}
{2, 3, 5, 2, 3, 6}
{6, 7, 3, 5, 3, 7}
{9, 4, 6, 7, 4, 5}
{1, 1, 1, 1, 1, 100, 1}
{1, 9, 1, 8, 1, 7, 1, 11}

```

Falsy examples:

```
{1, 2, 3}
{2, 3, 9, 5}
{3, 5, 4, 4, 6}
{2, 3, 5, 2, 3, 4}
{3, 5, 7, 5, 9, 3, 7}
{5, 6, 7, 8, 9, 10, 11}
{1, 9, 1, 8, 1, 6, 1, 11}

```

This is , so the shortest code wins. Answers in all languages are encouraged.

# Answer
## Haskell, ~~60~~ ~~57~~ ~~56~~ 55 bytes

```
f(a:b)=b==[]||length(fst$span(/=a)b)<=a&&f b
g x=f$x++x

```

Assumes that the input list contains at least one element.

Usage example: `g [1]` -\> `True`. Try it online!

Let `a` be the head of the list and `b` the tail. The result is `True` if `b` is empty or the number of elements at the beginning of `b` that are not equal to `a` is not greater than `a` and the recursive call of `f b` is also `True`, else `False`. Start with twice the input list.

Edit: @Leo saved 3 bytes. Thanks!

Edit 2: @Laikoni saved 1 byte. Thanks!
> 7 votes

# Answer
# Python, ~~57~~ 56 bytes

-1 byte thanks to Dennis (replace `i+1:i+v+2` with `i:i-~v` with an `i` offset of 1 from `enumerate`)

```
lambda a:all(v in(a+a)[i:i-~v]for i,v in enumerate(a,1))

```

**Try it online!**

Unnamed function taking a list, `a`, and testing the condition that each value, `v`, appears `in` the relevant slice to its right in a concatenation of `a` with itself, `(a+a)[i:i-~v]`, where the 1-based index of `v` in `a`, `i`, is provided by `enumerate(a,1)`.
> 7 votes

# Answer
# JavaScript (ES6), ~~67 65 55 54 51~~ 49 bytes

*Saved 3B thanks to @ETHproductions and 2B thanks to @Arnauld*

```
a=>!a.some((b,c)=>a.concat(a).indexOf(b,++c)>b+c)

```

# Explanation

This defines a function that takes an array `a` as input. Then, the `.some` method iterates over that array, executing another function for every element.

This inner function takes two arguments, `b` and `c`, the current value and its index. The function finds the index of the current value, starting from index `c + 1`. Then it checks if this index is greater than the current value plus the current index (the difference between two occurrences of the same value is greater than `b`). Note that this returns the exact opposite of what we want.

If one of these return values is `true`, the `.some` function returns `true` as well. If none of the checks return `true`, the `.some` function returns `false`. Once again the opposite of the value we want to return, so this result is negated and then returned.

# Test it

Try all test cases here:

```
let f=
a=>!a.some((b,c)=>a.concat(a).indexOf(b,++c)>b+c)

let truthy = [[1], [8, 9], [2, 3, 4], [5, 5, 3, 3, 6], [2, 3, 5, 2, 3, 6], [6, 7, 3, 5, 3, 7], [9, 4, 6, 7, 4, 5], [1, 1, 1, 1, 1, 100, 1], [1, 9, 1, 8, 1, 7, 1, 11]];
let falsy  = [[1, 2, 3], [2, 3, 9, 5], [3, 5, 4, 4, 6], [2, 3, 5, 2, 3, 4], [3, 5, 7, 5, 9, 3, 7], [5, 6, 7, 8, 9, 10, 11], [1, 9, 1, 8, 1, 6, 1, 11]];

console.log("Truthy test cases:");
for (let test of truthy) {
    console.log(`${test}: ${f(test)}`);
}

console.log("Falsy test cases:");
for (let test of falsy) {
    console.log(`${test}: ${f(test)}`);
}
```
> 6 votes

# Answer
# Jelly, 11 bytes

```
ṣZL
;çÐ€<‘P

```

Try it online!

### How it works

```
;çÐ€<‘P  Main link. Argument: A (array)

;        Concatenate A with itself.
 çD€     For each n in A, call the helper with left arg. A + A and right arg. n.
     ‘   Increment all integers in A.
    <    Perform element-wise comparison of the results to both sides.
      P  Take the product of the resulting Booleans.

ṣZL      Helper link. Left argument: A. Right argument: n

ṣ        Split A at all occurrences of n.
 Z       Zip to transpose rows and columns.
  L      Length; yield the number of rows, which is equal to the number of columns
         of the input to Z.

```
> 4 votes

# Answer
# Jelly, 8 bytes

```
ṙJḣ"‘Œpċ

```

Insipred by @JonathanAllan's Python answer.

Try it online!

### How it works

```
ṙJḣ"‘Œpċ  Main link. Argument: A (array)

 J        Yield the indicies of A, i.e., [1, ..., len(A)].
ṙ         Rotate; yield A, rotated 1, ..., and len(A) units rotated to the left.
    ‘     Increment; add 1 to all elements of A.
  ḣ"      Head zipwith; truncate the n-th rotation to length A[n]+1.
     Œp   Take the Cartesian product of all resulting truncated rotations.
       ċ  Count the number of times A appears in the result.

```
> 4 votes

# Answer
# SWI-Prolog, 83 bytes

```
a(L,[H|R]):-nth0(X,R,H),H>=X,a(L,R);length(R,N),nth0(X,L,H),H>=N+X,a(L,R).
a(_,[]).

```

The list should be entered twice:

```
a([1,2,3],[1,2,3]).

```

If this is not considered acceptable, you may add the predicate

```
a(L):-a(L,L).

```

which adds an extra 14 bytes.

Try it online

nb: you may test for different false cases at once by separating your queries with ';' (or) and test for different true cases by separating with ',' (and)

ie, using the OP examples :

```
a([1],[1]),
a([8, 9],[8, 9]),
a([2, 3, 4],[2, 3, 4]),
a([5, 5, 3, 3, 6],[5, 5, 3, 3, 6]),
a([2, 3, 5, 2, 3, 6],[2, 3, 5, 2, 3, 6]),
a([6, 7, 3, 5, 3, 7],[6, 7, 3, 5, 3, 7]),
a([9, 4, 6, 7, 4, 5],[9, 4, 6, 7, 4, 5]),
a([1, 1, 1, 1, 1, 100, 1],[1, 1, 1, 1, 1, 100, 1]),
a([1, 9, 1, 8, 1, 7, 1, 11],[1, 9, 1, 8, 1, 7, 1, 11]).

```

and

```
a([1, 2, 3],[1, 2, 3]);
a([2, 3, 9, 5],[2, 3, 9, 5]);
a([3, 5, 4, 4, 6],[3, 5, 4, 4, 6]);
a([2, 3, 5, 2, 3, 4],[2, 3, 5, 2, 3, 4]);
a([3, 5, 7, 5, 9, 3, 7],[3, 5, 7, 5, 9, 3, 7]);
a([5, 6, 7, 8, 9, 10, 11],[5, 6, 7, 8, 9, 10, 11]);
a([1, 9, 1, 8, 1, 6, 1, 11],[1, 9, 1, 8, 1, 6, 1, 11]).

```
> 2 votes

# Answer
# PHP, 52 bytes

```
for(;$n=$argv[++$i];$$n=$i)!$$n|$i-$$n<$n+2?:die(1);

```

takes sequence from command line arguments; exits with code `1` for falsy, `0` for truthy.
Run with `-nr`.

* loop `$n` through arguments:
    + if there was no previous occurence or it was recent enough
    then do nothing, else exit with code `1`
    + remember previous occurence in `$$n` (variable variables)
* exit with code `0` (implicit)
> 2 votes

# Answer
## Retina, 50 bytes

```
$
,$`
M!&`\b(1+),.*?\b\1\b
+%`(^1*)1,1+
$1
M`1,
^0

```

Input as a list of comma-separate unary numbers.

Try it online!

### Explanation

```
$
,$`

```

Duplicate the input so we can check steps that wrap around the end.

```
M!&`\b(1+),.*?\b\1\b

```

Match and return each (shortest) section between two identical values, e.g. `11,111,1,11`.

```
+%`(^1*)1,1+
$1

```

Repeatedly remove a digit from the first number, together with an entire number after it. If the gap is small enough this will completely remove the first number. Otherwise, at least one digit will remain.

```
M`1,

```

Count how often `1,` appears in all the lines. If it appears anywhere, one of the steps was too wide.

```
^0

```

Try to match a number starting with `0` (i.e. only `0` itself). This is effectively a logical negation of the output.
> 2 votes

# Answer
## JavaScript (ES6), 47 bytes

```
a=>![...a,...a].some((n,i)=>a[-n]-(a[-n]=i)<~n)

```

### How it works

We re-use the input array `a` to store the position of the last encountered occurrence of each integer in `a`. We use the key `-n` to store this position so that it does not interfere with the original indices of `a`.

When `a[-n]` exists, the actual test occurs. When `a[-n]` doesn't exist, the expression `a[-n] - (a[-n] = i)` equals `undefined - i == NaN` and the comparison with `~n` is always falsy, which is the expected result.

### Test cases

```
f=
a=>![...a,...a].some((n,i)=>a[-n]-(a[-n]=i)<~n)

console.log('Truthy cases:');
console.log(f([1]));
console.log(f([8, 9]));
console.log(f([2, 3, 4]));
console.log(f([5, 5, 3, 3, 6]));
console.log(f([2, 3, 5, 2, 3, 6]));
console.log(f([6, 7, 3, 5, 3, 7]));
console.log(f([9, 4, 6, 7, 4, 5]));
console.log(f([1, 1, 1, 1, 1, 100, 1]));
console.log(f([1, 9, 1, 8, 1, 7, 1, 11]));

console.log('Falsy cases:');
console.log(f([1, 2, 3]));
console.log(f([2, 3, 9, 5]));
console.log(f([3, 5, 4, 4, 6]));
console.log(f([2, 3, 5, 2, 3, 4]));
console.log(f([3, 5, 7, 5, 9, 3, 7]));
console.log(f([5, 6, 7, 8, 9, 10, 11]));
console.log(f([1, 9, 1, 8, 1, 6, 1, 11]));
```
> 2 votes

# Answer
# Retina,  ~~41~~ 39 bytes

*2 bytes golfed thanks to Martin Ender, which by the way introduced me to balancing groups with his fantastic guide on SO*

```
$
,$`,
((1)+,)(?=(?<-2>1+,)*(\1|$))

^$

```

Input is a comma-separated list of unary numbers. Output is `0` for false and `1` for true.

Try it online! (Test suite that automatically converts from decimal)

I've recently learned about balancing groups, so I wanted to give them a try. They're not among the easiest tools to use, but sure they are powerful.

### Explanation

```
$
,$`,

```

As many other submissions do, we duplicate the list to deal with wrapping. We also add a comma at the end, so every number is followed by a comma (this makes things a bit easier later)

```
((1)+,)(?=(?<-2>1+,)*(\1|$))

```

Here's where things get interesting. This is a replacement stage, we replace everything matched by the first line with the second line, in this case we are looking to remove all numbers `n` not followed by `n+1` other different numbers.

To do so, we first match the number, capturing each `1` in a group (capturing group number 2 in this case). Then with a positive lookahead, in order to have a zero-width assertion, we repeatedly try to match in a balancing group `-2`, that will succeed no more than the number of captures made by group `2`, a number followed by a comma. After this sequence of numbers, we are satisfied if we reach either the first number again or the end of the line.

Note: this expression could match just the final part of a number, if it doesn't manage to find a match with the full number. This is not a problem, because then the first part of the number will remain in the string and we will know that the replacement didn't completely succeed.

```
^$

```

Finally, the result should be truthy iff we have completely removed all numbers from the list. We try to match the empty string and return the number of matches found.
> 2 votes

# Answer
# Jelly, 11 bytes

```
ẋ2ĠṢI_2<"QȦ

```

Try it online!

```
ẋ2ĠṢI_2<"QȦ  Main link. Argument: A (array)

ẋ2           Repeat A twice to account for wrap-around.
  Ġ          Group all indices of A + A by their respective values, sorting the
             index groups by the associated values.
   Ṣ         Sort the groups lexicographically, i.e., by first appearance in A.
    I        Increments; compute the forward differences of adjacent indices in
             each of the groups.
     _2      Subtract 2 from the differences.
         Q   Unique; yield A, deduplicated.
       <"    Compare all differences in the index group corresponding to the n-th
             unique value in A with the n-th unqiue value in A.
          Ȧ  All; yield 1 if and only if none of the comparisons returned 0.

```
> 1 votes

# Answer
# Python 3, 101 bytes

```
lambda l:all(v>=(l[i+1:].index(v)if v in l[i+1:]else len(l[i+1:])+l.index(v))for i,v in enumerate(l))

```

Try it online!
> 1 votes

# Answer
# Röda, 50 bytes

```
f a{seq 0,#a-1|[indexOf(a[_],a[_1+1:]..a)<=a[_1]]}

```

Try it online!

Finally! I have been waiting for this challenge...

It's a function that returns a truthy or a falsy value. It takes one argument, the array.

It iterates over a stream of indices and checks for each index `_1` that the distance of the current index and the next index of `a[_1]` is not more than `a[_1]`.
> 1 votes

# Answer
# Vyxal, 10 bytes

```
ƛ?=T¯‹≤A;A

```

Try it Online!

```
ƛ       ;A # Does every value have the property that...
       A   # All of...
    ¯      # The differences between...
 ?=T       # Indices of that value in the input
     ‹     # Minus 1
      ≤    # Are at most that value?

```
> 1 votes

# Answer
# 05AB1E, 13 bytes

```
Dì©v®¦©yky›_P

```

Try it online! or as a Test suite

**Explanation**

```
Dì             # duplicate input and prepend the copy to the original
  ©            # store a copy in the register
   v           # for each element in the list
    ®          # push the list from register
     ¦©        # remove the first element and store a copy in the register
       yk      # get the index of the current element in the list
         y›_   # check if it's less than or equal to the current element
            P  # product of stack

```
> 0 votes

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