引言
我报名参加了 Prosperity 2 交易挑战赛,花在上面的时间恐怕远比该花的多。我负责我们队所有的手动交易轮次,到目前为止(已经打了 4 轮),每一轮我都是靠批量跑 Python 暴力破解的。
想在这里分享一下我的解法,欢迎发邮件到 davidfeng@uchicago.edu 给我反馈。
第一轮
官方网站上的交易目标(点击展开)
一大群金鱼来到了我们的海岸,而且都带着想要尽快脱手的水肺潜水装备。当然,前提是价格合适。
你只有两次机会报出一个好价格。每条金鱼都会接受高于其保留价的最低出价。群岛上对潜水装备的需求一直都在。因此,在本轮结束时,你能够以每件 1000 贝壳币(SeaShells)的价格把它们卖掉。你的目标是设定价格,确保与尽可能多的金鱼达成有利可图的交易。
对自己的策略和输入感到满意之后,点击“Submit manual trade”(提交手动交易)按钮将其锁定。注意,只要本轮仍在进行,你就可以(重新)提交新的策略。本轮一结束,系统就会处理你最后提交的交易策略。
祝你好运,交易愉快!
Wiki 上的说明(点击展开)
一大群金鱼到访,带来了购入顶级潜水装备的机会。你只有两次机会报出一个好价格。每条金鱼都会接受高于其保留价的最低出价。你知道,群岛上对潜水装备的需求一直都在。因此,在本轮结束时,你能够以每件 1000 贝壳币的价格把它们卖掉。
虽然并非每条金鱼的保留价都相同,但你知道它们保留价的分布。保留价不会低于 900,也不会高于 1000。概率从 900 处的 0 开始线性上升,到 1000 处可能性最大。
你只与金鱼交易。其他参与者的出价不会影响你的结果。
好好想想该怎么设定你的两个出价,才能带着一大笔贝壳币利润离场。
第一轮解析
这道题不算特别难,最难的部分大概是讲清楚利润是怎么算的。简单总结如下:
我们设定两个出价 / 价格,一低一高
从所有愿意接受较低出价的金鱼手里买入
- 如果低出价为
a,那么我们会从所有保留价p <= a的金鱼手里买入 - 我们付的是自己的出价
a,而不是金鱼的保留价p,因此每笔交易获利1000-a
- 如果低出价为
从所有愿意接受较高出价的金鱼手里买入
- 如果高出价为
b,那么我们会从所有保留价a < p <= b的金鱼手里买入(p <= a的金鱼已经卖掉了) - 我们付的是自己的出价
b,而不是金鱼的保留价p,因此每笔交易获利1000-b
- 如果高出价为
简而言之,我们先买下低于低出价的所有装备,然后再买下低于高出价的所有装备。
理解了这一点,直接用蒙特卡洛方法模拟结果就很简单了。注意,我们可以用 numpy.random.triangular 函数从给定的分布中抽样,把 left(下限)设为 900,把 mode(众数)和 right(上限)都设为 1000。下面这段摘自 NumPy 官方文档:
random.triangular(left, mode, right, size=None)
在区间 [left, right] 上,从三角分布中抽取样本。
三角分布是一种连续概率分布,下限为 left,峰值位于 mode,上限为 right。与其他分布不同,这些参数直接决定了概率密度函数(pdf)的形状。
基于以上信息,我们运行了 200 次模拟,每次模拟 10,000 条金鱼,并记录下最佳的一组出价。输出如下:
Lower Bid Statistics
Min: 945,
Max: 957,
Median: 952.0,
Average: 951.61,
Std Deviation: 2.5880301389280613
----------
Higher Bid Statistics
Min: 972,
Max: 983,
Median: 978.0,
Average: 978.125,
Std Deviation: 1.8545552027373033
第一轮代码
完整展开的代码太占地方,所以我把每个代码单元格都做成了可展开的。如果不想逐个复制粘贴,这里有一个包含全部内容、可以直接运行的 Colab Notebook。
定义常量
N_SIMULATIONS = 200 # Number of simulations to run
PRICE = 1000 # Selling price per scuba gear
MIN_RESERVE_PRICE = 900 # Minimum reserve price of the goldfish
MAX_RESERVE_PRICE = 1000 # Maximum reserve price of the goldfish
N_GOLDFISHES = 10000 # Number of individuals to model in each simulation for precision
导入库
import numpy as np
import matplotlib.pyplot as plt
辅助函数
# Function to simulate bids and calculate profits
def simulate_bids(verbose = True):
best_pair = (0, 0) # To store the best bid combination
best_profit = 0 # To store the maximum profit found
# Iterate through all possible combinations of bids within the valid range
for low_bid in range(MIN_RESERVE_PRICE, MAX_RESERVE_PRICE):
for high_bid in range(low_bid + 1, MAX_RESERVE_PRICE + 1):
profit = 0 # Reset profit for each bid combination
# Simulate each goldfish's reserve price
for reserve_price in np.random.triangular(MIN_RESERVE_PRICE, MAX_RESERVE_PRICE, MAX_RESERVE_PRICE, N_GOLDFISHES):
# Check if the goldfish will accept the low bid
if reserve_price <= low_bid:
profit += (PRICE - low_bid)
# Check if the goldfish will accept the high bid
elif reserve_price <= high_bid:
profit += (PRICE - high_bid)
# Update best bid combination if the current one is more profitable
if profit > best_profit:
best_profit = profit
best_pair = (low_bid, high_bid)
if verbose:
print(f"\rProfit:{profit}\tLow:{low_bid}\tHigh:{high_bid}", end = "")
return best_pair, best_profit
# Function to print statistics given an array like input
def summary_stats(arr, name = ""):
print("\n" + "-"*10)
if name:
print(name)
print((
f"Min: {np.min(arr)},\n"
f"Max: {np.max(arr)},\n"
f"Median: {np.median(arr)},\n"
f"Average: {np.mean(arr)},\n"
f"Std Deviation: {np.std(arr)}"
), end = "")
验证 "np.random.triangular" 给出的分布符合预期(可选)
h = plt.hist(
np.random.triangular(MIN_RESERVE_PRICE, MAX_RESERVE_PRICE, MAX_RESERVE_PRICE, N_GOLDFISHES),
bins=200,
density=True
)
plt.show()
运行模拟
#@title Run Simulation
small_bids = []
large_bids = []
profits = []
for i in range(N_SIMULATIONS):
print(f"\n{i+1}/{N_SIMULATIONS}")
pair, profit = simulate_bids()
small_bids.append(pair[0])
large_bids.append(pair[1])
profits.append(profit)
summary_stats(small_bids, "Lower Bid Statistics")
summary_stats(large_bids, "Higher Bid Statistics")
summary_stats(profits, "Max Profit Statistics")
第二轮
官方网站上的交易目标(点击展开)
今天是个特别的日子。来自另外三个群岛的代表到访,要与我们交易他们的货币。你可以和鸣鸟 Sing 交易山葵根(Wasabi Root),和鸭子 Devin 交易披萨片(Pizza Slice),和企鹅 Pam 交易雪球(Snowball)。
你的目标是交易这些货币,让你以贝壳币计算的利润最大化。交易次数最多为 5 次。第一笔交易必须从我们自己的货币——贝壳币(SeaShells)——开始,最后一笔交易也必须以它结束。请利用交易表来制定你的交易策略,再用下拉框把策略转化为可执行的输入。对自己的策略和输入感到满意之后,点击“Submit manual trade”(提交手动交易)按钮将其锁定。
注意,只要本轮仍在进行,你就可以(重新)提交新的策略。本轮一结束,系统就会处理你最后提交的交易策略。
祝你好运,交易愉快!
Wiki 上的说明(点击展开)
你有机会用几种外岛货币进行一系列交易。第一笔交易是把你的贝壳币兑换成外币,最后一笔交易是把外币兑换回贝壳币。中间的一切都由你决定。好好想想要做怎样的一系列交易,因为你或许有机会带着比来时更多的贝壳离开。
第二轮解析
这是目前为止最简单的一轮。我们只需要在所有货币 / 商品上暴力枚举,把空填上:
Seashell -> [?] -> [?] -> [?] -> [?] -> Seashell
要注意的是,我们不一定要做满 5 笔交易,所以还要在以下几种情形中求最大值:
Seashell -> [?] -> [?] -> [?] -> Seashell
Seashell -> [?] -> [?] -> Seashell
Seashell -> [?] -> Seashell
每个未知的空有 4 种可能,因此总共有
种可能,我们要从中选出使最终贝壳数量最大的那一种。
最终输出如下:
Best 4 trades: Shell -> Pizza Slice -> Wasabi Root -> Shell -> Pizza Slice -> Shell
Best profit: 1.0569693888
We start with 2000 Shells.
Then we trade Shell to Pizza Slice at 1 Shell : 1.41 Pizza Slice.
Thus we have 2000 * 1.41 = 2820.0 Pizza Slices
Then we trade Pizza Slice to Wasabi Root at 1 Pizza Slice : 0.48 Wasabi Root.
Thus we have 2820.0 * 0.48 = 1353.6 Wasabi Roots
Then we trade Wasabi Root to Shell at 1 Wasabi Root : 1.56 Shell.
Thus we have 1353.6 * 1.56 = 2111.616 Shells
Then we trade Shell to Pizza Slice at 1 Shell : 1.41 Pizza Slice.
Thus we have 2111.616 * 1.41 = 2977.3785599999997 Pizza Slices
Then we trade Pizza Slice to Shell at 1 Pizza Slice : 0.71 Shell.
Thus we have 2977.3785599999997 * 0.71 = 2113.9387776 Shells
Finally, we end up with 2113.9387776 Shells.
第二轮代码
完整展开的代码太占地方,所以我把每个代码单元格都做成了可展开的。如果不想逐个复制粘贴,这里有一个包含全部内容、可以直接运行的 Colab Notebook。
定义常量
PROD_LST = ['Pizza Slice', 'Wasabi Root', 'Snowball', 'Shell']
CONVERSION_MATRIX = [
[1. , 0.48, 1.52, 0.71],
[2.05, 1. , 3.26, 1.56],
[0.64, 0.3 , 1. , 0.46],
[1.41, 0.61, 2.08, 1. ]
]
# Mapping words to index numbers
TO_NUM = {
"Pizza Slice": 0,
"Wasabi Root": 1,
"Snowball": 2,
"Shell": 3
}
# Mapping index numbers back to words
TO_PROD = {
0: "Pizza Slice",
1: "Wasabi Root",
2: "Snowball",
3: "Shell"
}
导入库
import numpy as np
from itertools import product
辅助函数
# Function to simulate moving between currency
def get_profit(list_prod):
# We can fill in 1-4 currencies
assert len(list_prod) in [1,2,3,4]
profit = 1
list_prod = ["Shell"] + list_prod + ["Shell"]
# Loop through each pair of currencies
for i in range(len(list_prod)-1):
# Convert the current currency to the next one
cur = TO_NUM[list_prod[i]]
nxt = TO_NUM[list_prod[i+1]]
profit *= CONVERSION_MATRIX[cur][nxt]
return profit, list_prod
# Same as get_profit, but prints out results
def get_profit_verbose(list_prod):
# Starting with a hardcoded initial amount of 2000 Shells
initial_amount = 2000
amount = initial_amount
# For printing detailed steps
print(f"We start with {initial_amount} Shells.")
for i in range(len(list_prod) - 1):
cur = TO_NUM[list_prod[i]]
nxt = TO_NUM[list_prod[i+1]]
rate = CONVERSION_MATRIX[cur][nxt]
new_amount = amount * rate
print(f"Then we trade {list_prod[i]} to {list_prod[i+1]} at 1 {list_prod[i]} : {rate} {list_prod[i+1]}.")
print(f"Thus we have {amount} * {rate} = {new_amount} {list_prod[i+1]}s")
# Update the amount for the next trade
amount = new_amount
# Final output for the amount of Shells we end up with
print(f"Finally, we end up with {amount} Shells.")
print("-"*10 + "\n")
return amount, list_prod
# Function to find maximum profit given a certain number of trades
def run_simulation(trade_count, verbose=False):
print(f"Running {trade_count} currencies / {trade_count+1} trades...", end="")
best_profit = 0
best_trades = []
# Generate all combinations of products with the length of `trade_count`
for prods in product(PROD_LST, repeat=trade_count):
profit, list_prod = get_profit(list(prods))
if profit > best_profit:
best_profit = profit
best_trades = list_prod
print("\rBest {} trades: {}".format(trade_count, " -> ".join(best_trades)))
print("Best profit:", best_profit)
if verbose:
get_profit_verbose(best_trades)
运行模拟
for trade_count in range(1, 4+1):
run_simulation(trade_count, verbose=True)
第三轮
官方网站上的交易目标(点击展开)
一个神秘的漂流瓶被冲上了岸。原来,里面装着一张属于传奇人物鬣蜥琼斯(Iguana Jones)的藏宝图。看来,宝藏散落在群岛各处。这位探险家兼考古学家还在藏宝图旁留下了一张字条,上面有一些提示,告诉你怎样找到最大的宝藏,以及怎样将它们据为己有。
你的目标是选择最多三个探险目的地,把最多的宝藏带回家。据说每个格子至少藏有 7.5k 贝壳币,但也有传言说,一个格子里可能有好几个宝箱。点击藏宝图来选择你心仪的目的地。进行这些探险可能需要付出成本,而且寻宝的也不止你一个人。所以,请慎重选择你的探险和目的地。
祝你好运,探险愉快!
Wiki 上的说明(点击展开)
一张神秘的藏宝图和附带的字条,让所有人都像英勇的冒险家一样行动起来。你最多可以进行三次探险来寻找宝藏。第一次探险免费,但第二次和第三次需要付费。请记住,寻宝的不止你一个人,你必须与所有在同一地点搜寻的人平分战利品。精心规划你的探险,说不定你就是满载而归、收获最大的那个人。
探险利润的计算方式如下:每个地点都有自己的宝藏倍数(最高 100)和寻宝者数量(最多 8 人)。一个地点的宝藏总额等于基础宝藏(7500,所有地点相同)与该地点的宝藏倍数的乘积。不过,所得的金额还要除以寻宝者数量与(其他玩家的)所有探险中发生在该地点的百分比之和。举个例子,如果某个格子有 5 个寻宝者,同时(其他所有玩家的)全部探险中有 10% 也去了那里,那么你从这个格子得到的奖励就要除以 15。除完之后,再扣掉探险成本(如果有的话),剩下的就是利润。
第二次和第三次探险是可选的:不要求做满 3 次。进行第二次探险的费用为 25,000,第三次为 75,000。提交探险的先后顺序不影响评分。
第三轮解析
从这一轮开始,事情才真正变得有意思起来。不存在唯一的正确答案,因为那样的话所有人都会选它,正确答案就会变差,其他策略反而会变好。因此,我们要找的是一个均衡分布,在这个分布下,每个人的利润都相同。
为此,我们从一个很长的向量开始,每一种可能的选择都对应其中一个分量。也就是说,某个分量可能代表选择 [(0,1)] 的玩家的百分比,另一个分量可能代表选择 [(0,1), (3,2), (1,1)] 的玩家的百分比。注意,这里的顺序并不重要。
本质上,我们要找的是一个具有以下特征的向量 :
的所有分量都是 范围内的非负数,且满足:
对于任意两个分量 和 ,下列情形之一成立:
a. 和 的边际利润相同。
b. 的边际利润小于 ,且 (或者反过来)。
对应的选择为 ,其边际利润可以用以下函数计算:
注意,由于很多选择包含多个岛屿,我们需要做相应的处理,避免重复计算。因此,我们将 定义如下:
上面的公式可能看着让人困惑,但思路很简单:
考虑了岛屿的数量(例如,如果 包含 3 个岛屿,那么 )。用这一项做归一化,可以确保我们得到的是岛屿选择的百分比,而不是选择中包含该岛屿的提交策略 / 玩家的百分比,后者和我们要找的东西相去甚远。
问题建模完成之后,就可以暴力求解了。具体来说,我们重复以下步骤:
遍历所有满足 的 对
检查它们是否满足以下情形之一:
a. 和 赚的钱一样多
b. 赚得更少,但 ;或者反过来, 也是同理
如果不满足,就用给定的步长 更新 ,以抵消这种不平衡
a. 例如,如果 赚得更少,我们就从 中减去 ,加到 上,这样 就能赚得更多
b. 严格来说,我们加的是 ,以防止出现负概率
尽可能多地重复这些步骤,必要时把 调小
在模拟进行的过程中,我们把每次迭代的状态画了出来,得到了一张很酷的 GIF,展示了步长 的影响。delta 从 开始,每 50 次迭代除以 10。
按左上、右上、左下、右下的顺序,共有 4 张不同的图:
左上图画的是当前分布中概率非零的选择的利润。
右上图画的是当前分布中概率为零的选择的利润。
左下图把上面两张图合在一起,左上图的内容用黄色表示,右上图的内容用蓝色表示。
右下图给出当前的概率分布。X 轴是各个不同选择的索引,Y 轴是选择它的玩家百分比。X 轴上的所有选择都按顺序排列。索引 是只选 1 个岛屿的选择, 是选 2 个岛屿的选择, 是选 3 个岛屿的选择。

