这是一个非常简单的骰子游戏,规则如下:
- 选择 1 到 100 之间的数字
- 同时作用三个骰子
使用滚动点和以下选项尽可能接近所选数字:
- 加法、减法、乘法和/或
- 将点乘以 10
示例 1:
Dice1 = 2, Dice2 = 3, Dice3 = 1, Chosen number = 5
Possible calculations:
2 + 3 * 1 = 5 or
2 * 3 - 1 = 5
示例 2:
Dice1 = 6, Dice2 = 2, Dice3 = 2, Chosen number = 42
Possible calculation:
(6*10) - (2*10) + 2 = 42
我的程序的目标是找到组合点和运算符的最佳方法。
到目前为止我所拥有的:
import sys
import operator
a = int (sys.argv[1]) # Dice 1
b = int (sys.argv[2]) # Dice 2
c = int (sys.argv[3]) # Dice 3
d = int (sys.argv[4]) # Number to reach
class Calc():
def __init__(self):
self.resultsdict = dict()
self.werte = dict()
permutations = [[a,b,c], [a,c,b], [b,a,c], [b,c,a], [c,a,b], [c,b,a]]
for p in permutations:
aa = int(p[0])
bb = int(p[1])
cc = int(p[2])
self.compute(aa,bb,cc, d)
self.getBest(d, a, b, c)
def compute(self, a,b,c,d):
func = [a+b+c, a+b-c, a+b*c, (a+b)*c, (a-b)+c, a-(b+c), a-b-c, a-b*c, (a-b)*c, a*b+c, a*(b+c), a*b-c, a*(b-c), a*b*c]
func1 = ["a+b+c", "a+b-c", "a+b*c", "(a+b)*c", "(a-b)+c", "a-(b+c)", "a-b-c", "a-b*c", "(a-b)*c", "a*b+c", "a*(b+c)", "a*b-c", "a*(b-c)", "a*b*c"]
i = 0
while i < len(func):
dictkey = str(a)+str(b)+str(c)+ ", " +str(func1[i])
if not func[i] < 0 :
self.resultsdict[dictkey] = abs(d-func[i])
self.werte[dictkey] = func[i]
i += 1
def getBest(self, d, d1, d2, d3):
self.bestresults = dict()
keys = self.resultsdict.keys()
minval = 1000000000
for k in keys:
if int(self.resultsdict[k]) <= int(minval):
minval = int(self.resultsdict[k])
print("THE BEST COMBINATION FOR REACHING " + str(d) + " WITH " + str(d1) + ", " + str(d2) + ", " + str(d3) + " HAS BEEN GAINED WITH REST: " + str(minval))
for k in keys:
if int(self.resultsdict[k]) == int(minval):
ergebnis = self.werte[k]
print('\t' + "Combination: " + str(k) + ", Result: " + str(ergebnis))
t = Calc()
在 func 中,我对可能组合的一部分进行了硬编码。
现在我正在寻找一种自动生成这些组合的算法,这样我就不必手动将它们全部写下来。
你会怎么做?