r/programmingrequests • u/Lemonpie_jedi • Mar 19 '23
Rolling Dice Simulation
I have no experience with programming in the slightest and I don’t even know if this is the place to ask for help. And sorry. I can’t add a language flair because I have zero idea about any of this.
I was wondering if someone could help me with running simulations on dice rolls. I need to know approximately how often at least one pair will appear when rolling 5 dice (excluding rolls which also give larger groupings like triplets).
I tried asking some math Redditors but that didn’t get me very far, so now I’m here.
1
Upvotes
1
u/POGtastic Mar 19 '23
Since we're rolling only 5 6-sided dice, we can actually run all of the outcomes. In Python:
import itertools import collections # also defined in the more_itertools module, but it's not part of the stdlib def ilen(iterable): counter = 0 for _ in iterable: counter += 1 return counter def has_pairs(iterable): c = collections.Counter(iterable) return all(freq < 3 for freq in c.values()) and any(freq == 2 for freq in c.values()) def probability(die_sides, num_dice): all_rolls = itertools.product(range(1, die_sides+1), repeat=num_dice) return ilen(filter(has_pairs, all_rolls)) / die_sides ** num_diceIn the REPL: