(蟒蛇) 平均分配数字

2024-10-04 17:21:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我为标题道歉。如果有人能想到更具描述性的标题,请告诉我,我会转载这个问题,或编辑标题。(如有可能) 你好,我正在做一个游戏。当发起攻击时,攻击者有一个潜在的资源编号,他可以从其他玩家那里获得。如果防守方有足够的资源,我很难弄清楚如何将这些资源平均分配给攻击者。在

#this is how many resources the attacker can get, def's resources
attacker_potential = 250
#this is how many resources the defender has
defender.wood = 100
defender.iron = 25
defender.wheat = 76
defender.gold = 50000
#then the attacker would make off with 
attacker.wood += 75
attacker.iron += 25
attacker.wheat += 75
attacker.gold += 75

另一个例子:

^{pr2}$

下面是另一个例子:

defender.wood = 100
defender.iron = 0
defender.wheat = 1
defender.gold = 0
#attacker would make off with:
attacker.wood += 100
attacker.iron += 0
attacker.wheat += 1
attacker.gold += 0

最后一个例子是:

defender.wood = 50000 #pretend the rest are 0
attacker.wood += 250 

(当我计算出攻击者得到多少资源时,剩下的计算就很容易了)。 我刚刚在代码中达到了这一点,我花了整整20分钟试图弄清楚它是如何工作的。不过,我觉得答案可能很简单。在


Tags: the标题is资源this例子howresources
2条回答

整数资源的循环。如果确实要拆分资源,可以检查剩余资源的总量是否小于资源的数量,然后平均拆分。在

def distribute(potential, defender_resources):
    attacker_resources = [0] * len(defender_resources)

    while potential and any(defender_resources):
        for i in range(len(defender_resources)):
            if potential and defender_resources[i]:
                defender_resources[i] -= 1
                attacker_resources[i] += 1
                potential -= 1

    return attacker_resources

print distribute(250, [100,0,1,0])
print distribute(250, [100,25,76,5000])
print distribute(250, [2500,2500,2500,2500])
print distribute(250, [5000])

一种与您介绍的示例相一致的算法如下:

  1. 让平均战利品是攻击者的潜力除以防御者的非零资源。循环查看防御者的非零资源,如果其中任何资源小于或等于平均战利品,则将其从防御者中移除并交给攻击者。

  2. 如果在步骤1中遇到并移动了小于或等于平均战利品的资源,则重新计算平均战利品并重复步骤1。否则,继续执行步骤3。

  3. 如果防御者有剩余资源,最后再计算他们的资源。

python中可能的实现如下:

def step1(dres, aloot, potential):

    again = False

    ndres = {}

    if len(dres) > 0:

        avgloot = int(potential / len(dres))

        for r in dres:
            if dres[r] <= avgloot:
                potential -= dres[r]
                aloot[r] += dres[r]
                again = True
            else:
                ndres[r] = dres[r]

    return (ndres, aloot, potential, again)

def calculate_loot(dres, potential):

    aloot = {'wood':0, 'iron':0, 'wheat':0, 'gold':0}

    (dres, aloot, potential, again) = step1(dres, aloot, potential)

    while again:
        (dres, aloot, potential, again) = step1(dres, aloot, potential)

    if len(dres) > 0:
        avgloot = int(potential / len(dres))
        for r in dres:
            aloot[r] += avgloot

    return aloot

potential = 250

for dres in [
        {'wood':100,  'iron':25,   'wheat':76,   'gold':50000},
        {'wood':2500, 'iron':2500, 'wheat':5000, 'gold':5000 },
        {'wood':100,  'iron':0,    'wheat':1,    'gold':0    },
        {'wood':0,    'iron':0,    'wheat':0,    'gold':50000}
    ]:

    print(dres)
    print(calculate_loot(dres, potential))
    print(' ')

Online Demo

相关问题 更多 >

    热门问题