我正在嘗試為 Yahtzee(骰子游戲)建模。
作為第一步,我試圖列舉同時擲出的 5 個骰子的所有可能組合。我只想要獨特的組合(例如5,5,5,4,4,與等相同5,5,4,5,4)。在 Python、C 或 Mathematica 中是否有一種簡單的方法可以做到這一點?
uj5u.com熱心網友回復:
您可以itertools.combinations_with_replacement()在 Python 中使用:
from itertools import combinations_with_replacement
options = list(range(1, 7))
print(list(combinations_with_replacement(options, 5)))
uj5u.com熱心網友回復:
使用的解決方案itertools.combinations_with_replacement幾乎可以肯定是最好的(無論如何在 Python 中),因為它既快速又易于使用。但是解決這個問題的遞回演算法是如此簡單和漂亮,不展示它會很可惜。
為了確保卷的組合是唯一的,我們只需要按排序順序生成它。每個卷的組合都有一個唯一的排序,我們可以通過始終附加一個新值來生成每個排序的組合,該值至少與組合中的前一個值一樣大。
將其翻譯成 Python:
def rolls(n, k=6):
'''Generate distinct rolls of n k-sided dice'''
if n:
for i in range(k, 0, -1):
for roll in rolls(n-1, i):
yield roll [i]
else:
yield []
這會以反向 colex 順序生成組合,盡管可以通過將范圍更改為range(1, k 1).
uj5u.com熱心網友回復:
這將列出 Mathematica 中的所有 252 個排列。
Union[Sort /@ Tuples[Range[6], {5}]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438325.html
