title: Chromatic polynomial of a graph

text:
# Question
Title: Chromatic polynomial of a graph
Given a undirected graph \\$G\\$ and a integer \\$k\\$, how many \\$k\\$-coloring does the graph have?

Here by a **\\$k\\$-coloring**, we mean assigning one of the \\$k\\$ colors to each vertex of the graph, such that no two vertices connected by an edge have the same color. For example, the following graph can be 3-colored in 12 different ways:

Let \\$P(G,k)\\$ denotes the number of \\$k\\$-coloring of the graph \\$G\\$. For example, \\$P(G, 3) = 12\\$ for the graph above.

\\$P(G,k)\\$ is in fact a polynomial in \\$k\\$, which is known as the **chromatic polynomial**. For example, the chromatic polynomial of the graph above is \\$k^4-4k^3+5k^2-2k\\$.

This can be shown using the deletion–contraction formula, which also gives a recursive definition of the chromatic polynomial.

The following proof is taken from Wikipedia:

> For a pair of vertices \\$u\\$ and \\$v\\$, the graph \\$G/uv\\$ is obtained by merging the two vertices and removing any edges between them. If \\$u\\$ and \\$v\\$ are adjacent in \\$G\\$, let \\$G-uv\\$ denote the graph obtained by removing the edge \\$uv\\$. Then the numbers of \\$k\\$-colorings of these graphs satisfy: $$P(G,k)=P(G-uv, k)- P(G/uv,k)$$ Equivalently, if \\$u\\$ and \\$v\\$ are not adjacent in \\$G\\$ and \\$G+uv\\$ is the graph with the edge \\$uv\\$ added, then $$P(G,k)= P(G+uv, k) + P(G/uv,k)$$ This follows from the observation that every \\$k\\$-coloring of \\$G\\$ either gives different colors to \\$u\\$ and \\$v\\$, or the same colors. In the first case this gives a (proper) \\$k\\$-coloring of \\$G+uv\\$, while in the second case it gives a coloring of \\$G/uv\\$. Conversely, every \\$k\\$-coloring of \\$G\\$ can be uniquely obtained from a \\$k\\$-coloring of \\$G+uv\\$ or \\$G/uv\\$ (if \\$u\\$ and \\$v\\$ are not adjacent in \\$G\\$).
>
> The chromatic polynomial can hence be recursively defined as
>
> * \\$P(G,x)=x^n\\$ for the edgeless graph on \\$n\\$ vertices, and
> * \\$P(G,x)=P(G-uv, x)- P(G/uv,x)\\$ for a graph \\$G\\$ with an edge \\$uv\\$ (arbitrarily chosen).
>
> Since the number of \\$k\\$-colorings of the edgeless graph is indeed \\$k^n\\$, it follows by induction on the number of edges that for all \\$G\\$, the polynomial \\$(G,x)\\$ coincides with the number of \\$k\\$-colorings at every integer point \\$x=k\\$.

## Task

Given a undirected graph \\$G\\$, outputs its chromatic polynomial \\$P(G, x)\\$.

This is , so the shortest code in bytes wins.

### Input

You can take input in any reasonable format. Here are some example formats:

* an adjacency matrix, e.g., `[[0,1,1,0],[1,0,1,1],[1,1,0,0],[0,1,0,0]]`;
* an adjacency list, e.g., `{1:[2,3],2:[1,3,4],3:[1,2],4:[2]}`;
* a vertex list along with an edge list, e.g., `([1,2,3,4],[(1,2),(2,3),(3,1),(2,4)])`;
* a built-in graph object.

You may assume that the graph has no loop (an edge connecting a vertex with itself) or multi-edge (two or more edges that connect the same two vertices), and that the number of vertices is greater than zero.

### Output

You can output in any reasonable format. Here are some example formats:

* a list of coefficients, in descending or ascending order, e.g. `[1,-4,5,-2,0]` or `[0,-2,5,-4,1]`;
* a string representation of the polynomial, with a chosen variable, e.g., `"x^4-4*x^3+5*x^2-2*x"`;
* a function that takes an input \\$n\\$ and gives the coefficient of \\$x^n\\$;
* a built-in polynomial object.

## Testcases:

Input in adjacency matrices, output in polynomial strings:

```
[[0,0,0],[0,0,0],[0,0,0]] -> x^3
[[0,1,1],[1,0,1],[1,1,0]] -> x^3-3*x^2+2*x
[[0,1,0,0],[1,0,1,0],[0,1,0,1],[0,0,1,0]] -> x^4-3*x^3+3*x^2-x
[[0,1,1,0],[1,0,1,1],[1,1,0,0],[0,1,0,0]] -> x^4-4*x^3+5*x^2-2*x
[[0,1,1,1,1],[1,0,1,1,1],[1,1,0,1,1],[1,1,1,0,1],[1,1,1,1,0]] -> x^5-10*x^4+35*x^3-50*x^2+24*x
[[0,1,1,0,1,0,0,0],[1,0,0,1,0,1,0,0],[1,0,0,1,0,0,1,0],[0,1,1,0,0,0,0,1],[1,0,0,0,0,1,1,0],[0,1,0,0,1,0,0,1],[0,0,1,0,1,0,0,1],[0,0,0,1,0,1,1,0]] -> x^8-12*x^7+66*x^6-214*x^5+441*x^4-572*x^3+423*x^2-133*x
[[0,0,1,1,0,1,0,0,0,0],[0,0,0,1,1,0,1,0,0,0],[1,0,0,0,1,0,0,1,0,0],[1,1,0,0,0,0,0,0,1,0],[0,1,1,0,0,0,0,0,0,1],[1,0,0,0,0,0,1,0,0,1],[0,1,0,0,0,1,0,1,0,0],[0,0,1,0,0,0,1,0,1,0],[0,0,0,1,0,0,0,1,0,1],[0,0,0,0,1,1,0,0,1,0]] -> x^10-15*x^9+105*x^8-455*x^7+1353*x^6-2861*x^5+4275*x^4-4305*x^3+2606*x^2-704*x

```

Input in vertex lists and edge lists, output in descending order:

```
[1,2,3], [] -> [1,0,0,0]
[1,2,3], [(1,2),(1,3),(2,3)] -> [1,-3,2,0]
[1,2,3,4], [(1,2),(2,3),(3,4)] -> [1,-3,3,-1,0]
[1,2,3,4], [(1,2),(1,3),(2,3),(2,4)] -> [1,-4,5,-2,0]
[1,2,3,4,5], [(1,2),(1,3),(1,4),(1,5),(2,3),(2,4),(2,5),(3,4),(3,5),(4,5)] -> [1,-10,35,-50,24,0]
[1,2,3,4,5,6,7,8], [(1,2),(1,3),(1,5),(2,4),(2,6),(3,4),(3,7),(4,8),(5,6),(5,7),(6,8),(7,8)] -> [1,-12,66,-214,441,-572,423,-133,0]
[1,2,3,4,5,6,7,8,9,10], [(1,3),(1,4),(1,6),(2,4),(2,5),(2,7),(3,5),(3,8),(4,9),(5,10),(6,7),(6,10),(7,8),(8,9),(9,10)] -> [1,-15,105,-455,1353,-2861,4275,-4305,2606,-704,0]

```

# Answer
> 3 votes
# BQN, ~~62~~ ~~59~~ ~~55~~ 47 bytesSBCS

Takes a vertex list  on the left and an edge list  on the right. Returns coefficients in descending order.

```
{×≠?(1↓)-0∾(1↓)⍷∧¨1↓-(-´⊑)×=⊑⊑;1∾0¨}

```

Run online!

This is a recursive function based on the deletion-contraction formula.

If the edge list is empty (`¬×≠`) the polynomial `1 0 ... 0` with as many zeros as there are vertices is returned. (`1∾0¨`)

Otherwise:

* Pick \\$uv\\$ as the first edge in the list , replace all occurences of \\$u\\$ with \\$v\\$: `-(-´⊑)×=⊑⊑`.
* Remove the edge \\$uv\\$ (now \\$vv\\$), sort each edge and remove duplicate edges generated by merging \\$u\\$ and \\$v\\$: `⍷∧¨1↓`.
* Recursively call the function with this new edge list and and a vertex list with one less vertex: `(1↓)`. (Technically we would want to remove \\$u\\$ from , but as we only care about the length of the vertex list, removing the first one achieves the same). This is \\$P(G/uv, x)\\$.
* Because the recursive call got one less vertex, the resulting polynomial will have one degree too few. By prepending a zero this can be fixed: `0∾`.
* Recursively call the function on \\$G-uv\\$ and subtract the previous result from this: `(1↓)-`.

# Answer
> 3 votes
# Haskell, 102 bytes

Port of my BQN answer.

```
import Data.List
n!([u,v]:e)=zipWith(-)(n!e)$0:tail n!nub[sort$take 2$(r++[v])\\[u]|r<-e]
n!_=1:(0<$n)

```

Try it online!

I feel like there should be a shorter way to replace \\$u\\$ with \\$v\\$ in a list (currently `take 2$(r++[v])\\[u]`).

# Answer
> 3 votes
# , ~~111~~ 108 bytes

```
f=\(n,e,`+`=el)`if`(length(e),f(n,x<-e[-1])-f(n-1,unique(Map(\(i)sort(ifelse(+e+1-i,i,+e+2)),x))),c(!1:n,1))
```

Attempt This Online!

Takes input as the number of vertices `n` and list of edges `e`. Outputs a vector of coefficients in ascending order.

Thanks to pajonk for -3 bytes.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 24 bytes

```
#~ChromaticPolynomial~x&

```

Try it online!

We create a pure function for the built-in Mathematica function `ChromaticPolynomial`. We make use of infix notation.

If we need to allow adjacency matrices we can parse them to a graph using `AdjacencyGraph`. Thus we need more bytes in this case.

**Edit:** Thanks to att for guiding me to the correct solution!

# Answer
> 2 votes
# SageMath, ~~35~~ 33 bytes

```
lambda g:g.chromatic_polynomial()

```

Try it here!

The function `f` takes a built-in graph object as an argument and calculates its chromatic polynomial. However, it is fairly simple to parse a matrix directly into a sage graph object as follows.

```
Graph(matrix([[0, 1, 1], [1, 0, 1], [1, 1, 0]]))

```

In this case we would need more bytes.

**Notice** the difference to my post for Mathematica. In Mathematica we call a function and provide the graph as an argument. Here, the graph object's interface specifies the function `chromatic_polynomial`, which needs more code.

Thanks to alephalpha we can save 2 bytes!

# Answer
> 2 votes
# Python3, 668 bytes

```
from copy import*
R=lambda x:x[0]*R(x[1:])if x else 1
e=lambda g:[(i,[*g[i]][0])for i in g if g[i]][0]
T=set.remove
def r(g,e):
 g=deepcopy(g);T(g[e[0]],e[1])
 if e[1]in g:g[e[1]]={i for i in g[e[1]]if i!=e[0]}
 return g
def m(g,e):
 g=deepcopy(g);T(g[e[0]],e[1])
 if e[1]in g:g[e[1]]={i for i in g[e[1]]if i!=e[0]}
 for i in g.get(e[1],[]):
  if i in g:g[i].add(e[0])
 if e[1]in g:del g[e[1]]
 return{x:{[i,e[0]][i==e[1]]for i in g[x]}for x in g}
def f(g,s=[]):
 if not any(g.values()):yield(s,len(g));return
 yield from f(r(g,E:=e(g)),s+[1]);yield from f(m(g,E),s+[-1])
def F(g):
 d={}
 for a,b in f(g):d[b]=d.get(b,0)+R(a)
 return[*d.values()]+[0]*(len(g)-len(d)+1)

```

Try it online!

# Answer
> 2 votes
# Charcoal, 104 bytes

