Skip to content

Instantly share code, notes, and snippets.

@V-FEXrt
Created August 15, 2024 01:40
Show Gist options
  • Select an option

  • Save V-FEXrt/85cdf412765bdd2e022a9400f27a2930 to your computer and use it in GitHub Desktop.

Select an option

Save V-FEXrt/85cdf412765bdd2e022a9400f27a2930 to your computer and use it in GitHub Desktop.
import math
import multiprocessing
import random
# Rolls 231 d4 and returns the total number of 1s
def roll():
ones = 0
for i in range(231):
# Returns a 2 bit random binary number (00, 01, 10, 11) => 1, 2, 3, 4
if random.getrandbits(2) == 0:
ones += 1
return ones
# Attempt *count* roll sessions and return the highest result
def attempt(count):
maxOnes = 0
for i in range(count):
r = roll()
if r > maxOnes:
maxOnes = r
return maxOnes
# Entry point of the program
def main():
# 1 Billion
goal = 1000000000
# This number should be the number of cores on the machine
# Most laptops have between 4 and 16
cores_on_machine = 48
# Set up parallel tasks. Put one task on each core
pool = multiprocessing.Pool(processes=cores_on_machine)
# Determine how much work per core, try to split evenly
per_core = int(goal / cores_on_machine)
# Goal might not be divisble by the number of core. Grab the missing count here
extra_missing = goal - (per_core * cores_on_machine)
# Assign the work to each core
inputs = [per_core] * cores_on_machine
inputs[0] = inputs[0] + extra_missing
# Do the work
outputs = pool.map(attempt, inputs)
# Grab the max result from among all the cores
maxOnes = max(outputs)
# Print out the summary
print("Highest Ones Roll:", maxOnes)
print("Number of Roll Sessions: ", sum(inputs))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment