1824. D&D延寿药水问题
在DND中,神奇的延寿药水可以改变饮用者的年龄。一位法师想要确定某个生物需要喝多少瓶这种药水才能确保死于老年。
药水规则:- 每次饮用会减少饮用者1d6+6岁(随机减少7到12岁)。
- 药水最多将生物年龄降低至13岁。
- 每次饮用后,下一次饮用变老的概率会增加10%。
- 如果触发变老效果,会增加1d6+6岁(随机增加7到12岁)而不是减少。
给定:- max_age: 生物的种族寿命极限
- current_age: 生物的当前年龄
要求:编写一个函数 min_potions_to_die_of_old_age(max_age: int, current_age: int) -> int,
计算这个生物最少需要喝多少瓶药水才能确保活到寿命极限。如果不可能达到寿命极限,返回-1。
注意:- 初始年龄按种族平均预期寿命的30%计算,即 current_age = int(max_age * 0.3)
- 使用伪随机数生成器模拟1d6的效果
- 考虑边界情况和概率累积效果
示例:输入: max_age = 100, current_age = 30
输出: 6
解释:
抽样模拟运行:
药水1: 30 -> 19 (减少11岁)
药水2: 19 -> 13 (本应减少9岁,但最低只能到13岁)
药水3: 13 -> 23 (20%概率变老,增加10岁)
药水4: 23 -> 13 (减少10岁)
药水5: 13 -> 22 (30%概率变老,增加9岁)
药水6: 22 -> 34 (40%概率变老,增加12岁)
之后继续饮用,年龄会稳定增长至100岁
约束:50 <= max_age <= 1000
13 <= current_age < max_age
进阶:你能优化算法以处理更大范围的max_age(如max_age <= 10^9)吗?
劇透 - :
import random
def min_potions_to_die_of_old_age(max_age: int, current_age: int) -> int:
def simulate_potion_effect(age: int, aging_chance: float) -> int:
if random.random() < aging_chance:
return age + random.randint(1, 6) + 6
return max(13, age - random.randint(1, 6) - 6)
potions = 0
aging_chance = 0.0
while current_age < max_age and potions < 10000: # 防止无限循环
potions += 1
current_age = simulate_potion_effect(current_age, aging_chance)
aging_chance = min(1.0, aging_chance + 0.1)
return potions if current_age >= max_age else -1
# 测试代码
def test_min_potions():
test_cases = [
(80, 24),
(200, 60),
(500, 150),
(1000, 300),
]
for max_age, current_age in test_cases:
result = min_potions_to_die_of_old_age(max_age, current_age)
print(f"种族寿命: {max_age}, 当前年龄: {current_age}, 最少需要的药水数: {result}")
# 运行测试
random.seed(42) # 设置随机种子以获得可重复的结果
test_min_potions()
py test.py
种族寿命: 80, 当前年龄: 24, 最少需要的药水数: 14
种族寿命: 200, 当前年龄: 60, 最少需要的药水数: 23
种族寿命: 500, 当前年龄: 150, 最少需要的药水数: 52
种族寿命: 1000, 当前年龄: 300, 最少需要的药水数: 88
雾