File size: 1,178 Bytes
ff93ece
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import gradio as gr
import numpy as np
import plotly.graph_objects as go


# N sequences, each with n coinflips.
# for each sequence, determine the length of the longest constant 0 interval.
def histogram(N, n):
    data = np.random.binomial(size=(N, n + 2), n=1, p=0.5)
    # putting 1s at both ends as barriers:
    data[:, 0] = 1
    data[:, -1] = 1

    ks = []
    for i in range(N):
        seq = data[i]
        ones = np.nonzero(seq)[0]
        jumps = np.diff(ones)
        k = np.max(jumps) - 1
        ks.append(k)
    return np.array(ks)


def visualize(x):
    x_range = int(np.max(x) - np.min(x) + 1)
    fig = go.Figure(data=[go.Histogram(x=x, marker=dict(color='#7A88CC'), nbinsx=x_range)])
    fig.update_layout(title='length of longest row of heads', xaxis_title='length k', yaxis_title='count')
    return fig


def update(N, n):
    return visualize(histogram(N, n))


demo = gr.Interface(update,
    inputs = [
        gr.Slider(0, 10000, value=1000, label="N, the number of simulations"),
        gr.Slider(0, 1000, value=50, label="n, the number of coin flips in a simulation"),
    ],
    outputs = ["plot"],
    live=True)


demo.launch(show_api=False)