0

I've created a program that runs the hat check problem 100,000 times. It works like this:

  • There are 10 people
  • Each person rolls a random number between 1-10 inclusive
  • If roll == their index, then that person 'receives' his hat back
  • At end of each trial, number of people who received their hat back is appended to list
  • Trial is repeated 100,000 times
  • Results are plotted on a histogram to show how many 0 people received their hat back, 1 person received hat back, 2 people, 3 people... 10 people received their hat back.

enter image description here

As you can see in the above histogram though, the x-axis labels aren't centered in the middle of each bar. Moreover, there's a gap between 2 and 3 that shouldn't be there.

Why is this??

Code:

import matplotlib.pyplot as plt
from random import randint

# Define constant N for number of people
N = 10

# Define constant E for number of experiments
E = 100000

# Define list of number of ppl who got their hat back after each experiment
trials = []

# Run experiement E times
for i in range(E):

    # Initialise r as number of people who had their hat returned
    r = 0

    # Loop through each person in N
    for i in range(1, N+1):

        # Each person rolls a random number
        roll = randint(1, 10)

        # If roll equals to i, then ith person received his hat back. So increment r by 1
        if roll == i:
            r += 1

    # Append how many ppl got their hat returned after each trial
    trials.append(r)

print(trials)

# Create histogram
plt.hist(trials, 10, rwidth=0.8)

# Show histogram
plt.show()
doctopus
  • 5,349
  • 8
  • 53
  • 105

0 Answers0