我正在实现一个带有记忆的递归函数以加快速度。该程序的要点如下:
我洗一副牌(红牌和黑牌的数量相等),然后开始正面朝上处理它们。在任何一张牌之后,你可以说“停止”,此时我为每张红牌支付 1 美元,而你为每张黑牌支付 1 美元。你的最佳策略是什么,你愿意花多少钱来玩这个游戏?
我的递归函数如下:
double Game::Value_of_game(double number_of_red_cards, double number_of_black_cards)
{
double value, key;
if(number_of_red_cards == 0)
{
Card_values.insert(Card_values.begin(), pair<double, double> (Key_hash_table(number_of_red_cards, number_of_black_cards), number_of_black_cards));
return number_of_black_cards;
}
else if(number_of_black_cards == 0)
{
Card_values.insert(Card_values.begin(), pair<double, double> (Key_hash_table(number_of_red_cards, number_of_black_cards), 0));
return 0;
}
card_iter = Card_values.find(Key_hash_table(number_of_red_cards, number_of_black_cards));
if(card_iter != Card_values.end())
{
cout << endl << "Debug: [" << number_of_red_cards << ", " << number_of_black_cards << "] and value = " << card_iter->second << endl;
return card_iter->second;
}
else
{
number_of_total_cards = number_of_red_cards + number_of_black_cards;
prob_red_card = number_of_red_cards/number_of_total_cards;
prob_black_card = number_of_black_cards/number_of_total_cards;
value = max(((prob_red_card*Value_of_game(number_of_red_cards - 1, number_of_black_cards)) +
(prob_black_card*Value_of_game(number_of_red_cards, number_of_black_cards - 1))),
(number_of_black_cards - number_of_red_cards));
cout << "Check: value = " << value << endl;
Card_values.insert(Card_values.begin(), pair<double, double> (Key_hash_table(number_of_red_cards, number_of_black_cards), value));
card_iter = Card_values.find(Key_hash_table(number_of_red_cards , number_of_black_cards ));
if(card_iter != Card_values.end());
return card_iter->second;
}
}
double Game::Key_hash_table(double number_of_red_cards, double number_of_black_cards)
{
double key = number_of_red_cards + (number_of_black_cards*91);
return key;
}
第三个 if 语句是代码的“记忆”部分,它存储了所有必要的值。地图中保存的值可以被认为是一个矩阵,这些值将对应于某些#red 牌和#black 牌。真正奇怪的是,当我对总共 8 张卡片(4 张黑色和 4 张红色)执行代码时,我得到了一个错误的答案。但是当我执行 10 张牌的代码时,我的答案是错误的,但现在我对 4 个黑色和 4 个红色的答案是正确的(8 张牌)!12 张卡片也可以这样说,我得到 12 张卡片的错误答案,但 10 张卡片的正确答案,依此类推。代码中有一些错误,但是我无法弄清楚。