```
⊞υθＦυ«≔§ι⁰η≔⊟ιζ¿ζ«≔⊟ζδ≔⁻ζ⟦δ⮌δ⟧ζＦ⟦⟦ηζ⟧⟦⊖ηＥζＥκ⎇⁼μ⌈δ⌊δμ⟧⟧«⊞υκ⊞ικ»»»Ｆ⮌υ¿⊖Ｌι«≔⊟⊟ιη⊞ιＥ⊟⊟ι⁻κ§ηλ»⊞ιＥ⊕§θ⁰⁼κ§ι⁰Ｉ⊟θ

```

Try it online! Link is to verbose version of code. Takes input as a pair of the number of vertices and a list of edges and outputs the polynomial as a list of coefficients in ascending order. Explanation:

```
⊞υθＦυ«

```

Start processing with the input graph.

```
≔§ι⁰η≔⊟ιζ

```

Get the number of vertices and list of edges of this graph.

```
¿ζ«

```

If the graph still has edges, then...

```
≔⊟ζδ

```

Remove an edge from the list.

```
≔⁻ζ⟦δ⮌δ⟧ζ

```

Remove any other duplicate copies of that edge from the list.

```
Ｆ⟦⟦ηζ⟧⟦⊖ηＥζＥκ⎇⁼μ⌈δ⌊δμ⟧⟧«

```

Loop over the graph with the edge removed and the graph with the edge merged.

```
⊞υκ⊞ικ

```

Push each graph both to the list of graphs to process but also to the graph that is being processed.

```
»»»Ｆ⮌υ

```

Loop over the list of graphs in reverse order.

```
¿⊖Ｌι«

```

If this graph had to be split into two simpler graphs, then...

```
≔⊟⊟ιη⊞ιＥ⊟⊟ι⁻κ§ηλ

```

... push the difference between the two polynomials from the simpler graphs to this graph, ...

```
»⊞ιＥ⊕§θ⁰⁼κ§ι⁰

```

... otherwise push the polynomial for a trivial graph to this graph.

```
Ｉ⊟θ

```

Output the polynomial for the original graph.

# Answer
> 1 votes
# Pari/GP, 87 bytes

A port of ovs's Haskell answer. Make sure to upvote that answer as well!

```
f(n,e)=if(e,[u,v]=e[1];-f(n[^1],Set([Set([if(w-u,w,v)|w<-r])|r<-e=e[^1]]))+f(n,e),x^#n)

```

Try it online!

# Answer
> 1 votes
# Python \+ `sympy`, 458 bytes

A Port of @ovs's Haskell answer.

---

Golfed version. Attempt this online!

```
from sympy import*
def f(n,e):
    if e:
        u,v=e[0]
        w=[N for N in n if N!=u]
        E=[]
        for d in e[1:]:
            if u in d and v in d:
                continue
            elif u in d:
                E.append([v if N == u else N for N in d])
            else:
                E.append(d)
        E= [list(i) for i in set(tuple(sorted(s)) for s in E)]
        return -f(w,E)+f(n,e[1:])
    else:
        return symbols('x')**len(n)

```

Ungolfed version. Attempt this online!

```
from sympy import symbols

x = symbols('x')

def f(n, e):
    if e:
        u, v = e[0]
        n_without_u = [node for node in n if node != u]

        # Generate new edges after merging u and v
        new_edges = []
        for edge in e[1:]:
            if u in edge and v in edge:
                continue  # remove edge if it contains both u and v
            elif u in edge:
                new_edges.append([v if node == u else node for node in edge])
            else:
                new_edges.append(edge)

        # Remove any potential duplicate edges
        new_edges = [list(item) for item in set(tuple(sorted(sub)) for sub in new_edges)]

        return -f(n_without_u, new_edges) + f(n, e[1:])
    else:
        return x**len(n)

test_cases = [
    [[1,2,3], []],
    [[1,2,3], [[1,2],[1,3],[2,3]]],
    [[1,2,3,4], [[1,2],[2,3],[3,4]]],
    [[1,2,3,4], [[1,2],[1,3],[2,3],[2,4]]],
    [[1,2,3,4,5], [[1,2],[1,3],[1,4],[1,5],[2,3],[2,4],[2,5],[3,4],[3,5],[4,5]]],
    [[1,2,3,4,5,6,7,8], [[1,2],[1,3],[1,5],[2,4],[2,6],[3,4],[3,7],[4,8],[5,6],[5,7],[6,8],[7,8]]],
    [[1,2,3,4,5,6,7,8,9,10], [[1,3],[1,4],[1,6],[2,4],[2,5],[2,7],[3,5],[3,8],[4,9],[5,10],[6,7],[6,10],[7,8],[8,9],[9,10]]]
]

for case in test_cases:
    print(f"{case} -> {f(case[0], case[1])}")

```

---
Tags: code-golf, graph-theory, polynomials
---


# Question
Title: Is it a canonical elementary CA rule number?
## Background

Given an elementary cellular automaton rule number like, for example, 28 = `00011100`

* We can swap \\$\color{red}{\text{the 2nd bit with the 5th bit}}\\$ and \\$\color{orange}{\text{the 4th bit with the 7th bit}}\\$ to get a rule that acts the same way but mirrored horizontally. This gets us `01000110` = 70.
* We can reverse *and flip* all the bits to get a rule that does the same thing but with black and white reversed: `11000111` = 199.
* And we can combine these two processes — it doesn't matter which order we apply them in — to get a mirrored, reversed rule: `10011101` = 157.

Or, as MathWorld puts it:

> The mirror image, complement, and mirror complement are rules 70, 199, and 157, respectively.

The automata identified by rules {28, 70, 199, 157} all behave the same way, up to arbitrary distinctions of colors and axis orientation. But because 28 is the *lowest* of these four numbers, it is the "canonical" rule number.

## Task

Write a program or function that takes an input \\$0 \leq n \leq 255\\$ and decides whether it is a canonical rule number.

These 88 inputs should be give a "true" result:

```
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 18 19 22 23 24 25 26 27 28 29 30 32 33 34 35 36 37 38 40 41 42 43 44 45 46 50 51 54 56 57 58 60 62 72 73 74 76 77 78 90 94 104 105 106 108 110 122 126 128 130 132 134 136 138 140 142 146 150 152 154 156 160 162 164 168 170 172 178 184 200 204 232

```

and all other inputs should give a "false" result.

This is . The I/O defaults apply.

# Answer
# Jelly, 18 bytes

I imagine there may be a shorter hashing based Link that any approach like this, but finding it might take a while ;p

```
+⁹BḊ⁽¦hœ?,ƊU¬;ƊḄṂ⁼

```

A monadic Link that accepts an integer from \\$\[0,255\]\\$ and yields \\$1\\$ if connonical, else \\$0\\$.

**Try it online!**

### How?

```
+⁹BḊ⁽¦hœ?,ƊU¬;ƊḄṂ⁼ - Link: integer, Rule
+⁹                 - {Rule} add 256
  B                - convert to binary
   Ḋ               - dequeue (remove the leading 256-bit)
          Ɗ        - last three links as a monad f(Rule-Byte=that):
    ⁽¦h            -   2355
       œ?          -   {2355}th permutation of {Rule-Byte}
                         (swap bit 2 with bit 5 and bit 4 with bit 7)
         ,         -   pair with {Rule-Byte}
              Ɗ    - last three links as a monad f(Mirrors=that):
           U       -   reverse each
            ¬      -   logical Not
             ;     -   concatenate {Mirrors}
               Ḅ   - convert from binary
                Ṃ  - minimum
                 ⁼ - equals {Rule}?

```
> 7 votes

# Answer
# Nekomata, 19 bytes

```
¥+Ƃi:↔¬?:Jĭ,Ťđ,?ƃa≤

```

Attempt This Online!

```
¥+Ƃi:↔¬?:Jĭ,Ťđ,?ƃa≤
¥+                      Add 256 to ensure that binary length is 9
  Ƃ                     Binary digits; least significant bit comes first
   i                    Remove the last digit (the 1 from the 256)
                        Now the list contains exactly 8 digits
    :  ?                Optional apply:
     ↔¬                     Reverse and logical NOT
        :      ?        Optional apply:
         Jĭ,Ťđ,             Swap the 2nd and 5th digits, and the 4th and 7th digits
                ƃ       Convert from binary to decimal
                 a≤     Check that all possible values are greater than or equal to the input

```
> 6 votes

# Answer
# Python, 95 bytes

```
lambda x:x==min(z for y in(x,256+~int(f'{x:08b}'[::-1],2))for z in(y,y&165|(y&80)>>3|(y&10)*8))

```

Attempt This Online!
> 5 votes

# Answer
# Python 3, 61 bytes

```
lambda i:61!=i<=255^int(f'{i:08b}'[::-1],2)!=194>i*8&80>=i&80

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES11), 54 bytes

Expects a BigInt. Returns `1` for canonical or `0` for non-cannonical.

```
n=>0x10005012777AFFA0F0A0F0FAFFFAFFn>>n%2n*64n+n/2n&1n

```

Try it online!

We take advantage of the following properties to reduce the size of the lookup bit-mask:

$$f(2k+128)=f(2k+1),\\:0\le k\<64$$ $$f(2k+1)=0,\\:k\>52$$

---

# JavaScript (ES6), 75 bytes

Returns `0` for canonical or `1` for non-cannonical.

```
n=>(g=n=>n&165|n/8&10|n*8&80)(n)<n|(h=i=>q=i--&&~n>>i&1|2*h(i))(8)<n|g(q)<n