可以看到,选择 2 个岛屿通常是最优解。随着步长 减小,分布很快就趋于稳定。以下是最终分布的统计数据:
Top 10 choices:
[(2, 0), (2, 1)] 3.5850499999999106
[(2, 2), (3, 1)] 3.583449999999967
[(1, 1), (1, 2)] 3.0079899999998894
[(0, 4), (3, 3)] 2.830099999999941
[(0, 1), (3, 3)] 2.4663899999999828
[(1, 2), (1, 3)] 2.2960000000000513
[(1, 2), (3, 2)] 2.073439999999967
[(2, 3), (3, 0)] 1.996660000000012
[(1, 1), (2, 1)] 1.9702600000000208
[(1, 1), (3, 2)] 1.9034099999999843
----------------------------------------
Bottom 10 choices that still have nonezero probability:
[(0, 4), (2, 4)] 0.00012000000000000002
[(3, 1), (4, 3)] 0.00016
[(4, 1), (4, 3)] 0.00026000000000000003
[(2, 4), (3, 3)] 0.0002900000000000001
[(1, 0), (3, 3)] 0.00030000000000000014
[(3, 4), (4, 3)] 0.00031000000000000016
[(3, 0), (4, 3)] 0.0004000000000000004
[(1, 3), (4, 4)] 0.0004300000000000005
[(2, 1), (2, 4)] 0.0006500000000000011
[(0, 2), (4, 3)] 0.0007100000000000008
不过,我们最后还是故意挑了一个相对较差的选项,避开了最高和最低的 20%。
我们的想法是,选它的人会更少,这样好处就都归我们自己了。
Given Answer: [(1, 0), (3, 4)]
The answer is in the 92.55th percentile among all entries.
The answer is in the 29.17th percentile among non-zero entries.
第三轮代码
完整展开的代码太占地方,所以我把每个代码单元格都做成了可展开的。如果不想逐个复制粘贴,这里有一个包含全部内容、可以直接运行的 Colab Notebook。
导入库并设置输出文件夹
import os
import cv2
import time
import json
import random
import imageio
import itertools
import numpy as np
import matplotlib.pyplot as plt
OUTPUT_NAME = "prosperity_240415_round3_manual_optimal_distribution_output"
try:
os.makedirs(OUTPUT_NAME)
except OSError:
if not os.path.isdir(OUTPUT_NAME):
raise
定义常量
SHELL_PER_MULTIPLIER = 7500
EXPEDITION_COSTS = {1: 0, 2: 25000, 3: 100000}
# (i,j) stands for i multiplier and j hunters
TREASURE_MAP = [
[(24, 2), (70, 4), (41, 3), (21, 2), (60, 4)],
[(47, 3), (82, 5), (87, 5), (80, 5), (35, 3)],
[(73, 4), (89, 5), (100, 8), (90, 7), (17, 2)],
[(77, 5), (83, 5), (85, 5), (79, 5), (55, 4)],
[(12, 2), (27, 3), (52, 4), (15, 2), (30, 3)]
]
# All possible single islands (NOT ALL CHOICES)
ISLANDS = [(i, j) for i in range(5) for j in range(5)]
# All possible choices, also weights |C_i| for islands
CHOICES = []
WEIGHTS = []
for l in itertools.combinations(ISLANDS, 1):
CHOICES.append(list(l))
WEIGHTS.append(1.0)
for l in itertools.combinations(ISLANDS, 2):
CHOICES.append(list(l))
WEIGHTS.append(2.0)
for l in itertools.combinations(ISLANDS, 3):
CHOICES.append(list(l))
WEIGHTS.append(3.0)
# np.array allows faster processing
# Not available for CHOICES, which does not have uniform length :(
WEIGHTS = np.array(WEIGHTS)
# Masks for calculating sum of v_k, True iff island is in the choice
# Caching it with dict accelerates function by ~1e3 times
MASKS = {}
for island in ISLANDS:
MASKS[island] = np.array([island in choice for choice in CHOICES])
辅助函数
# Get the profit for a single island
def profit_island(island, mask, v, weight):
# sum_v is V bar or normalized sum
sum_v = np.sum(v[mask]) / weight * 100
i, j = island
multiplier, hunters = TREASURE_MAP[i][j]
return SHELL_PER_MULTIPLIER * multiplier / (hunters + sum_v)
# Get the profit for a choice
def total_profit(choice, v, weight):
profit = 0
for island in choice:
mask = MASKS[island]
profit += profit_island(island, mask, v, weight)
return profit - EXPEDITION_COSTS[len(choice)]
# Remaining are just plotting functions
def plot_none_zero_probability(v, name='Profit from choices with none zero probability'):
weight = np.dot(v, WEIGHTS)
x = [i for i in range(len(v)) if v[i]>0]
y = [total_profit(CHOICES[i], v, weight) for i in range(len(v)) if v[i]>0]
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='Profit')
plt.title(name)
plt.grid(True)
plt.legend()
plt.savefig(f'{name}.png')
def plot_zero_probability(v, name='Profit from choices with zero probability'):
weight = np.dot(v, WEIGHTS)
x = [i for i in range(len(v)) if v[i]==0]
y = [total_profit(CHOICES[i], v, weight) for i in range(len(v)) if v[i]==0]
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='Profit')
plt.title(name)
plt.grid(True)
plt.legend()
plt.savefig(f'{name}.png')
def plot_both_profit(v, name='Profit from both, in the same chart'):
weight = np.dot(v, WEIGHTS)
x1 = [i for i in range(len(v)) if v[i]==0]
y1 = [total_profit(CHOICES[i], v, weight) for i in range(len(v)) if v[i]==0]
x2 = [i for i in range(len(v)) if v[i]>0]
y2 = [total_profit(CHOICES[i], v, weight) for i in range(len(v)) if v[i]>0]
plt.figure(figsize=(8, 4))
plt.plot(x1, y1, label='Zero')
plt.plot(x2, y2, label='None Zero')
plt.title(name)
plt.grid(True)
plt.legend()
plt.savefig(f'{name}.png')
def plot_probability(v, name='Probability Distribution among all possible choices'):
x = [i for i in range(len(v))]
y = [i for i in v]
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='Probability')
plt.title(name)
plt.grid(True)
plt.legend()
plt.savefig(f'{name}.png')
def plot(v, n1, n2, n3, n4):
plot_none_zero_probability(v, n1)
plot_zero_probability(v, n2)
plot_both_profit(v, n3)
plot_probability(v, n4)
image = cv2.vconcat([
cv2.hconcat([cv2.imread(f'{n1}.png'), cv2.imread(f'{n2}.png')]),
cv2.hconcat([cv2.imread(f'{n3}.png'), cv2.imread(f'{n4}.png')]),
])
cv2.imwrite("result.png", image)
plt.close("all")
return imageio.v2.imread("result.png")
运行模拟
# Initialize distribution vector with small random values summing to 100%
random_values = np.random.rand(len(CHOICES))
v = 100 * random_values / np.sum(random_values)
# The settings describe the delta iteration pairs
# (0.1, 20) means perform 20 iterations with delta=0.1
# After each delta iteration pair a checkpoint is saved
# Note that a iteration is described as iterating through all the pairs once
settings = np.array([
(1.0, 50),
(0.1, 50),
(0.01, 50),
(0.001, 50),
(0.0001, 50),
(0.00001, 50),
])
# Time for logging and frames for plotting
init_time = time.time()
frame_lst = []
# Plotting
frame_lst.append(
plot(
v,
"Profit for None Zero Probability Choices (Initial)",
"Profit for Zero Probability Choices (Initial)",
"Profit for All Choices (Initial)",
"Probability Distribution Among Choices (Initial)"
)
)
# Iterate through settings
counter = 0
checkpoint_counter = 0
for delta_value, num_iterations in settings:
num_iterations = int(num_iterations)
checkpoint_counter += num_iterations
for iter in range(num_iterations):
counter += 1
# Time for logging
round_time = time.time()
# Iterate through pairs
for i in range(len(v)):
for j in range(len(v)):
# Choose two different indices
if i == j:
continue
# Matrices soon become sparse, utilize it for speed boost
if v[i]==0 and v[j]==0:
continue
# V bar in equation above
# Calculate once and apply to both profit calculations
weight = np.dot(v, WEIGHTS)
# Find profit, update probability accordingly
profit_i = total_profit(CHOICES[i], v, weight)
profit_j = total_profit(CHOICES[j], v, weight)
if profit_i < profit_j and v[i] > 0:
delta = min(v[i], delta_value)
v[i] -= delta
v[j] += delta
elif profit_i > profit_j and v[j] > 0:
delta = min(v[j], delta_value)
v[j] -= delta
v[i] += delta
# Logging
print(f"-"*40)
print(f"Step Size = {delta_value} | Iteration {counter}/{checkpoint_counter}")
print(f"Iteration Time:", time.strftime('%H hr %M min %S s', time.gmtime(time.time() - round_time)))
print(f"Total Time:", time.strftime('%H hr %M min %S s', time.gmtime(time.time() - init_time)))
# Plotting
frame_lst.append(
plot(
v,
f"Profit for None Zero Probability Choices (delta = {delta_value}, iter = {counter})",
f"Profit for Zero Probability Choices (delta = {delta_value}, iter = {counter})",
f"Profit for All Choices (delta = {delta_value}, iter = {counter})",
f"Probability Distribution Among Choices (delta = {delta_value}, iter = {counter})"
)
)
# Save Checkpoint
with open(f'{OUTPUT_NAME}/checkpoint_{counter}.txt', 'w') as filehandle:
json.dump(list(v), filehandle)
imageio.mimsave(f'{OUTPUT_NAME}/checkpoint_{counter}.gif', frame_lst, fps=4, loop=2)
print(f"-"*40)
print(f"Updated checkpoint at iteration {counter}, saved to folder {OUTPUT_NAME}")
检查结果是否大致达到均衡(可选)
def check(v):
weight = np.dot(v, WEIGHTS)
for i in range(len(v)):
for j in range(len(v)):
# Choose two different indices
if i == j:
continue
# Make sure one is zero and one is not
if v[i]==0 and v[j]==0:
continue
if v[i]!=0 and v[j]!=0:
continue
# Swap so i is zero / bad choice
if v[i]!=0:
i,j = j,i
# Compare profits
profit_i = total_profit(CHOICES[i], v, weight)
profit_j = total_profit(CHOICES[j], v, weight)
# This should NOT print anything if we have a stable equilibrium
if profit_i > profit_j:
print("NOT EQUILIBRIUM!")
print(f"Index {i} or choice {CHOICES[i]} has profit {profit_i} and probability {v[i]}")
print(f"Index {j} or choice {CHOICES[i]} has profit {profit_j} and probability {v[j]}")
print(f"Although {j} has proability {v[j]} > 0, its profit is lower!")
return
check(v)
获取统计数据并抽样得出答案
def find_indices_by_count(weights, top_k, bottom_k):
# Normalize the weights to sum to 1
probabilities = weights / np.sum(weights)
# Get indices sorted by probability
sorted_indices = np.argsort(probabilities)[::-1] # Descending order
top_indices = sorted_indices[:top_k]
# Filter out zero probabilities and get their indices
non_zero_probabilities = probabilities[probabilities > 0]
non_zero_sorted_indices = np.argsort(non_zero_probabilities)
# Select the bottom k indices of non-zero probabilities
if bottom_k > len(non_zero_sorted_indices):
bottom_k = len(non_zero_sorted_indices) # Adjust bottom_k if it's larger than available non-zero indices
bottom_indices = non_zero_sorted_indices[:bottom_k]
# Adjust the non-zero indices to match original array indices
actual_bottom_indices = np.nonzero(probabilities > 0)[0][bottom_indices]
return top_indices, actual_bottom_indices
def find_percentiles(v, i):
# Ensure i is within the valid range
if i >= len(v) or i < 0:
return None # or raise an exception
# Sort the entire array and find the position of v[i]
sorted_v = np.sort(v)
position_all = np.argwhere(sorted_v == v[i])[0][0] # Using argwhere to find the first occurrence
percentile_all = ((position_all + 0.5) / len(v)) * 100
# Filter out zero entries and repeat the process
non_zero_v = v[v != 0]
sorted_non_zero_v = np.sort(non_zero_v)
position_non_zero = np.argwhere(sorted_non_zero_v == v[i])[0][0]
percentile_non_zero = ((position_non_zero + 0.5) / len(non_zero_v)) * 100
return percentile_all, percentile_non_zero
top_indices, bottom_indices = find_indices_by_count(v, 10, 10)
print(f"-"*40)
print("Top 10 choices:")
for i in top_indices:
print(CHOICES[i], v[i])
print(f"-"*40)
print("Bottom 10 choices:")
for i in bottom_indices:
print(CHOICES[i], v[i])
print(f"-"*40)
probabilities = v / np.sum(v)
answer = np.random.choice(len(v), p=probabilities)
print("Sampled Answer:", CHOICES[answer])
percentile_all, percentile_non_zero = find_percentiles(v, answer)
print(f"The answer is in the {percentile_all:.2f}th percentile among all entries.")
print(f"The answer is in the {percentile_non_zero:.2f}th percentile among non-zero entries.")
给定一个选择,查看其百分位(可选)
choice = [(1,0), (3,4)] # Replace with any choice
choice.sort()
# Function to find index of list containing the tuple
def find_index(arr, target_tuple):
for index, list_of_tuples in enumerate(arr):
if any(t == target_tuple for t in list_of_tuples):
return index
return None
def find_percentiles(v, choice):
i = -1
for index, list_of_tuples in enumerate(CHOICES):
if list_of_tuples == choice:
i = index
break
# Ensure i is within the valid range
if i >= len(v) or i < 0:
return None # or raise an exception
# Sort the entire array and find the position of v[i]
sorted_v = np.sort(v)
position_all = np.argwhere(sorted_v == v[i])[0][0] # Using argwhere to find the first occurrence
percentile_all = ((position_all + 0.5) / len(v)) * 100
# Filter out zero entries and repeat the process
non_zero_v = v[v != 0]
sorted_non_zero_v = np.sort(non_zero_v)
position_non_zero = np.argwhere(sorted_non_zero_v == v[i])[0][0]
percentile_non_zero = ((position_non_zero + 0.5) / len(non_zero_v)) * 100
return percentile_all, percentile_non_zero
print("Given Answer:", choice)
percentile_all, percentile_non_zero = find_percentiles(v, choice)
print(f"The answer is in the {percentile_all:.2f}th percentile among all entries.")
print(f"The answer is in the {percentile_non_zero:.2f}th percentile among non-zero entries.")
将 GIF 转换为 MP4 并保存输出(可选,仅限 Colab)
!for f in prosperity_240415_round3_manual_optimal_distribution_output/*.gif; do ffmpeg -i "$f" -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" -c:v libx264 -preset fast -crf 23 "${f%.*}.mp4"; done
import shutil
shutil.make_archive(OUTPUT_NAME, "zip", OUTPUT_NAME)
from google.colab import files
files.download(f'{OUTPUT_NAME}.zip')
第四轮
官方网站上的交易目标(点击展开)
金鱼们又回来了,还带来了更多的潜水装备!和上次一样,它们想尽快脱手,只要价格合适,就愿意卖给你。
你只有两次机会报出一个好价格。每条金鱼都会接受高于其保留价的最低出价。但这一次,它们听说了上次来访时群岛上其他居民开出的价格。所以,对于你的第二个出价,它们还会参考群岛上其他交易者出价的平均值。当你的出价高于所有出价的平均值时,它们就会与你交易。但如果你低于平均值,成交的概率就会迅速下降。
群岛上对潜水装备的需求一直都在。因此,在本轮结束时,你能够以每件 1000 贝壳币的价格把它们卖掉。你的目标是设定价格,确保与尽可能多的金鱼达成有利可图的交易。
对自己的策略和输入感到满意之后,点击“Submit manual trade”(提交手动交易)按钮将其锁定。注意,只要本轮仍在进行,你就可以(重新)提交新的策略。本轮一结束,系统就会处理你最后提交的交易策略。
祝你好运,交易愉快!
Wiki 上的说明(点击展开)
金鱼们带着更多的潜水装备回来了。每条金鱼都会有新的保留价,但它们仍然遵循与第一轮相同的分布。
你的交易选项和之前类似。你有两次机会报出一个好价格。每条金鱼都会接受高于其保留价的最低出价。但这一次,对于你的第二个出价,它们还会参考群岛上其他交易者第二个出价的平均值。当你的出价高于所有第二个出价的平均值时,它们就会与你交易。但如果你低于平均值,成交的概率就会迅速下降。
为了模拟这一概率,如果你的第二个出价低于所有第二个出价的平均值,那么与这条金鱼交易所得的盈亏(PNL)将乘以一个系数 p:
你能从已有的数据中学到什么?又将如何应对这种新的变化?在沙滩上站稳脚跟,做好准备吧,因为局面可能会变得混乱。
第四轮解析
这道题的做法和第三轮很像——我们的目标是找到一个好的概率向量,让每个人赚的钱都一样多。不过,由于不再使用百分比,向量之和只需为 1,而不是 100。
我们同样从一个很长的向量开始,每一种可能的答案都对应其中一个分量。也就是说,某个分量可能代表选择 (900, 1000) 的人的比例,另一个分量可能代表选择 (925, 975) 的玩家的比例。注意,这里的顺序很重要。
本质上,我们要找的是一个具有以下特征的向量 :
的所有分量都是 范围内的非负数,且满足:
对于任意两个分量 和 ,下列情形之一成立:
a. 和 的利润相同。
b. 的利润小于 ,且 (或者反过来)。
的边际利润可以用以下函数计算:
其中 表示保留价在 内的金鱼数量。
只需对一个线性函数积分,就能得到 的期望值;既然可以直接求出概率密度函数(pdf)及其积分,就没必要再用蒙特卡洛了。
线性函数的积分很容易计算:
问题建模完成之后,就可以用和之前一样的方式暴力求解。具体来说,我们重复以下步骤:
遍历所有满足 的 对
检查它们是否满足以下情形之一:
a. 和 赚的钱一样多
b. 赚得更少,但 ;或者反过来, 也是同理
如果不满足,就用给定的步长 更新 ,以抵消这种不平衡
a. 例如,如果 赚得更少,我们就从 中减去 ,加到 上,这样 就能赚得更多
b. 严格来说,我们加的是 ,以防止出现负概率
尽可能多地重复这些步骤,必要时把 调小
我们把每一代的状态画成了 GIF,delta 从 开始,每 20 次迭代除以 10。再提醒一下,按左上、右上、左下、右下的顺序,共有 4 张不同的图:
左上图画的是当前分布中概率非零的选择的利润。
右上图画的是当前分布中概率为零的选择的利润。
左下图把上面两张图合在一起,左上图的内容用黄色表示,右上图的内容用蓝色表示。
右下图给出当前的概率分布。X 轴是各个不同选择的索引,Y 轴是选择它的玩家百分比。

可惜结果没有我们预期的那么有意思——似乎会收敛到一个明显的最优解,没有太多来回的拉锯。100 轮之后,最终只剩下 2 个概率非零的选择。如果迭代更多次,或者用更大的步长 ,分布大概会收敛到唯一的答案。以下是我们的最终统计数据:
Top 10 none-zero choices:
[956, 984] 0.8930841506074441
[955, 984] 0.1069158493925551
----------------------------------------
Bottom 10 none-zero choices:
[955, 984] 0.1069158493925551
[956, 984] 0.8930841506074441
此外,Discord 上有人声称会故意选择很低或很高的值,试图人为地影响平均值。因此,我们测试了在有人故意选择最高值 / 最低值 / 随机值的情况下,利润最高的解是什么。结果看起来相对稳定,少量捣乱的选择影响很小,一般不值得为此冒险。
For 1.0% random choosers, with at least 0% choosing 900 and 0% choosing 1000, the best choice is:
Choice 4087 [956, 984] with probability 88% and profit 20.070400000000024
For 1.0% random choosers, with at least 5.0% choosing 900 and 0% choosing 1000, the best choice is:
Choice 4087 [956, 984] with probability 88% and profit 20.070400000000024
For 1.0% random choosers, with at least 0% choosing 900 and 5.0% choosing 1000, the best choice is:
Choice 4087 [956, 984] with probability 88% and profit 20.070400000000024
For 1.0% random choosers, with at least 10.0% choosing 900 and 0% choosing 1000, the best choice is:
Choice 4087 [956, 984] with probability 88% and profit 20.070400000000024
For 1.0% random choosers, with at least 0% choosing 900 and 10.0% choosing 1000, the best choice is:
Choice 4087 [956, 984] with probability 88% and profit 20.070400000000024
For 5.0% random choosers, with at least 0% choosing 900 and 0% choosing 1000, the best choice is:
Choice 4042 [955, 983] with probability 0% and profit 20.12500058734451
For 5.0% random choosers, with at least 5.0% choosing 900 and 0% choosing 1000, the best choice is:
Choice 4042 [955, 983] with probability 0% and profit 20.181300000000014
For 5.0% random choosers, with at least 0% choosing 900 and 5.0% choosing 1000, the best choice is:
Choice 4042 [955, 983] with probability 0% and profit 20.09472298578444
For 5.0% random choosers, with at least 10.0% choosing 900 and 0% choosing 1000, the best choice is:
Choice 4042 [955, 983] with probability 0% and profit 20.181300000000014
For 5.0% random choosers, with at least 0% choosing 900 and 10.0% choosing 1000, the best choice is:
Choice 4087 [956, 984] with probability 84% and profit 20.070400000000024
For 10.0% random choosers, with at least 0% choosing 900 and 0% choosing 1000, the best choice is:
Choice 4042 [955, 983] with probability 0% and profit 20.181300000000014
For 10.0% random choosers, with at least 5.0% choosing 900 and 0% choosing 1000, the best choice is:
Choice 4041 [955, 982] with probability 0% and profit 20.270700000000012
For 10.0% random choosers, with at least 0% choosing 900 and 5.0% choosing 1000, the best choice is:
Choice 4042 [955, 983] with probability 0% and profit 20.181300000000014
For 10.0% random choosers, with at least 10.0% choosing 900 and 0% choosing 1000, the best choice is:
Choice 4041 [955, 982] with probability 0% and profit 20.270700000000012
For 10.0% random choosers, with at least 0% choosing 900 and 10.0% choosing 1000, the best choice is:
Choice 4042 [955, 983] with probability 0% and profit 20.181300000000014
第四轮代码
完整展开的代码太占地方,所以我把每个代码单元格都做成了可展开的。如果不想逐个复制粘贴,这里有一个包含全部内容、可以直接运行的 Colab Notebook。
导入库并设置输出文件夹
import os
import cv2
import time
import json
import random
import imageio
import itertools
import numpy as np
import matplotlib.pyplot as plt
OUTPUT_NAME = "prosperity_240419_round4_manual_optimal_distribution_output"
try:
os.makedirs(OUTPUT_NAME)
except OSError:
if not os.path.isdir(OUTPUT_NAME):
raise
定义常量
BETS = [i for i in range(900,1001)]
CHOICES = []
WEIGHTS = []
# Weights are the second choices. We use it to calculate the average
for c in itertools.combinations(BETS, 2):
CHOICES.append(list(c))
WEIGHTS.append(c[1])
WEIGHTS = np.array(WEIGHTS)
辅助函数
# PDF for gold fish price
def f(x):
return (x/5000) - (9/50)
# Integral of f, used to calculate G_[a,b]
def int_f(a,b):
avg = (f(b)+f(a)) / 2
return (b-a) * avg
# Function to simulate bids and calculate profits
def profit(v, i, mean):
a,b = CHOICES[i]
g1 = int_f(900, a)
g2 = int_f(a, b)
if b == 1000:
p = 1
else:
p = min(1, (1000-mean)/(1000-b))
return ((1000-a) * g1) + ((1000-b) * g2 * p)
# Remaining are just plotting functions
def plot_none_zero_probability(v, name='Profit from choices with none zero probability'):
mean = np.dot(v, WEIGHTS)
x = [i for i in range(len(v)) if v[i]>0]
y = [profit(v, i, mean) for i in range(len(v)) if v[i]>0]
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='Profit')
plt.title(name)
plt.grid(True)
plt.legend()
plt.savefig(f'{name}.png')
def plot_zero_probability(v, name='Profit from choices with zero probability'):
mean = np.dot(v, WEIGHTS)
x = [i for i in range(len(v)) if v[i]==0]
y = [profit(v, i, mean) for i in range(len(v)) if v[i]==0]
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='Profit')
plt.title(name)
plt.grid(True)
plt.legend()
plt.savefig(f'{name}.png')
def plot_both_profit(v, name='Profit from both, in the same chart'):
mean = np.dot(v, WEIGHTS)
x1 = [i for i in range(len(v)) if v[i]==0]
y1 = [profit(v, i, mean) for i in range(len(v)) if v[i]==0]
x2 = [i for i in range(len(v)) if v[i]>0]
y2 = [profit(v, i, mean) for i in range(len(v)) if v[i]>0]
plt.figure(figsize=(8, 4))
plt.plot(x1, y1, label='Zero')
plt.plot(x2, y2, label='None Zero')
plt.title(name)
plt.grid(True)
plt.legend()
plt.savefig(f'{name}.png')
def plot_probability(v, name='Probability Distribution among all possible choices'):
x = [i for i in range(len(v))]
y = [i for i in v]
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='Probability')
plt.title(name)
plt.grid(True)
plt.legend()
plt.savefig(f'{name}.png')
def plot(v, n1, n2, n3, n4):
plot_none_zero_probability(v, n1)
plot_zero_probability(v, n2)
plot_both_profit(v, n3)
plot_probability(v, n4)
image = cv2.vconcat([
cv2.hconcat([cv2.imread(f'{n1}.png'), cv2.imread(f'{n2}.png')]),
cv2.hconcat([cv2.imread(f'{n3}.png'), cv2.imread(f'{n4}.png')]),
])
cv2.imwrite("result.png", image)
plt.close("all")
return imageio.v2.imread("result.png")
运行模拟
# Initialize distribution vector with small random values summing to 1
random_values = np.random.rand(len(CHOICES))
v = random_values / np.sum(random_values)
mean = np.dot(v, WEIGHTS)
# The settings describe the delta iteration pairs
# (0.1, 20) means perform 20 iterations with delta=0.1
# After each delta iteration pair a checkpoint is saved
# Note that a iteration is described as iterating through all the pairs once
settings = np.array([
(0.01, 20),
(0.001, 20),
(0.0001, 20),
(0.00001, 20),
(0.000001, 20),
])
# Time for logging and frames for plotting
init_time = time.time()
frame_lst = []
# Plotting
frame_lst.append(
plot(
v,
"Profit for None Zero Probability Choices (Initial)",
"Profit for Zero Probability Choices (Initial)",
"Profit for All Choices (Initial)",
"Probability Distribution Among Choices (Initial)"
)
)
# Iterate through settings
counter = 0
checkpoint_counter = 0
for delta_value, num_iterations in settings:
num_iterations = int(num_iterations)
checkpoint_counter += num_iterations
for iter in range(num_iterations):
counter += 1
# Time for logging
round_time = time.time()
# Iterate through pairs
for i in range(len(v)):
for j in range(len(v)):
# Choose two different indices
if i == j:
continue
# Matrices soon become sparse, utilize it for speed boost
if v[i]==0 and v[j]==0:
continue
# Find profit, update probability accordingly
profit_i = profit(v, i, mean)
profit_j = profit(v, j, mean)
# print(profit_i, profit_j)
# print(CHOICES[i], CHOICES[j])
# print(v[i], v[j])
# print(mean)
if profit_i < profit_j and v[i] > 0:
delta = min(v[i], delta_value)
v[i] -= delta
v[j] += delta
mean -= delta * WEIGHTS[i]
mean += delta * WEIGHTS[j]
elif profit_i > profit_j and v[j] > 0:
delta = min(v[j], delta_value)
v[j] -= delta
v[i] += delta
mean -= delta * WEIGHTS[j]
mean += delta * WEIGHTS[i]
# print(mean)
# Logging
mean = np.dot(v, WEIGHTS)
max_index = np.argmax([profit(v, index, mean) for index, value in enumerate(v)])
print(f"-"*40)
print(f"Step Size = {delta_value} | Iteration {counter}/{checkpoint_counter}")
print(f"Iteration Time:", time.strftime('%H hr %M min %S s', time.gmtime(time.time() - round_time)))
print(f"Total Time:", time.strftime('%H hr %M min %S s', time.gmtime(time.time() - init_time)))
print(f"Current mean is {np.dot(v, WEIGHTS)}, best choice is {CHOICES[max_index]} ({max_index}) with profit {profit(v, max_index, mean)}")
# Plotting
frame_lst.append(
plot(
v,
f"Profit for None Zero Probability Choices (delta = {delta_value}, iter = {counter})",
f"Profit for Zero Probability Choices (delta = {delta_value}, iter = {counter})",
f"Profit for All Choices (delta = {delta_value}, iter = {counter})",
f"Probability Distribution Among Choices (delta = {delta_value}, iter = {counter})"
)
)
# Save Checkpoint
with open(f'{OUTPUT_NAME}/checkpoint_{counter}.txt', 'w') as filehandle:
json.dump(list(v), filehandle)
imageio.mimsave(f'{OUTPUT_NAME}/checkpoint_{counter}.gif', frame_lst, fps=4, loop=2)
print(f"-"*40)
print(f"Updated checkpoint at iteration {counter}, saved to folder {OUTPUT_NAME}")
获取统计数据并抽样得出答案
def find_indices_by_count(weights, top_k, bottom_k):
# Normalize the weights to sum to 1
probabilities = weights / np.sum(weights)
# Get indices sorted by probability
sorted_indices = np.argsort(probabilities)[::-1] # Descending order
top_indices = sorted_indices[:top_k]
# Filter out zero probabilities and get their indices
non_zero_probabilities = probabilities[probabilities > 0]
non_zero_sorted_indices = np.argsort(non_zero_probabilities)
# Select the bottom k indices of non-zero probabilities
if bottom_k > len(non_zero_sorted_indices):
bottom_k = len(non_zero_sorted_indices) # Adjust bottom_k if it's larger than available non-zero indices
bottom_indices = non_zero_sorted_indices[:bottom_k]
# Adjust the non-zero indices to match original array indices
actual_bottom_indices = np.nonzero(probabilities > 0)[0][bottom_indices]
return top_indices, actual_bottom_indices
def find_percentiles(v, i):
# Ensure i is within the valid range
if i >= len(v) or i < 0:
return None # or raise an exception
# Sort the entire array and find the position of v[i]
sorted_v = np.sort(v)
position_all = np.argwhere(sorted_v == v[i])[0][0] # Using argwhere to find the first occurrence
percentile_all = ((position_all + 0.5) / len(v)) * 100
# Filter out zero entries and repeat the process
non_zero_v = v[v != 0]
sorted_non_zero_v = np.sort(non_zero_v)
position_non_zero = np.argwhere(sorted_non_zero_v == v[i])[0][0]
percentile_non_zero = ((position_non_zero + 0.5) / len(non_zero_v)) * 100
return percentile_all, percentile_non_zero
top_indices, bottom_indices = find_indices_by_count(v, 10, 10)
print(f"-"*40)
print("Top 10 choices:")
for i in top_indices:
print(CHOICES[i], v[i])
print(f"-"*40)
print("Bottom 10 choices:")
for i in bottom_indices:
print(CHOICES[i], v[i])
print(f"-"*40)
probabilities = v / np.sum(v)
answer = np.random.choice(len(v), p=probabilities)
print("Sampled Answer:", CHOICES[answer])
percentile_all, percentile_non_zero = find_percentiles(v, answer)
print(f"The answer is in the {percentile_all:.2f}th percentile among all entries.")
print(f"The answer is in the {percentile_non_zero:.2f}th percentile among non-zero entries.")
模拟捣乱者的选择(可选)
def check_random(v, weight=0.1, left=0., right=0.):
if left<0 or right<0 or weight<0:
raise Exception("weight, left, right must be non-negative values")
if left+right>1 or weight>1:
raise Exception("weight, left + right must be bounded by one")
length = len(CHOICES)
random_values = np.random.rand(length)
random_values = (1-left-right) * random_values / np.sum(random_values)
random_values[0] += left
random_values[length-1] += right
v_new = weight * random_values + (1-weight) * v
mean_new = np.dot(v_new, WEIGHTS)
# Initialize variables to track the maximum profit and the corresponding number
max_profit = float('-inf')
max_index = None
# Iterate over each number in the array to calculate profit and find the maximum
for i in range(length):
current_profit = profit(v, i, mean_new)
if current_profit > max_profit:
max_profit = current_profit
max_index = i
print(f"For {weight * 100}% random choosers, with at least {left * 100}% choosing 900 and {right * 100}% choosing 1000, the best choice is:")
print("Choice", max_index, CHOICES[max_index], f"with probability {int(v_new[max_index]*100)}% and profit {max_profit}")
plot(
v_new,
f"None Zero Probability (random = {weight * 100}%, left={left * 100}%, right={right * 100}%)",
f"Zero Probability (random = {weight * 100}%, left={left * 100}%, right={right * 100}%)",
f"Best Choice is Choice {max_index} {CHOICES[max_index]} with profit {round(max_profit, 2)}",
f"Probability Distribution Among Choices"
)
os.rename("result.png", os.path.join(OUTPUT_NAME, f"Random Test (random = {weight * 100}%, left={left * 100}%, right={right * 100}%).png"))
weight_lst = [0.01, 0.05, 0.1]
left_right_lst = [(0,0), (0.05,0), (0,0.05), (0.1,0), (0,0.1)]
num_tests = 3
for weight in weight_lst:
for left, right in left_right_lst:
check_random(v, weight, left, right)
将 GIF 转换为 MP4 并保存输出(可选,仅限 Colab)
!for f in prosperity_240419_round4_manual_optimal_distribution_output/*.gif; do ffmpeg -i "$f" -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" -c:v libx264 -preset fast -crf 23 "${f%.*}.mp4"; done
import shutil
shutil.make_archive(OUTPUT_NAME, "zip", OUTPUT_NAME)
from google.colab import files
files.download(f'{OUTPUT_NAME}.zip')