c#中的增量谜题
本文关键字: | 更新日期: 2023-09-27 18:04:21
在比赛中,您使用以下策略下注。每次你赌输了,下一轮的赌注就翻倍。无论何时你赢了,下一轮的赌注将是1美元。你赌1美元开始。
例如,如果你一开始有20元,你在第一轮中赢了,在接下来的两轮中输了,然后在第四轮中赢了,那么你最终会得到20+1-1-2+4 = 22元。
您需要完成函数getFinalAmount
,它接受两个参数:
- 第一个参数是一个整数
initialAmount
,它是我们开始投注时的初始金额。 - 第二个参数是字符串
betResults
。结果的第i个字符将是"W"(赢)或"L"(输),表示第i轮的结果。你的函数应该返回所有回合结束后你将拥有的钱数。
如果在某一时刻你的账户中没有足够的钱来支付下注的价值,你必须停止并归还你在那个时刻的钱。
我试过这段代码,失败了:
var amountInHand = 15;
var possiblities = "LLLWLLLL";
static int Calculate(int amountInHand, string possibles)
{
var lastBet = 1;
foreach (char c in possiblities)
{
if (c == 'W')
{
amountInHand = amountInHand + 1;
}
else if (c == 'L')
{
var loss = 0;
if (lastBet == 1)
{
loss = lastBet;
}
else if (lastBet > 1)
{
loss = lastBet * 2;
}
amountInHand = amountInHand - loss;
lastBet++;
}
}
return amountInHand;
}
预期输出
1st round - Loss: 15-1 = 14
2nd round - Loss: 14-2 = 12 (Bet doubles)
3rd round - Loss: 12-4 = 8
4th round - Win: 8 + 8 = 16
5th round - Loss:16-1 = 15 (Since the previous bet was a win, this bet has a value of 1 dollar)
6th round - Loss: 15-2 = 13
7th round - Loss: 13-4 = 9
8th round - Loss: 9-8 = 1
这是R.B.给出的正确答案,但不知道他为什么删掉了。
var amountInHand = 15;
var possiblities = "LLLWLLLL";
var lastBet = 1;
foreach (char c in possiblities)
{
if (c == 'W')
{
amountInHand = amountInHand + lastBet;
lastBet = 1;
}
else if (c == 'L')
{
amountInHand = amountInHand - lastBet;
lastBet = lastBet * 2;
}
//handle running out of money
if (lastBet > amountInHand) return amountInHand;
}
关于这个问题,我写了一篇博文和一段代码高尔夫。我的答案是:
return possibilities.Aggregate(new{b=1,c=amountInHand,x=1},(l,o)=>l.x<0?l:o=='W'?new{b=1,c=l.c+l.b,x=1}:new{b=l.b*2,c=l.c-l.b,x=(l.c-l.b)-(l.b*2)}).c;
Un-golfed:
private static int getFinalAmount(string q, int w)
{
return possibilities.Aggregate(new { b = 1, c = amountInHand, x = false }, //initial seed gets the flag for cancel set to false
(l, o) =>
l.x //if our cancel flag is set,
? l //just return the same result
: o == 'W' //if the outcome was a win
//do the math and now also set a cancel flag to false (if we won, we can make our next bet for sure)
? new { b = 1, c = l.c + l.b, x = false }
//do our math again, but this time the cancel flag is tricky.
: new { b = l.b * 2, c = l.c - l.b,
//we cancel if our new amount will be less than our new bet.
//Note, we can't use the new values that we just set in the same section -
//they're not available yet so we have duplicate math here.
x = (l.c - l.b) < (l.b * 2) })
.c; //all the function returns is the current amount
}