```

Try it online!
> 4 votes

# Answer
# , 36 bytes

```
=[:<./(,&(,:2354&A.)1-|.)@{.~&_8&.#:

```

Try it online!

Constructs all possible representations according to the spec, and checks if the input is the min of those.
> 3 votes

# Answer
# sclin, 65 bytes

```
"256+2X>b1dp."Q"2b>X"map"&"fold~ =
["""_` ! ""perm2354:""++"Q ] Q

```

Try it here!

For testing purposes:

```
28 ;
"256+2X>b1dp."Q"2b>X"map"&"fold~ =
["""_` ! ""perm2354:""++"Q ] Q

```

## Explanation

Prettified code:

```
\; Q 2.b>X map \& fold~ =
256+ 2X>b 1dp.
["" "_` ! " "perm2354:" \++ Q ] Q

```

Assuming input *n*:

* `256+ 2X>b 1dp` convert *n* \+ 256 to binary and drop 0th bit
    + i.e. convert *n* to binary digits, padded to length 8
* `[ "" "_` ! " "perm 2354:" \++ Q ] Q` vectorized-evaluate the binary digits over the following...
    + `""` just return the digits
    + `"_` ! "` reverse array + vectorized-NOT
    + `"perm 2354:"` 2354th permutation
    + `\++ Q` get concatenation of previous 2 strings
* `2.b>X map` convert back to decimal
* `\& fold~` minimum
* `=` check if equal to *n*
> 2 votes

# Answer
# Charcoal, 39 bytes

```
⊞υΦ↨⁺²⁵⁶Ｎ²κ⊞υＥ04261537§⌊υＩι¬⌕υ⌊⁺υＥυ⁻¹⮌ι

```

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

```
⊞υΦ↨⁺²⁵⁶Ｎ²κ

```

Convert the input to base `2` padded to `8` digits and push the result to the predefined empty list.

```
⊞υＥ04261537§⌊υＩι

```

Apply the permutation to the result given by reflecting the binary for each index and push that.

```
¬⌕υ⌊⁺υＥυ⁻¹⮌ι

```

Logically invert and reverse each of the two results and check that the minimum of the four values is the original input.
> 2 votes

# Answer
# K (ngn/k), 42 bytes

```
{x~&//2/''(~|:')\1@[;|8\15637664]\(8#2)\x}

```

Try it online!
> 2 votes

# Answer
# Retina, 118 bytes

```
.+
*
8+`^(_*)\1(_?)
$1$.2
(.)(.)(.)(.)(.)(.)(.)(.)
$&¶$&¶$1$5$3$7$2$6$4$8
¶(.+)
¶$^$1$&
T`d`10`¶(.+)¶
O`¶(.+)
^(.+)¶\1

```

Try it online! Link includes test suite. Explanation:

```
.+
*

```

Convert to unary.

```
8+`^(_*)\1(_?)
$1$.2

```

Convert to `8` bits of binary.

```
(.)(.)(.)(.)(.)(.)(.)(.)
$&¶$&¶$1$5$3$7$2$6$4$8

```

Duplicate the input, then append the shuffled input.

```
¶(.+)
¶$^$1$&

```

Duplicate both new rows but with the bits reversed.

```
T`d`10`¶(.+)¶

```

Complement the bits in the reversed rows.

```
O`¶(.+)

```

Sort all the rows except the very original.

```
^(.+)¶\1

```

Check that the first of the sorted rows is the same as the original.
> 1 votes

# Answer
# 05AB1E, 23 bytes

Should have been 20 bytes, but there is a bug in the \\$n^{th}\\$ permutation builtin `.I` for bit-lists..

```
₁+2в¦Dā<Ž9x.Iè‚Dí_«JCßQ

```

Try it online or verify all truthy test cases.

**Explanation:**

```
₁+                   # Add 256 to the (implicit) input-integer
  2в                 # Convert it to a binary-list (this cannot be a binary-string,
                     # because builtin `.I` only works with lists)
    ¦                # Remove the first 1 to 'subtract' the 256 again
     D               # Duplicate this bit-list
      ā<             # Workaround part 1 of 2: Push a list in the range [0,length)
                     # without popping the list itself
      Ž9x            # Push compressed integer 2354
         .I          # Get the 2354th permutation of the [0,length) list
          è          # Workaround part 2 of 2: Index those into the duplicated bit-list
           ‚         # Pair the two bit-lists together
            D        # Duplicate this pair
             í       # Reverse each inner list
              _      # And negate each with an ==0 check
               «     # Merge the two pairs together
                JC   # Convert the inner bit-lists to integers
                  ß  # Pop and push the minimum
                   Q # Check whether it's equal to the (implicit) input-integer
                     # (after which the result is output implicitly)

```
> 1 votes

# Answer
# JavaScript (V8), 135 bytes

```
x=>/^(.|2[^01]|[37][^0159]|[369]0|4[0-6]|5[^2359]|35|62|94|1([^67]|0[458]|10|22|[3-7][02]|[2367]8|[3568]4|[02-5]6)|20[04])$|32/.test(x)

```

Try it online!

Can't wait for Deadcode to outgolf this :-)
> 0 votes

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


# Question
Title: Tips for Golfing the Lambda Calculus & Friends
This includes tips for all related derivatives, as coding in these langs often primarily consists of writing the function in the lambda calculus and then compiling it down at the end.

Among others, this includes tips for:

Please post one tip per answer.

We have one tips page already for binary lambda calculus here. However it only has one answer, and it's a tip for the general calculus; not binary specific. We'll have to decide if we want to keep that question open.

# Answer
> 2 votes
# Implementations on the Web

For those who are into standard Lambda calculus/combinator calculus, it is a shame that it isn't easy to find an easy-to-use interpreter and converter, especially the ones available on a web page. Here are some that I know of.

* aditsu's interpreter runs SKIBC expressions and outputs a reduced lambda term.
* Ben Lynn has several interpreters and converters on their web site. Note that each one accepts slightly different syntax, so check out the example program(s).
    + plain lambda calculus: evaluates lambda calculus expressions and shows the result in a raw form, like aditsu's. You can write auxiliary definitions.
    + combinatory logic: takes a lambda term and converts to SK calculus.
    + SK-based compiler: takes a lambda program (with auxiliary definitions), compiles to SK-based intermediate representation, and evaluates it to a Church numeral.
    + Crazy L: takes a lambda program (with auxiliary definitions and predefined combinators) in various syntaxes, compiles to SKIBC intermediate form, and evaluates it to a Church numeral. This one apparently supports inputs too.

Crazy L can be used to demonstrate simple programs in LC or SKI(BC), but also used as its own language for golfing.

I'm planning to write one that can handle various I/O formats other than Church numerals, and can compile lambda expressions to SKI(BC) and BLC (and maybe another encoding of my own). I'll update when I get it to a usable state.

---
Tags: code-golf, tips, combinatory-logic, lambda-calculus
---


title: Decimalize a Fraction

text:
# Question
Title: Decimalize a Fraction
## Preamble

A common pain-point when working with rational numbers and decimals is how infrequently one can represent their rational number as a clean, non-repeating decimal. Let's solve this by writing a program to decimalize (not to be confused with decimate) them for us!

## The Challenge

Given a fraction, check if it can be represented perfectly by a finite decimal number. If it can, output the decimal representation of this fraction. Otherwise, output the input fraction.

## Specifics

Input will be provided as two integers within the range of `[1, 32767]` *(Positive Signed Shorts)*, representing both the Numerator and Denominator. Numbers may be taken in any convenient format or order, including built-in Fraction formats, a single pre-divided floating point number *(of a precision that can accurately represent all possible fractions)*, a deliminated string, an imagine number, etc. The Input is **not** guaranteed to be in simplified form.

A given Input is "Decimalizable" if the Denominator of the Simplified Fraction contains no prime factors other than `2` or `5`.

The Output, given a Decimalizable Input, must be a decimal number. This may be as any convenient format, including a string, char array, or float. It may **not** be a Fraction type. *(Floats are allowed as it is generally trivial to stringify.)* Trailing Zeroes are **not** allowed, though leading zeroes are.

Otherwise, The Output must be Two Numbers signifying the Numerator and Denominator, in any convenient format. The output may **not** be a decimal number, nor a floating point number. Output may optionally be Simplified.

## Test Cases

```
16327 /     4 = 4081.75
  186 /   400 = 0.465
23164 /   100 = 231.64
32604 / 20000 = 1.6302
22764 / 16384 = 1.389404296875
    3 /     6 = 0.5
    1 /     3 = 1/3
 3598 /  2261 = 514/323
 7725 / 18529 = 7725/18529
21329 /  3774 = 21329/3774
12213 /  2113 = 12213/2113

```

## Rules

# Answer
> 6 votes
# Vyxal, 86 bitsv2, 10.75 bytes

```
\/€tǏ25F[|øḋ

```

Try it Online!

And here I thought I was being clever skipping the challenge text. Takes a fraction as input, which is automatically simplified.

## Explained

```
\/€tǏ25F[|øḋ
\/€           # Push a copy of the input splitted on "/"
   tǏ25F      # Push the prime factorisation of the denominator with 2s and 5s removed.
        [|øḋ  # If that is empty, convert to decimal.

```

Created with the help of Luminespire.

# Answer
> 11 votes
# Python 3, 34 bytes

```
lambda n,d:[n/d,(n,d)][n*1e16%d>0]

```

Try it online!

# Answer
> 5 votes
# Husk, 13 bytes

```
?¤/i/¤-p*10¹³

```

Try it online!

Input as two integers (den, num) represented in floating-point format: it's much easier in Husk to convert a float to an int than the other way around.

```
?¤/i/¤-p*10¹³       # full program
?¤/i/¤-p*10⁰²⁰²     # with arg expansion:
     ¤              # combin: ¤fgxy means f(gx)(gy)
      -             #  f = - = list difference
       p            #  g = p = prime factors
        *10⁰        #  x = 10x arg1
            ²       #  y = arg2
                    # (so this simplifies the fraction,
                    # and returns list of any non-2, non-5 factors
                    # - truthy if there are any, falsy if none)
?                   # fif: ternary if for functions
                    # use the above result to choose from:
 ¤/i             ⁰² #  (if truthy) convert both args to integers & divide
                    #  (Husk outputs real fractions by default)
    /            ⁰² #  (if falsy) just divide
                    #  (keeps input floating-point format)

```

# Answer
> 4 votes
# Retina 0.8.2, 246 bytes

```
\d+
$*
^(1+)(\1)*/(\1)*$
1$#2$*1/$#3$*
+`/(1+)\1{9}(0*)$
/$1$+0
+`/(1+)\1{4}(0*)$
$`/$1$+0
+`/(1+)\1(0*)$
$`$`$`$`/$1$+0
+`/(11+)0
/$1$1$1$1$1$1$1$1$1$1
^(1+)(\1)*/(\1)*$
1$#2$*1/$#3$*
1+
$.&
r`^(?<-1>.)+/1(0)+$
$#1$*00$&
r`((?<-2>.)+)/1(0)+$
.$1

```

Try it online! Link includes faster test cases, as manipulating large numbers in unary is horribly slow. Explanation:

```
\d+
$*

```

Convert to unary.

```
^(1+)(\1)*/(\1)*$
1$#2$*1/$#3$*

```

Reduce to lowest terms.

```
+`/(1+)\1{9}(0*)$
/$1$+0

```

Find all factors of `10` in the denominator.

```
+`/(1+)\1{4}(0*)$
$`/$1$+0
+`/(1+)\1(0*)$
$`$`$`$`/$1$+0

```

Find all factors of `5` and `2` in the denominator, and multiply both numerator and denominator by `2` or `5`.

```
+`/(11+)0
/$1$1$1$1$1$1$1$1$1$1

```

If the denominator turned out to have other factors, then convert it back to unary.

```
^(1+)(\1)*/(\1)*$
1$#2$*1/$#3$*

```

Reduce the fraction to lowest terms again, but only if it was converted back to unary.

```
1+
$.&

```

Convert to decimal.

```
r`^(?<-1>.)+/1(0)+$
$#1$*00$&

```

Prepend zeros to the numerator if the denominator is a larger power of `10`.

```
r`((?<-2>.)+)/1(0)+$
.$1

```

Divide the numerator by the denominator if it is a power of `10`.

179 bytes and faster for exact decimals in Retina 1:

```
+`.+/(.*50*)$
$.(*2*)/$.($1*2*
+`.+/(.*[2468]0*)$
$.(*5*)/$.($1*5*
+`0(/.+)0$
$1
r`^(?<-1>.)+/1(0)+$
0$#1*0$&
r`((?<-2>.)+)/1(0)+$
.$1
/\//&`\d+
*
^(_+)(\1)*/(\1)*$
$.(_$#2*_)/$#3

```

Try it online! Link includes test cases. Explanation:

```
+`.+/(.*50*)$
$.(*2*)/$.($1*2*

```

Double the numerator and denominator while the latter ends in `50*`.

```
+`.+/(.*[2468]0*)$
$.(*5*)/$.($1*5*

```

Multiply the numerator and denominator while the latter's last nonzero digit is even.

```
+`0(/.+)0$
$1

```

Cancel out any power of `10` common to both numerator and denominator.

```
r`^(?<-1>.)+/1(0)+$
0$#1*0$&

```

Prepend zeros to the numerator if the denominator is a larger power of `10`.

```
r`((?<-2>.)+)/1(0)+$
.$1

```

Divide the numerator by the denominator if it is a power of `10`.

```
/\//&`\d+
*
^(_+)(\1)*/(\1)*$
$.(_$#2*_)/$#3

```

Otherwise, reduce the fraction to its lowest terms.

# Answer
> 4 votes
# Factor, 44 bytes

```
[| x y | x 1e16 * y mod 0 > x y / x y /f ? ]

```

Try it online!

Port of xnor's Python answer. The only difference is that it's shorter to return either a ratio or a float instead of bothering with lists.

# Answer
> 4 votes
# 05AB1E, 11 bytes

```
`s16°*sÖi`/

```

I/O as a pair \\$\[nominator,denominator\]\\$. The output is unsimplified.

Port of *@xnor*'s Python 3 answer.

Try it online or verify all test cases.

**Explanation:**

```
`           # Pop the (implicit) input-pair, and push both items separately to the stack
 s          # Swap so the nominator is at the top
  16°       # Push 10000000000000000 (10**16)
     *      # Multiply it to the nominator
      s     # Swap so the denominator is at the top again
       Ö    # Check if the nominator with 16 trailing 0s is divisible by the denominator
        i   # Pop, and if this is truthy:
         `  #  Pop and push the input-pair separated to the stack again
          / #  And divide them
            #  (after which this decimal is output implicitly as result)
            # (implicit else)
            #  (output the implicit input-pair instead)

```

# Answer
> 3 votes
# Wolfram Language (Mathematica), 47 bytes

```
If[Depth[r=RealDigits@#]>3,#,N[#,Tr[1^#&@@r]]]&

```

Try it online!

-8 bytes thanx to @att

# Answer
> 3 votes
# JavaScript (ES6), 24 bytes

Unsurprisingly, a port of xnor's method probably leads to the shortest code.

```
p=>q=>p*1e16%q?[p,q]:p/q

```

Try it online!

---

### Other approach (43 bytes, invalid)

Expects `(p)(q)`. Returns either `[p,q]` or `p/q`.

We multiply by \\$5\\$ the greatest power of \\$2\\$ that divides \\$q\\$ until it's greater than or equal to \\$q\\$.

This works for all test cases (at the time of posting) but would fail on some others because *the input is not guaranteed to be in simplified form*.

```
p=>q=>(g=n=>n>q?[p,q]:n<q?g(n*5):p/q)(q&-q)

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 125 bytes

```
f=s=>{[n,m]=s.split('/').map(v=>+v);for(i=n>m?n:m;i>1;i--)if(!(n%i|m%i))[n,m]=[n/i,m/i];return n*1e16%m?`${n}/${m}`:`${n/m}`}

const testCases = [
  { input: '16327/4',     output: '4081.75'        },
  { input: '186/400',     output: '0.465'          },
  { input: '23164/100',   output: '231.64'         },
  { input: '32604/20000', output: '1.6302'         },
  { input: '22764/16384', output: '1.389404296875' },
  { input: '3/6',         output: '0.5'            },
  { input: '1/3',         output: '1/3'            },
  { input: '3598/2261',   output: '514/323'        },
  { input: '7725/18529',  output: '7725/18529'     },
  { input: '21329/3774',  output: '21329/3774'     },
  { input: '12213/2113',  output: '12213/2113'     },
];

for (let { input, output } of testCases) {
  console.log(input, '=>', f(input) === output); // Equals?
}
```

```
.as-console-wrapper { top: 0; max-height: 100% !important; }
```

# Answer
> 2 votes
# Charcoal, 40 bytes

```
≔Ｉ⪪Ｓ/θ≧÷⌈Φ⊕⌊θ∧ι¬⌈﹪θιθ¿﹪Ｘχφ§θ¹⪫θ/Ｉ∕§θ⁰§θ¹

```

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

```
≔Ｉ⪪Ｓ/θ

```

Input the fraction.

```
≧÷⌈Φ⊕⌊θ∧ι¬⌈﹪θιθ

```

Reduce it to its lowest terms.

```
¿﹪Ｘχφ§θ¹

```

If the denominator is not a factor of `10¹⁰⁰⁰`...

```
⪫θ/

```

... output as a fraction, otherwise...

```
Ｉ∕§θ⁰§θ¹

```

output as a decimal.

81 bytes for the way overengineered version which works with arbitrary precision positive integer inputs:

```
≔Ｉ⪪Ｓ/θＷ﹪§θ±²§θ±¹⊞θι≧÷⌊θθ≔Ｘχ⌈Ｅ25⌕⮌Ｘ⁰↨§θ¹Ｉι⁰η¿﹪η§θ¹⪫…θ²/⁺÷§θ⁰§θ¹⭆Ｉ⁺η﹪×§θ⁰÷η§θ¹η⎇κι.

```

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

```
≔Ｉ⪪Ｓ/θ

```

Input the fraction.

```
Ｗ﹪§θ±²§θ±¹⊞θι≧÷⌊θθ

```

Reduce it to its lowest terms.

```
≔Ｘχ⌈Ｅ25⌕⮌Ｘ⁰↨§θ¹Ｉι⁰η

```

Find a power of `10` that the denominator might be a factor of.

```
¿﹪η§θ¹⪫…θ²/

```

But if it isn't then just output the fraction.

```
⁺÷§θ⁰§θ¹⭆Ｉ⁺η﹪×§θ⁰÷η§θ¹η⎇κι.

```

Convert the fraction to arbitrary precision decimal.

# Answer
> 2 votes
# C (gcc), 137 bytes

```
#define W(A,B)for(;d%A<1;q*=10,++c)n*=B,d/=A;
f(a,b){long n=a,d=b,q=1,c=0;W(2,5)W(5,2)printf("%ld%c%0*ld",d?a:n/q,47-!d,c*!d,--d?b:n%q);}

```

Try it online!

# Answer
> 2 votes
# Ruby, 30 bytes

Yet another xnor port. Like chunes' Factor port, it's shorter to return a `Rational` instead of an array if it can't be decimalized.

```
->n,d{(n*1e16%d>0?1r:1.0)*n/d}

```

Attempt This Online!

# Answer
> 2 votes
# sclin, 29 bytes

```
16 17,.N>d Q",_ ="Q0.:"pop"?#

```

Try it on scline!

## Explanation

Prettified code:

```
16 17,.N>d Q ( ,_ = ) Q 0.: \pop ?#

```

Numbers in sclin are internally represented as rational numbers.

* `16 17,.N>d Q` represent the fraction as a decimal with 16 and 17 places
* `( ,_ = ) Q ... ?#` check if both representations are equal...
    + `0.:` if true, then get decimal representation
    + `\pop` otherwise, get rational representation

---
Tags: code-golf, math, rational-numbers
---


# Question
Title: Make your code error, but only sometimes!
Your task is to create a program or function which **randomly** errors. Specifically, there must be a nonzero probability of erroring, but also a nonzero probability of running without error.

An error is anything that causes a program to terminate abnormally, such as dividing by zero or using an uninitialized variable. This also includes runtime errors, syntax errors and errors while compiling. Statements which manually throw an error, such as JavaScript's `throw` are allowed.

This program doesn't need to do anything if it doesn't error, other than exiting gracefully.

This is , so shortest answer per language wins.

**Note:** For this challenge, "randomly" follows the current consensus (so no using undefined behavior or uninitialized memory for randomness), and the program must be capable of producing both outputs if run or compiled multiple times (so a random number with the same seed is not valid)

# Answer
# Baby Language, 0 bytes

```

```

Try it online!

I *knew* this could be fun with a non-deterministic tarpit! I looked through the category on the *Esolang* wiki and found this language...

From the page:

> A Baby Language interpreter ignores the input program and does something random. (Likewise, a Baby Language compiler generates a random executable.) As such, whatever you wanted your program to do, there's an (admittedly small) chance that it will actually do it.
>
> The intended use case for the language is to run your program repeatedly until it does what you want. Just like trying to reason with a real baby, this may take quite a while.

So the blank program, and every program for that matter, executes a random program which will therefore randomly error!

### Details on TIO link

I used *Esolang* user Enoua5's source code which generates and executes a random brainfuck program. It's linked on the Esolang page:

> An interpreter created in Python 3 by User:Enoua5: View Source

So the *TIO* link above takes you to Python 3 interpreter is implemented in the header and the actual (blank) code is in the (blank) code slot, which is ignored anyway!

The above interpreter is simply copied and pasted into the header; a multiline comment starting/ending in the header/footer nullifies the actual code.
> 33 votes

# Answer
# Charcoal, 2 bytes

```
‽‽

```

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

```
 ‽  Random value (defaults to 0 or 1)
‽   Random element from implicit range

```

If the first random value is `1`, then the implicit range is simply `[0]`, so the random element is just `0`, which does nothing (it's implicitly printed, but printing `0` has no effect).

If the first random value is `0` however, then the implicit range is `[]`. This is an illegal input to `randrange` which therefore throws a ValueError.
> 21 votes

# Answer
# Bash \+ Unix utilities, ~~12~~ ~~11~~ 8 bytes

```
m$RANDOM

```

Try it online!

If `$RANDOM` happens to have the value `4`, this will run the macro processor `m4` (which exits right away on TIO because stdin is empty). If `$RANDOM` has any other value, you'll get an error because there's no program available via $PATH with the indicated name.

---

If you want pure bash, with no external utilities, then the shortest I’ve found is my first version (which is 12 bytes long):

```
((1/RANDOM))

```
> 17 votes

# Answer
# Python 3, ~~15~~ ~~14~~ 11 bytes

*-3 bytes thanks to @newbie!*

```
1/(id(0)%3)

```

Try it online!

**Also 11 bytes**:

```
id(0)%3or a

```

Try it online!

**How**: The `id` of an object varies across different runs. Thus `id(0)%3` can be `0`, which causes `ZeroDivisionError` and `NameError` in the programs above respectively.
> 16 votes

# Answer
includes 3 different answers, smallest first

# x86-64 machine code "function", 4 bytes

("works" in all 3 modes: 16-bit, 32-bit, and 64-bit. In other modes, FE 00 is a jmp to eax or ax.)

```
0000000000401000 <timejump>:
  401000:       0f 31           rdtsc           # EDX:EAX = timestamp counter
  401002:       ff e0           jmp    rax      # "return" with jmp to register

```

This function can be called with `jmp` instead of `call`; it doesn't need you to pass it a return address on the stack. **It uses the low 32 bits of the time counter as a jump target, which might or might not be the correct return address (or somewhere else useful).**

The crash possibility is code-fetch from an unmapped or non-executable page, or jumping to instructions that fault (e.g. `00 00 add [rax],al`), or to an illegal instruction, like a `1F` or other byte somewhere in 64-bit mode, or a multi-byte illegal sequence in 16 or 32-bit mode, that will raise #UD.

RDTSC sets EDX:EAX = the number of reference cycles since power-on (i.e. the TSC = TimeStamp Counter, SO canonical Q&A about it. Note that it doesn't count core clock cycles on modern x86). The reference frequency is normally close to the CPU's sticker frequency (e.g. 4008MHz on a nominally 4GHz i7-6700k) so **the low 32 bits wraps around in just over 1 second, which is close enough to random for interactive use.** Or every few seconds on chips with lower "base" frequencies.

Assuming a valid return address or other jump target exists in the low 32 bits of virtual address space, we have a `1` in `2^32-1` chance of reaching it. Or higher if there are multiple useful targets to dispatch to. (Assuming TSC is uniformly distributed, and fine-grained enough that every 32-bit low half is actually possible. I think this is the case.)

In 32 and 16-bit mode, every possible address (in the same code segment) is reachable, but 64-bit mode unfortunately still splits the TSC between EDX and EAX so most of the 64-bit (or 48-bit) address space is unreachable.

On systems like MacOS where 64-bit processes normally have all their code outside the low 4GiB of address space, use 32-bit mode. Linux non-PIE executables are mapped in the low 2GiB of virtual address space so any non-library code will be reachable.

---

# x86 32-bit machine code function, 5 bytes

```
0000000000401000 <inctime>:
 8049000:       0f 31                   rdtsc           # EDX:EAX = timestamp counter
 8049002:       40                      inc    eax      # EAX++
 8049003:       ce                      into            # trap if OF==1
 8049004:       c3                      ret

```

On most x86 CPUs, the TSC is fine-grained and really can be any value in the low half, including 231-1. So incrementing it can produce signed integer overflow, setting OF.

Also works in 16-bit mode (incrementing only AX with this machine code), but not 64-bit mode where `into` isn't a valid opcode.

# x86-64 machine code function, 6 bytes

(same machine code works in all 3 modes, using the default operand size for the mode; 16, 32, and 32.)

divides 64-bit user input by a random number: can overflow or divide by 0.

```
0000000000401000 <divrandom>:                          # input in EDX and EAX
  401000:       0f c7 f1                rdrand ecx
  401003:       f7 f1                   div    ecx       # return EDX:EAX / ECX
  401005:       c3                      ret

```

Yup, x86 has a *true* RNG built in (Intel since IvyBridge, and AMD since at least Zen).

x86 division of 64-bit EDX:EAX / 32-bit ECX =\> 32-bit quotient and remainder faults (with a #DE exception -\> SIGFPE or other OS signal) if the quotient doesn't fit in 32-bit EAX. With a small dividend, this can only happen on divisor = 0, 1 chance in 2^32.

With function input in EDX:EAX above 2^32-1, small divisors could leave a quotient larger than 2^32-1. So the chance of faulting depends on the input value. Specifically, division runs without faulting if ECX \> EDX, where ECX is the random divisor and EDX is the high half of the 64-bit input.

---

`rdrand` always sets OF to 0 so we can't use 1-byte `into` conditionally trap on overflow. (It only sets CF = success, 0 means HW RNG temporarily exhausted).

---

I can't think of any "unpredictable / undefined behaviour" situation that could actually give different results on different runs, other than meltdown-style timing that depends on microarchitectural conditions.

Some old ARM and MIPS CPUs have unpredictable behaviour that depends on timing if you for example use a multiply where the destination is one of the inputs, or on MIPS I read the result of a load in the next instruction (in the load delay slot). So for example on MIPS `lw $ra, ($a0)` ; `jr $ra` (4 bytes each) might use the original return address in `$ra` (the link register) if the load hits in cache, otherwise it stalls and we'd return to wherever the load points.
> 13 votes

# Answer
# JavaScript (V8), ~~15~~ 13 bytes

*idea and -2 bytes from @apsillers*

Uses `new Date` instead of `Math.random`, has a \\$\frac{1}{9}\\$ chance of not erroring:

```
new Date%9&&a

```

Try it online!

# JavaScript (V8), ~~17~~ 16 bytes

*-1 thanks to @newbie*

```
Math.random()&&a

```

Try it online!

This has a \\$\frac{1}{2^{1074}}\\$ chance of not erroring, as `Math.random()` can occasionally be 0.
> 8 votes

# Answer
# \>\<\>, 3 bytes

```
x,;

```

Try it online!

My first submission in \>\<\>, very simple
> 7 votes

# Answer
# , 6 byte function

```
z^:?@2

```

Try it online!

If `y` is the argument, `z^:v` conditionally returns the result `z y` if `v y` returns `1`. Otherwise it returns `y` unchanged.

`? 2` will return 0 half the time and 1 half the time.

No matter what argument we pass to this function, it will be converted into the constant `2` and then passed to `z^:?`.

So half time the result will be `2`, and half the time it will error when trying to execute the non-existent verb `z`.

## alternative full programs

Though these may look like snippets they should count as full programs in the context of this challenge.

4 bytes thanks to Bubbler:

```
q:?2

```

5 bytes thanks to Adam:

```
0^.?2

```
> 6 votes

# Answer
# Python \<= 3.7, ~~25~~ 24 bytes

`lambda x:id(x.__dir__)`

Included for its weirdness rather than its brevity. This will cause a segmentation fault in obscure cases involving deep recursion. A fix is being applied, but only to python versions \>=3.8.

The crash only occurs on cleanup when *exiting* the interpreter, but an example of how to call this function (and reproduce the segfault) can be found here: Try it online!
> 6 votes

# Answer
# Lost -A, 9 bytes (Probability 1/2)

```
\\\\
%1-@

```

Try it online! Verification1

As an introduction to Lost for anyone unfamiliar, Lost is a 2-D programming language in which the start location and direction are selected at random at the beginning of the program. This source of randomness is what we use in this challenge.

We want some start locations that will cause an error and some that will not.

The program will error if it starts on the character `%` going right (or down). In this case it will encounter the ops `%1-@` before termination. This pushes `-1` and exits. Since `-1` is not a valid character code this causes an error in character mode.

The program will terminate safely if it starts on the character `%` going left (or up). In this case it will encounter the ops `%@` before termination. This does nothing and exits.

Since we have a path that errors and one that does not, all that remains is to know that every path terminates, which is guarenteed by the `\\\\`. So this program is valid.

We could shorten this significantly if there was not a termination requirement. The program :

```
%1-@

```

Try it online!

Either errors, terminates cleanly or loops forever, and it selects which at random with the following probabilities:

* **1/2** Non-terminating
* **1/4** Errors
* **1/4** Terminates cleanly

---

1: For verification we turn off character mode. All outputs containing negative numbers are the ones that will error in character mode.
> 5 votes

# Answer
# INTERCAL, 10 bytes

```
DO%9GIVEUP

```

The only way to terminate an INTERCAL program without an error is to execute a `GIVE UP` statement -- running off the end of the source code is a runtime error. This program uses INTERCAL's probabilistic execution feature to have a 9% chance of successfully exiting; the rest of the time, it errors out:

```
ICL129I PROGRAM HAS GOTTEN LOST
        ON THE WAY TO WHO KNOWS WHERE
        CORRECT SOURCE AND RESUBNIT

```
> 5 votes

# Answer
# C (gcc), ~~17~~ 16 bytes

Random across function calls.

Saved a byte thanks to newbie!!!

```
f(i){i/=rand();}

```

Try it online!

Has a \\$\frac1{\text{RAND\_MAX} + 1}\\$ chance of failing with `Floating point exception`.

**Random across runs.**

# C (gcc), 19 bytes

```
f(i){i/=(int)&i%3;}

```

Try it online!
> 4 votes

# Answer
# \>\<\>, 5 bytes

```
v
x+;

```

Try it online!

## Explanation

The pointer will be represented by a hashtag symbol. It will replace in bewteen these spaces:

```
v
x + ;

```

Ok, explanation start.

The instruction pointer goes down.

```
v*
x + ;

```

The step is randomized.

```
v
x*+ ;

```

Case 1: Error

```
v
x +*;

```

It tries to pop two items, but there is nothing on the stack. Cue error.

Case 2: Exit gracefully

```
v
x + ;*

```

It loops to the right side, and ends on the semicolon.
> 4 votes

# Answer
# APL (Dyalog Unicode), 3 bytes

```
÷?2

```

Try it online!

(Requires `IO←0`)

Inverse of random boolean (any range including 0 would work). I expect this'll be a common technique...

```
÷    ⍝ Inverse
 ?2  ⍝ Random number in [0,1]

```
> 4 votes

# Answer
# PowerShell, 10 bytes

```
1/(random)

```

Try it online!

`get-random` returns an int between 0 and 0x7FFFFFFF so it'll eventually divide by 0. Maybe...
> 4 votes

# Answer
# Google Sheets, 8 bytes

```
=0/RAND(

```

Google will a closing parentheses automatically to give `=0/RAND()`.

Since `RAND()` produces a uniformly random between 0 inclusive and 1 exclusive and to 15 decimal points of accuracy, is has a 0.0000000000001% chance of returning exactly 0 and causing the `#DIV/0!` error.
> 4 votes

# Answer
# Metatape, ~~4~~ 3 bytes

```
x?(

```

*-1 byte thanks to Hactar, the language creator, on Discord*

Initially, the tape head is within a tape and pointing to a null cell. The command `x` exits the current cell, creating a new tape and putting the initial tape within it. Now the tape head is within a tape and pointing at a tape.

The `?` command then generates a random bit, setting the current cell of the tape to null if it is `0` and doing nothing if it is `1`. Then the `(` command jumps to the next `|` or `)` characters in the code if and only if the current cell is null, and does nothing otherwise. Thus, if the bit generated by `?` is `0`, the interpreter will throw an error, as there is no `|` or `)` to jump to. On the other hand, Metatape does not implicitly check for every `(` matching with a `)`, so if the bit generated by `?` is `1`, no error will be thrown.

EDIT: After further clarification with the language's creator, I found that the last sentence I wrote may not apply to all interpreters, and thus this answer might not work for all interpreters. Oops.
> 4 votes

# Answer
# Z80 machine code, 6 5 bytes

I finally managed to reduce it to 5 bytes and also make it more well-behaved at the same time:

```
ED 5F B7 C0 76

```

Explanation:

```
ED 5F   LD A, R  ; get non-deterministic value (00-7F) from memory refresh register
B7      OR A, A  ; set Z flag if A is zero
C0      RET NZ   ; return normally, unless we were unlucky and got zero
76      HALT     ; halt the CPU

```

Alternatively to the `HALT` instruction `RST` could be used to call an error handler.

Other approaches that use 6 bytes and fail in a less well-behaved way:

---

```
ED 5F 17 32 06 00

```

Explanation:

```
ED 5F      LD A, R       ; get random value (00-7F) from refresh count register
17         RLA           ; rotate left one
32 06 00   LD (0006), A  ; write the byte immediately following this instruction.

```

There is a chance that this results in one of the conditional RET instructions to be written after the code, which returns normally if the condition happens to be met, which is the case for `RET NZ (C0)`, `RET NC (D0)`, `RET PE (E8)` and `RET M (F8)`. Otherwise, a random instruction is executed and the program counter runs into whatever is in RAM after that, failing horribly. If bit 8 of the R register was somehow set (which doesn't normally happen), or any instruction with an opcode up to 7F would somehow end the program normally, this could be reduced to 5 bytes. The address operand in the last instruction must be set relative to where the code is actually located.

---

```
ED 5F B7 28 FE C9

```

Explanation:

```
ED 5F   LD A, R  ; get non-deterministic value (00-7F) from memory refresh register
B7      OR A, A  ; set Z flag if A is zero
28 FE   JR Z, -2 ; infinite loop if Z-flag is set
C9      RET      ; return

```

An infinite loop might not really count as an 'error' though. An alternative solution (same length), inspired by Peter Cordes' x86 solution, is to mess with the return address:

---

```
E5 ED 5F AC 67 E9

```

Explanation:

```
E5      POP HL   ; get return address from stack
ED 5F   LD A, R  ; get non-deterministic value (00-7F) from memory refresh register
AC      XOR A, H ; this will only leave H intact
67      LD H, A  ;       if R was zero by chance
E9      JP HL    ; jump to (probably broken) return address

```
> 4 votes

# Answer
# Zsh, ~~8~~ 7 bytes, \\$ \approx \frac{1}{10}\\$ chance of success

```
>$$
<*4
```

Attempt This Online!

Determines whether the process ID ends in `4`.
> 4 votes

# Answer
# Jelly, 5 bytes

I haven't used Jelly for a long time, it's time for me to pick it up again.

```
2X’İX

```

Try it online!

# Explanation

```
2X    Pick random from [    1,  2]
  ’   Decrement:       [    0,  1]
   İ  Reciprocal:      [  inf,  1]
    X randrange 1      [Error,  1]

```
> 3 votes

# Answer
# Octave / MATLAB, 13 bytes

```
det(0:rand*2)

```

Try it online!

### How it works

`rand` produces a random number with uniform distribution between `0` and `1`. So the range `0:rand*2` may be `0` (1×1 matrix) or `[0 1]` (1×2 matrix). `det` tries to compute the determinant, which is only defined for square matrices.
> 3 votes

# Answer
# 05AB1E, 4 bytes

```
Î)ΩE

```

Try it online!

```
Î        Push 0 and input, ie. [0, ""] b/c input blank
 )       Wrap total stack to an array
  Ω      Push random element of a, ie. [0, ""]
   E     For-loop in [1 .. a]

```

where `a` is the top of the stack

Errors when `""` is randomly selected & for loop is attempted on it.
Proceeds when `0` is randomly selected & for loop is attempted on it.
> 3 votes

# Answer
# SQL (Oracle), 3733 Bytes

```
SELECT 1/INSTR(UID,3) FROM DUAL;

```

Fails if the User Session doesn't have a 3 in it. Edit: Was using SYSDATE, but UID is shorter. Although I'm kinda sad. I liked having a function that worked in March, but not February.
> 3 votes

# Answer
# , ~~15~~ 14 bytes

```
if(rexp(1)>1)a

```

Try it online!

R doesn't throw errors often. In particular, dividing by 0 doesn't lead to an error (`1/0=Inf`); nor does attempting to access an out-of-bounds entry in a vector (outputs `NA` with a warning). Two easy ways to get an error are: 1. an `if` statement gives an error if it is not fed a `TRUE`/`FALSE` value; 2. trying to access a non-existing object.

Here, if the random variate is \>1, we try to access `a` which doesn't exist, so R throws `Error: object 'a' not found`. If the random variate is \<1, nothing happens.

---

Previous version:

# , 15 bytes

```
if(T[rexp(1)])1

```

Try it online!

Here, `rexp(1)` generates a realization of the exponential distribution, i.e. a random value \\$x\in\mathbb R\_+\\$.

* if \\$x\<1\\$ then `T[x]` is an empty logical vector and R throws an `Error: argument is of length zero`
* if \\$1\leq x\<2\\$ then `T[x]` is `TRUE` and R outputs `1` without error
* if \\$2\leq x\\$ then `T[x]` is `NA` and R throws an `Error: missing value where TRUE/FALSE needed`

An error is thrown with probability \\$1-e^{-1}+e^{-2}\approx 0.767\\$.
> 3 votes

# Answer
## Compiled Stax, 28 27 25 bytes

Requires 116 TB RAM, and ulimit -s set to 116TB.

```
8000000000000{1-cy{}?}Y!

```

At present time, obvious ways to golf this fail to compile due to the compiler not supporting the requisite language feature.

This program attempts a recursive block invocation with a depth of 8000000000000, which in turn tries to create 8000000000000 16 byte stack frames on the runtime stack. This either succeeds or fails with probability of about .5 depending on how far apart the program and the top of the stack are in address space are.

I am using the environment's RNG that is actually documented to be random to make this fault or not fault.

And recursive said there's no such thing as nondetermistic stax.
> 3 votes

# Answer
# Taxi, 209 bytes

```
Go to Heisenberg's:w 1 r 3 r 1 l.Pickup a passenger going to Magic Eight.Pickup a passenger going to Magic Eight.Go to Magic Eight:s 1 r 1 l 3 r.Pickup a passenger going to Cyclone.Go to Taxi Garage:e 2 l 2 r.

```

Try it online!

Ungolfed and commented:

```
[ Heisenberg's produces random integers ]
Go to Heisenberg's:w 1 r 3 r 1 l.
[ Pickup two random integers ]
Pickup a passenger going to Magic Eight.
Pickup a passenger going to Magic Eight.
[ Magic Eight compares two numeric passengers ]
[ It returns the first passenger if it is less than the second and no one if it is not ]
Go to Magic Eight:s 1 r 1 l 3 r.
[ Try to pickup a passenger, which will error if there isn't anyone waiting ]
Pickup a passenger going to Cyclone.
[ Return to the garage to avoid getting the "you're fired" error ]
Go to Taxi Garage:e 2 l 2 r.

```

Try the ungolfed and commented version online!
> 3 votes

# Answer
# Knight, 3 bytes

```
/1R

```

Try it online!

Has a roughly \\$\frac{1}{65536}\\$ chance of dividing by zero.

The classic `1/rand()` trick. Assumes that dividing by zero throws an error, of course.

Uncommenting the line at the top of the header code will `srand` with a seed that will cause glibc's `rand()` to return `0xe7d0000`, which when masked by `0xFFFF`, results in `0`.
> 3 votes

# Answer
****\>\<\>, 4 bytes****

The **!** skips the next instruction, even if it would give an error. The **x** set the pointer's direction to a random direction. It can make it go up or down but if the pointer reaches the edge then it wraps around. The **;** ends the program. The **{** can be replaced with any character as long as it's not a valid command in \>\<\>.

```
!{x;

```

https://tio.run/##S8sszvj/X7G6wvr/fwA Try it online!
> 3 votes

# Answer
# C (clang), 24 bytes

```
main(i){i/=(time(0)%3);}

```

Try it online!

# C, 20 bytes

```
main(i){i/=time(0);};

```

Will crash once every +/- 68 years.

https://en.wikipedia.org/wiki/Year\_2038\_problem
> 3 votes

# Answer
# Aussie++, 78 bytes

```
G'DAY MATE!
IMPOHT ME FUNC ChuckSomeDice;
ChuckSomeDice(0,ChuckSomeDice(0,2));

```

Tested in commit 9522366.

`ChuckSomeDice` is the only way to get a random number, but it behaves a bit interestingly:

* If either argument is a finite non-integer, it's truncated to an integer.
* Inputs are capped to be no greater than 9223372036854775296.
* NaN is treated as 0.
* If both arguments (let's call them `x` and `y`) are integers, and `y` is greater than `x`, it gets a random integer in `[x, y)`.
* If `x` is less than `y`, it prints `OI MATE, CAN YA FUCKIN' COUNT?? START MUST BE LESS THAN END!!` to STDERR, but continues execution.
* If `x` is equal to `y`, it panics. See this Github issue.

The result is stored as a double, so calling e.g. `ChuckSomeDice(9223372036854775295, 1/0)` only ever produces either 9223372036854775000 or 9223372036854776000.

**TL;DR:** The arguments can't be equal, and behind the scenes it's likely casting between `i64` and `f64`.

So, I get either 0 or 1 randomly, and then get a random number between 0 and the result. If that was also 0, it panics. If that was 1, it returns 0.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 17 bytes

```
1/RandomInteger[]

```

Try it online!
> 2 votes

# Answer
# Pyth, 3 bytes

-1 thanks to FryAmTheEggman.

```
lO2

```

Try it online!
> 2 votes

# Answer
# Erlang (escript), 22 bytes

Just like the other answers...

```
f()->1/rand:uniform().

```

Try it online!
> 2 votes

# Answer
# Keg, 3 bytes

```
~~/

```

Try it online!

This works by pushing two random numbers onto the stack ane dividing them. If the second number is 0, then it errors out.

There is indeed a chance for the second number to be 0, but it is highly unlikely that it will be, as the random range used is quite large. But highly unlikely != zero.

If I were to estimate the odds of erroring out, I'd say it'd be something like 1 in `((int("9"*3234) ** 2) + 21) * 2`.
> 2 votes

# Answer
**Ruby, 9 bytes**

```
1/rand(2)

```

Try it online!
> 2 votes

# Answer
# C (gcc), 28 bytes

```
f(i){srand(&i);i/=rand()&1;}

```

Crashes approximately every other time it's run. Abuses ASLR.

Try it online!
> 2 votes

# Answer
# Bash, 1/32767 chance of success, 12 bytes

```
exit $RANDOM

```
> 2 votes

# Answer
# PowerShell Windows, 10 bytes

```
ps(random)

```

`get-random` returns an int between 0 and 0x7FFFFFFF so it'll eventually match some PID and `ps` will get the process that are running on the local computer. Maybe...

---

# PowerShell Linux, 11 bytes

```
gps(random)

```

`TIO` does not work because `System.UnauthorizedAccessException`. Please use your own `Powershell`. :)
> 2 votes

# Answer
# Batch, 11 bytes

```
%random:1=%

```

Has a probability of ~~1/65536~~ Corrected by @Neil, 5/32768 (~0.0015%) to not generate an error.

Edit: Alternatively,

```
%random:~1%

```
> 2 votes

# Answer
# Red - 24 bytes

```
x: now/time 1 / x/minute

```
> 2 votes

# Answer
# 05AB1E, 3 bytes

```
®ΩF

```

Try it online! Has a \\$\frac12\\$ chance of erroring.

```
®ΩF  # full program
  F  # for N in (0, ...
 Ω   # random element from...
®    # register_c (starts at -1)...
     # (implicit) split into separate characters...
  F  # ... - 1)...
     # (implicit) do nothing
     # (implicit) end loop

```

`-1` split into separate characters is `["-", "1"]`, so it picks a random element from there. Either it picks `1` and does nothing once, or it picks `-`, tries to loop `-` times, and crashes. Unlike `ï`, the built-in integer conversion function, it doesn't handle errors (if it can't be converted to an integer). So, it throws an error.
> 2 votes

# Answer
# Ahead, 4 bytes

50/50 chance of a divide by zero error. `X` causes the head to go in a random cardinal direction, `/` is obviously division, and `@` ends the program. Because of edge bouncing, the head traveling up or left is the same as it traveling down or right since it's in a corner.

```
X/
@

```

Try it online!
> 2 votes

# Answer
# Ruby, 10 bytes

```
1.div rand

```

Can't do `1/rand`, since 1/0.0 in Ruby is Infinity, not an error.

Try it online!
> 2 votes

# Answer
# Vyxal, 3 bytes

```
∆Ṙl

```

Try it Online!

I think this has a \\$\frac{1}{2^{19937}}\\$ chance of not erroring, but I'm not sure - Vyxal is written in Python, so it's whatever chance python's PRNG has of returning 0.
> 2 votes

# Answer
# Minim, 6 Bytes

```
[R*S].

```

Accesses memory at index **R**andomNumber *times* Memory**S**ize.

**R** is between **0** and **1** *inclusive*, and **S** is the memory scope size in elements. If **R = 1**, then the index will be out of bounds, and throws an error.

GitHub Repository
> 2 votes

# Answer
# JavaScript (Node.js), ~~17~~ ~~15~~ 14 bytes

```
new Date%2?a:0

```

Errors if current millisecond is odd

`new Date` returns current epoch time
`%2` modulo 2, returns 1 if odd, 0 if even
if it's a truthy value (1), `a` will throw as it's an undefined variable

Try it online!
> 2 votes

# Answer
# Japt, 3 bytes

Feck it, may as well post this. Similar in concept to but derived independently from Etheryte's solution. Predicated on the fact that JavaScript's `toString` method can only handle bases 2-36 so it, therefotre, has a 20% chance of throwing a `RangeError` (`toString() radix argument must be between 2 and 36`) - change the `A` to alter the odds of an error occurring.

```
sAö

```

Test it (errors are displayed below the output field)

```
sAö     :Implicit input of integer U, defaulting to 0
s       :Convert to string in base
 A      :  10
  ö     :  Random integer from range [0,A)

```
> 2 votes

# Answer
# Trilangle, 5 bytes

Contains invalid UTF-8, so I can't post it here. Instead, have a hexdump reversible with `xxd -r`:

```
00000000: 2437 40f7 2e                             $7@..

```

When reading the file, the interpreter starts by loading it as UTF-8 and converting it to a list of 24-bit integers (effectively UTF-32 on many machines due to struct padding). If it encounters an invalid UTF-8 sequence, it doesn't immediately error; rather, it takes that character as U+FFFD and keeps going. Once it's done, it makes the program length be a triangular number by appending `.` (U+002E) as necessary.

Currently, the interpreter stops with an error when it attempts to execute a character that isn't a valid opcode, but this behavior isn't specified. Any invalid opcode I choose could be added in the future, invalidating my answer.

Any character, that is, except for U+FFFD. When the interpreter attempts to execute `0xfffd`, it writes an error message to STDERR and exits with code 1:

```
Unicode replacement character (U+FFFD) detected in source. Please check encoding.

```

The sequence `f72e` is invalid UTF-8, so when the program is loaded in it looks like this:

```
  $
 7 @
� . .

```

The `$` instruction pushes a random integer to the stack, uniformly distributed in the range \[-8 388 608, 8 388 607\]. Then, `7` is a branch instruction based on the sign of the value on top of the stack. If the value is positive, the IP reaches the `@`, terminating the program gracefully. If the value is negative, the IP reaches the invalid character, triggering the encoding error.
> 2 votes

# Answer
# Pip, 4 bytes

```
VRCk

```

Attempt This Online!

### Explanation

`k` is a preinitialized variable containing the string `,` . `RC` chooses one of its characters at random, and `V` attempts to evaluate it as Pip code. If the space was chosen, the evaluation is successful and returns nil. If the comma was chosen, the interpreter crashes:

```
Fatal error during execution: Parsing error while evaluating ",": Hit end of tokens while parsing expression
Program terminated.

```
> 2 votes

# Answer
# brainfuck, 2 bytes

Sometimes segfaults, sometimes doesn't.

```
<.

```

Try it online!
> 1 votes

# Answer
## Windows Batch, 1715 bytes

```
set/a1/%random%
```
> 1 votes

# Answer
## VBA, ~~46~~ ~~42~~ ~~35~~ ~~25~~ 13 bytes

Thanks to @Taylor Scott

```
?1/Int(9*Rnd)

```

This code only works inside the Immediate Window.
> 1 votes

# Answer
# Befunge-98 (FBBI), 4 bytes

```
?@
=

```

Executing `=` is of the only ways I can get Befunge to actually error (a `/` won't work there because `0/0` evaulates to `0` in Befunge-98 and asks the user in Befunge-93).

Try it online!

The `?` turns the IP in a random direction. If it goes horizontally (1/2 chance), it hits the `@` and terminates successfully. If it goes vertically, it hits the `=` and uses the empty stack (interpreted as the empty string) as the argument. This throws a segfault in FBBI (which implements `=` as a C `system()` call).
> 1 votes

# Answer
# Jelly, 4 bytes

```
9XRy

```

Try it online!

Errors roughly 55% of the time

## How it works

```
9XRy - Main link. Takes no arguments
9X   - Generate a random number from 1 to 9
  R  - Get the range from 1 to that number
   y - Translate, by pairs

```

`y` splits a flat array `[a, b, c, d, ..., y, z]` into pairs, `[[a, b], [c, d], ..., [y, z]]`, then replaces `a` with `b`, `c` with `d` etc in the right argument. However, if there are an odd number of elements in the array, it attempts to pop from an empty list when doing the substitution, which errors.
> 1 votes

# Answer
# Japt, 3 bytes

Throws if seconds in a new date object are less than 2 or more than 36 since values outside of that range are not valid for base conversion in Japt.

```
sKb
s   // Try to convert the input to a string in base
 K  // new Date()
  b // get seconds.

```

Try it here.
> 1 votes

# Answer
# Java (JDK), 18 bytes

```
a->1/Math.random()

```

Try it online!

Well yeah, essentially the answer everyone gave but I didn't see Java yet. For the completeness.
> 1 votes

# Answer
# Perl 5, 10 bytes

```
1/(time%2)

```

Try it online!
> 1 votes

# Answer
# Pyt, 2 bytes

```
ɽ⅟

```

Try it online!

```
ɽ         gets a random 32-bit integer
 ⅟        takes the multiplicative inverse; implicit print

```

Errors on division by 0
> 1 votes

# Answer
# GolfScript, ~~12~~ 11 bytes

```
2rand{/}1if

```

Try it online!
> 1 votes

# Answer
# Fortran (GFortran), 16 bytes

```
j=1/mod(i,2)
end

```

Try it online!
> 1 votes

# Answer
# Volatile, 3 bytes

```
~~/

```

`~` pushes a random number onto the stack (which may include zero), and `/` pops two numbers and divides them. If the first `~` pushes a zero, then the program errors.
> 1 votes

# Answer
## (plain) pdfTeX, 34 bytes

```
\ifcase\pdfuniformdeviate9}\fi\bye

```
> 0 votes

# Answer
# Perl 5, 8 bytes

```
1/($$%2)

```

Here `$$` is current PID.

Try it online!
> 0 votes

# Answer
# Commodore BASIC (Commodore C64/128, VIC-20, C16/+4, PET, Ultimate64, THEC64 etc)

```
0 on6*rnd(.)goto10,20,30,40,50:goto
10 print"working":goto
20 print"working":goto
30 print"working":goto
40 print"working":goto

```

I've put a prompt in just to show that it does work sometimes too. Essentially, it breaks when the random number generated is rounded to 5 (it generates floating point numbers, but the BASIC interpreter ignores the decimal places).
> 0 votes

# Answer
# C (gcc), 30 bytes

```
main(){int*x=0x12345678;*x=1;}

```

Try it online!

Will segfault most of the time, but in the case that the program memory gets allocated to that address, it will NOT segfault.
> 0 votes

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


# Question
Title: Avoid repeating letters between five simple programs
Your challenge is to write 5 different full programs for the 5 following tasks:

1. Print `Hello, World!`.
2. Given an input on STDIN, output the factorial (you can assume that the input is an integer ≥ 0).
3. Given an integer N, calculate the sum of the primes ≤ N.
4. Given an input on STDIN, output the letters used in the input. For example: the input is `Hello world`, you need to output `helowrd`. Note that the output is in lowercase. You can assume that the input is always alphabetic with white spaces, the white spaces are ignored.
5. Output the following diamond exactly like this:
```
   *
  ***
 *****
*******
 *****
  ***
   *

```

All these challenges are probably very easy, but there is a catch. Every letter you use **cannot be used again** in the other programs. This is not prohibited, but will give you a penalty of **+8 bytes**. For example, if this is your program for the first task:

```
print("Hello, World!");

```

Then you cannot use the following letters (in uppercase or lowercase form): `p`, `r`, `i`, `n`, `t`, `h`, `e`, `l`, `o`, `w`, `d` in the other programs. If you do have to use them, you can “buy” each letter for 8 bytes. So if you want to use the letter `l` again in another program, you receive a penalty of 8 bytes. After you have paid the penalty, you can use each letter as many times as you want in *this* program. Other characters don’t matter. Also, all 5 programs should be in the same language.

This is a , least amount of bytes wins!

# Answer
# CJam, 73 bytes

```
"Obkkh+'Phukc&"7f^
q~m!
ri){'j3+_3++~},:+
lS-el_&
4{_' *4@-Y*('**+}%_1>W%\+N*

```

Each line is a full program. Try them online:  |  |  |  |

### Letter map

```
 bc  f h  k   op    u       18
            m   q            4
        ij       r          17
    e      l      s          7
             n        w y   27

```

If you want (and each of your programs fits in a line), you can use this CJam program to create a letter map for your own submission.
> 10 votes

# Answer
## Pyth, 90 bytes

First attempt...

### Task 1: 20 bytes

```
+"Hello, "+C87"orld!

```

### Task 2, 3 bytes

```
.!Q

```

### Task 3, 9 bytes

```
sf}TPTSvz

```

### Task 4, 6+8=14 bytes

```
@G{rw0

```

### Task 5, 44 bytes

```
"   *
  ***
 *****
*******
 *****
  ***
   *

```
> 4 votes

# Answer
# osascript, 759 Bytes

I knew this was going to be a lot when I started. o-o

**Task 1: 15 Bytes**

```
"Hello, World!"
```

I knew that it was going to be bad from this point.

**Task 2: 64 + 8\*4 = 96 Bytes**

```
on run a
set o to 1
repeat a
set o to a*o
set a to a-1
end
o
end
```

Oh gawd.

**Task 3: 170 + 8\*13 = 274 Bytes**

```
on run a
set o to 0
set t to false
repeat with i from 2 to a
set t to true
repeat with c from 2 to i-1
if i mod c=0 then set t to false
end
if t then set o to o+i
end
end
```

Dennis ≠ outgolfed.

**Task 4: 225 + 8\*13 = 329**

```
on run a
set o to""
repeat with i in items of a
repeat with c in characters of i
if c is not in o then
if ASCII number of c<91 then
set o to o&(ASCII character of(ASCII number of c+32))
else
set o to o&c
end
end
end
end
o
end
```

...

**Task 5: 45 Bytes**

```
"   *
  ***
 *****
*******
 *****
  ***
   *"
```

So, yeah. I knew I was gonna lose from the start. But it was interesting, I'd be interested to know if there's a way to do this in fewer characters. Character map (as provided by Dennis):

```
   de  h   l  o  r    w     15
a cdef hi  lmnop rstu w    160
a  de        nop rstu       57
abcdef hi  lmnop rstu w    214
                            39
                             0
```

The character count above is slightly off - newlines made it have issues, as the newlines were uncounted.

NOTE: The reason for not using stuff like `a's characters` or the like is that the `'` character has to be used when executing from the osascript command line. If I had used `'`, I'd have to use `\'` or something similar, which wouldn't have helped me at all. Also, it only recognizes `"` as string capturers, so I was kinda screwed there as well. But that was fun.
> 3 votes

# Answer
# Itr, 83 bytes, no characters repeated between programs

The five programs separated by newlines:

```
"Olssv'^vysk("7-

P

µf«äµL1=×S

32|ÍÌM64á<F¥

»   *
  ***
 *****
*******
 *****
  ***
   *

```

online interpreter:

*The letters in problem 4 are printed in alphabetical order instead of the order they appear in, I did not find any rule against that*

## Explanation

```
"Olssv'^vysk("7- ; Hello World! shifted by 7 to avoid space

P ; product over the 1-based range to the input

µf«äµL1=×S
µf«         ; replace the numbers in the range 1 : input with their prime-factorisation
   äµL1=×   ; only keep the elements with a length of one
         S  ; sum up the array

; assumes that the input consists of ASCII letters and white-spaces
32|ÍÌM64á<F¥
32|          ; or with 32 -> converts uppercase ascii to lowercase
   ÍÌ        ; get a list of all unique elements
     M64á<F¥ ; print the elements that are larger that 64 (filters out white spaces)
     M       ; for all elements
      64á<   ; is the the number greater than 64
          F  ; repeat that many times
           ¥ ; print

; string-literal containing the required output
; all possibilities to loop are used up by the previous answers
»   *
  ***
 *****
*******
 *****
  ***
   *

```
> 2 votes

# Answer
# NARS2000 APL, 144 bytes (85 characters)

## Task 1, 21 bytes (17 characters)

```
⎕←"Hello, World!"

```

## Task 2, 10 bytes (4 characters)

```
⎕←!⎕

```

## Task 3, 22 bytes (11 characters)

```
⎕←+/¯2π⍳2π⎕

```

## Task 4, 53 bytes (29 characters)

```
⎕←∪Q[26∣Q⍸⍞∩Q←⎕AV[97+⍳26]∪⎕A]

```

## Task 5, 38 bytes (24 characters)

```
⎕←" *"[1+4<∘.+⍨(⍳3),⊖⍳4]

```
> 1 votes

# Answer
# Jelly, 46 bytes (non-competing)

```
“3ḅaė;œ»
Ɠ!
ÆRS
ɠQḲŒl
4Ḷ¤‘+¤ṖṚṭ×”*Fµ4Ḷṭ4ḶṚṖ¤F×⁶+⁸Y

```

Try it online! (Copy/paste each snippet)

Apparently, the restriction did not restrict golfing :) Just suggestions for the last one, of course, please.
> 1 votes

# Answer
# Ruby `-rprime`, 398 bytes

I don't know why I decided to try this.

`-rprime` flag loads the `Prime` library for task 3. As per the meta post on program flags, adding flags treats it as a "different language", so I can't add `-n` or `-p` for some tasks and remove it for others, even if it would save bytes. (Tasks 1 and 5 take no input, and no input means programs with those flags won't run, which is why they can't be used.)

### Task 1, 47 bytes

Backslash-escaped almost every letter to free letters up for usage in later tasks. `$>` is an alias for `STDOUT`, which will be used later.

```
$><<"H\x65\154\154\x6f\54\40W\x6f\x72\154\x64!"

```

Attempt This Online!

### Task 2, 31 bytes

`3+9+~9 == 2` to avoid reusing `2`.

```
p((3+9+~9..gets.to_i).inject:*)

```

Attempt This Online!

### Task 3, 28 bytes + 56 (`().ceis`) = 84

Since this is the only task that doesn't say to take input from STDIN, this one is a lambda instead so I don't need to take a huge penalty from doing things with `gets.to_i` or something similar. This is probably the only time where `lambda` saves bytes over its stabby syntax `->`, which has to buy back `>` and uses up the `-` needed in Task 4.

```
lambda{|e|Prime.each(e).sum}

```

Attempt This Online!

### Task 4, 67 bytes + 96 (`*.<achinrstu`) = 163

This one had wayyyyyy too much overlap but it was needed to do the given task. Uses `t,=*STDIN` to get the line of input, assuming newlines won't be present. Let me know if that's an incorrect assumption.

```
t,=*STDIN;t=t.tr'A-Z','a-z';t=t.tr'^a-z','';STDOUT<<t.chars.uniq*''

```

Attempt This Online!

### Task 5, 53 bytes + 20 (`$*<>`) = 73

Buys back virtually every character in the program, since it's still cheaper than any alternative I could think of. Uses heredoc syntax for the string since we no longer have `'` or `"` and we're buying back `<` anyways since it's cheaper than buying back `puts`.

```
$><<<<Q
   *
  ***
 *****
*******
 *****
  ***
   *
Q

```

Attempt This Online!
> 0 votes

---
Tags: code-challenge, restricted-source, multiple-holes
---


# Question
Title: Given 4 fence lengths, what's the largest rectangular yard you can make?
Here's a very simple little problem that I don't believe has been asked before.

# Challenge

Write a program or a function that takes in four positive integers that represents the lengths of movable but unbreakable and unbendable straight fences. Output the area of the largest rectangular yard that can be fully encompassed with these fences.

The fences can be moved and rotated in increments of 90°, but can't overlap or be cut. Fences that just touch at a yard corner still count as encompassing the yard at that corner.

For example, given fence lengths 2, 8, 5, and 9, the best you can do is to make the 2 and 5 sides parallel, and the 8 and 9 sides parallel for a yard that is 2 by 8:

```
 888888885
2yyyyyyyy5
2yyyyyyyy5
9999999995
         5

```

Make any one side longer and the fences won't fully surround the yard. Thus the output here, the area of the yard, would be 16.

As another example, given 1, 1, 2, 2, the largest area yard that can be made is 2:

```
 22
1yy1
 22

```

A yard with area 1 like

```
22
1y1
 22

```

is a valid yard since it's perimeter is fully fenced, but 1 is an invalid output since it's not maximal.

This is so the shortest program wins!

You may *not* assume the 4 integer inputs to your program are in any particular order.

Here are some more test cases:

```
Inputs -> Output
1,1,1,1 -> 1
1,2,3,4 -> 3
4,3,2,1 -> 3
90,1,2,1 -> 2
1,90,1,1 -> 1
44,51,50,36 -> 1800
3,3,3,3 -> 9
3,3,3,4 -> 9
3,4,3,4 -> 12
4,4,3,4 -> 12
4,4,4,4 -> 16

```

# Answer
> 13 votes
# Python, 28 bytes

```
lambda*a:min(a)*sorted(a)[2]

```

It's an anonymous function that when called returns the answer, like `func(2,8,9,5) -> 16` or `func(1,1,2,2) -> 2`.

Unless I'm totally misunderstanding my own problem, I believe it can be solved by sorting the 4 input numbers and taking the smallest times the second biggest, since those sides will be matched parallel with the second smallest and the biggest respectively.

Like if the sorted inputs are `a <= b <= c <= d` then the biggest rect you can make will have area `a * c`, where side `a` is parallel to `b` and `c` parallel to `d`, and some of the `b` and `d` fences may have to be wasted.

(I'm a new user here so I'd love to know if this Python can be shortened at all. Thanks!)

# Answer
> 7 votes
# Vyxal `g`, 27 bitsv1, 3.375 bytes

```
sI÷*

```

Try it Online!

What I was thinking is that the side lengths can be split into two groups: those likely to be the long side of the rectangle and those likely to be the short side.

The long side of the rectangle will be the second most longest side, as it's guaranteed to be smaller or equal to than the other longer side.

The short side of the rectangle will be the shortest side, as it's guaranteed to be smaller than or equal to the other short side.

For example:

```
[2, 5, 8, 9]

```

The side length of 9 can't be the long side because there's no matching 9. But the side length of 8 can be because it's got that length in the 9. Hence, the second smallest length is the long side.

The side length of 5 can't be the short side, because there's no matching 5. But the side length of 2 can be because it's got that length in 5. Hence the smallest length is the short side.

## Explained

```
sI÷*
s    # sort the list ascending. The idea here is that the sides that are more likely to be the longer sides go to the end of the list and the ones likely to be the shorter sides go to the front.
 I    # split the list into two halves - [shorts, longs]
  ÷*  # dump each item onto the stack and multiply each item in shorts by each item in long.
# the g flag gets the smallest item of that list, which is also the first item.

```

# Answer
> 7 votes
# Ly, 7 bytes

```
&napfp*

```

Try it online!

Similar to other solutions, this sorts the numbers the messes with the stack to get the smallest and second largest. Then it multiples them to get the answer.

```
&n       - read in all the numbers
  a      - sort
   p     - discard top (largest)
    f    - flip two entries (pushes 2nd largest down)
     p   - discard top (3rd largest)
      *  - multiple what's left (smallest and 2nd largest)
         - exits and prints what's on the stack as a number

```

# Answer
> 7 votes
# Excel, 22 bytes

```
=MIN(A:A)*SMALL(A:A,3)

```

The `SMALL()` function finds the nth smallest number in a range.

# Answer
> 6 votes
# Nekomata, 4 bytes

```
o;*ṁ

```

Attempt This Online!

```
o;*ṁ
o       Sort
 ;      Nondeterministically split the list into two parts
  *     Multiply; fails if the two parts have different lengths
   ṁ    Take the minimum

```

# Answer
> 6 votes
# Julia, 24 21 **bytes**

-3 bytes: by @MarcMush

```
!a=(b=sort(a))[1]b[3]

```

Attempt This Online!

# Answer
> 5 votes
# Arturo, 20 bytes

```
$->a[sort'a a\0*a\2]

```

Try it

Sort the lengths then multiply the first by the third. Same algorithm as blaketyro arrived at independently.

# Answer
> 5 votes
# Bash \+ Linux utilities, 19

```
sort -n|dc -e??k?*p

```

Reads input from lines of STDIN.

### Explanation

```
sort -n              # sort numerically
       |             # pipe to ...
        dc -e        # ... dc expression
             ??      # push [1] and [2]
               k     # pop [2] to precision register (unused)
                ?    # push [3]
                 *   # pop and multiply [1] and [3]
                  p  # print

```

Try it online!

# Answer
> 5 votes
# Jelly, 4 bytes

```
Ṣm2P

```

A monadic Link that accepts a list of the four fence lengths and yields the maximal yard area.

**Try it online!**

### How?

```
Ṣm2P - Link: list of integers, F
Ṣ    - sort -> [a, b, c, d]
 m2  - modulo-2 slice -> [a, c]
   P - product -> a × c

```

# Answer
> 5 votes
# , 28 bytes

```
function(l)min(l)*sort(l)[3]

```

Try it online!

-2 bytes thanks to pajonk.

# , 30 bytes

```
function(l)prod(sort(l)[!0:1])

```

Try it online!

# Answer
> 4 votes
# , 8 bytes

```
]`*/@\:~

```

Attempt This Online!

Sort down, then reduce from the right by alternatingly taking the right value and multiplying:

```
    \:~2 8 5 9
9 8 5 2
    ]`*/9 8 5 2
9]8*5]2 -> 9]8*2 -> 9]16 -> 16

```

# Answer
> 4 votes
# Factor \+ `math.unicode`, 19 bytes

```
[ sort <evens> Π ]

```

Attempt This Online!

Sort the input, get the elements at even indices, then take the product.

# Answer
> 3 votes
# Retina, 26 bytes

```
N`
.+¶.+¶(.+)¶.+
$.($&*$1*

```

Try it online! Takes input on separate lines but link is to test suite that splits on commas for convenience. Explanation: Port of @blaketyro's Python answer.

```
N`

```

Sort numerically.

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

```

Multiply the first number by the third.

# Answer
> 3 votes
# Charcoal, 13 bytes

```
Ｉ×⌊θ⌈Φθ⁻κ⌕θ⌈θ

```

Try it online! Link is to verbose version of code. Takes input as a list of four elements. Explanation:

```
   θ            Input list
  ⌊             Take the minimum
 ×              Multiplied by
      θ         Input list
     Φ          Filtered where
        κ       Current index
       ⁻        Subtract i.e. is not equal to
            θ   Input list
           ⌈    Take the maximum
         ⌕      First index in
          θ     Input list
    ⌈           Take the maximum
Ｉ               Cast to string
                Implicitly print

```

# Answer
> 3 votes
# Scala, 25 bytes

Saved bytes thanks to the comments of @corvus\_192 and @user

---

Golfed version (25 bytes). Try it online!

```
a=>a.min*a.sorted.tail(1)

```

Alternative:

```
//scala 3
import scala.util.chaining._
def f(a:Int*):Int = a.sorted.pipe(a=>a(0)*a(2))

```

# Answer
> 3 votes
# Pyth, 5 bytes

```
*F%2S

```

Try it online!

### Explanation

```
*F%2SQ    # implicitly add Q
          # implicitly assign Q = eval(input())
    SQ    # sort Q
  %2      # take every other element (so first and third)
*F        # reduce on multiplication

```

# Answer
> 3 votes
# Thunno 2 `M`, 4 bytes

```
Ṡz€p

```

Attempt This Online!

#### Explanation

```
Ṡz€p  # Implicit input
Ṡ     # Sort in ascending order
 z    # Uninterleave ([a, b, c, d] -> [[a, c], [b, d]])
  €p  # Product of each inner pair
      # Implicit output of minimum (M flag)

```

# Answer
> 2 votes
# 05AB1E, 4 bytes

```
{ιPß

```

Try it online or verify all test cases.

**Explanation:**

```
{     # Sort the (implicit) input-quartet from lowest to highest
 ι    # Uninterleave it into two parts: [a,b,c,d]→[[a,c],[b,d]]
  P   # Get the product of both inner lists
   ß  # Get the minimum of this pair
      # (which is output implicitly as result)

```

# Answer
> 2 votes
# Japt `-g`, 5 bytes

```
Íó Ë×

```

Try it or run all test cases

```
Íó Ë×     :Implicit input of array
Í         :Sort
 ó        :Uninterleave
   Ë      :Map
    ×     :  Reduce by multiplication
          :Implicit output of first element

```

# Answer
> 2 votes
# Desmos, 19 bytes

```
f(l)=l.minl.sort[3]

```

Try It On Desmos!

Port of literally all the other answers here.

# Answer
> 2 votes
# Perl 5 `-pa`, 30 bytes

```
$_=(@F=sort{$a-$b}@F)[0]*$F[2]

```

Try it online!

# Answer
> 2 votes
# Ruby, 21 bytes

```
->*l{l.sort![2]*l[0]}

```

Try it online!

Nothing particularly original here.

# Answer
> 2 votes
# C (gcc), 59 bytes

```
g(a,b)int*a,*b;{b=*a-*b;}f(int*l){qsort(l,4,4,g);*l*=l[2];}

```

Try it online!

Takes a 4-element integer array as input and stores the result in the first element of that array. It can probably be shortened, but it's still one of my better submissions :)

Explanation:

```
// This will be used as a comparison function for qsort(), so that
// integers can be sorted in ascending order.
g(a,b)int*a,*b;
{
    b=*a-*b;
}

f(int*l)
{
    // Sort l, assuming it has 4 elements with element size 4 (which is usually
    // the size of integers in bytes), and using g() as a comparator.
    qsort(l,4,4,g);

    // Stores the first (minimum) element of l times the second-largest element
    // in the first element of l.
    *l*=l[2];
}

```

46-byte version using some complicated flag (`-zexecstack`), suggested by @ceilingcat:

```
f(int*l){qsort(l,4,4,"\x8b\7+\6ð");*l*=l[2];}

```

Try it online!

# Answer
> 2 votes
# BQN, 7 bytes

```
×´0‿2⊏∧

```

Try it

```
      ∧ # ascending sort
  0‿2⊏  # select first and third elements
×´      # product

```

# Answer
> 1 votes
# Lua, 35 bytes

```
table.sort(arg)print(arg[1]*arg[3])

```

Try it online!

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