JavaScript(ECMAScript 6草案)-62 51 50个字符(在函数主体中)
function g(a,r,t=0,b=1)
a>=b&&(c=r[t])?g((c=c>'L')?a+b:a-b,r,t+1,c||2*b):a
g
用两个参数定义一个递归函数:
a
-您目前拥有的金额;和
r
-获胜/失败的字符串。
还有两个可选参数:
t
-当前下注的索引(最初是0
)
b
-当前下注的金额(还是再次开始1
)。
取消高尔夫:
function g(a,r,t=0,b=1){ // declare a function g with arguments a,r,t,b where
// t defaults to 0 and b defaults to 1
c = r[t]; // get the character in the win/loss string for the current
// round.
if ( a>=b // check if we have enough money
&& c ) // and if the string has not ended
{
if ( c > 'L' ) // check if we've won the round
{
return g(a+b,r,t+1,1); // if so call g again adding the winnings and resetting the
// cost.
} else {
return g(a-b,r,t+1,2*b); // otherwise, subtract from the total money and double the
// cost.
}
} else {
return a; // If we've run out of money or got to the end then return
// the current total.
}}
JavaScript(ECMAScript 6)-61 58 54个字符(在函数主体中)
function g(a,r)
(b=1,[b=b>a?b:x>'L'?(a+=b,1):(a-=b,b*2)for(x of r)],a)
说明:
(b=1, // Initialise the cost to 1
[ // for each character x of r using array comprehension
b=
b>a?b // if we have run out of money do b=b
:x>'L'?(a+=b,1) // else if we've won collect the winnings and reset b=1
:(a-=b,2*b) // else subtract the cost from the total money and double
// the cost for next round.
for(x of r)] // Repeat for each character
// array.
,a) // Finally, return a.
测验
console.log(g(0,'LLLLLWWLWWLW')) // 0
console.log(g(1,'WWWLLLWWWWLLWW')) //1
console.log(g(2,'LLWLWWWWWWWL')) //1
console.log(g(3,'WWWWWWWLLLWL')) //3
console.log(g(4,'LWWLWLWWWL')) //9
console.log(g(5,'LLLWWWLLWLWW')) //2
console.log(g(6,'LWLLLLWWLWWW')) //0
console.log(g(7,'WWLWWLLLWLWLW')) //4
console.log(g(8,'WWLWWLLWLWL')) //13
console.log(g(9,'WWWLLLWLLWLWWW')) //5
console.log(g(10,'WLWLLWWWWWWWL')) //18
console.log(g(11,'WLWLWLWLLLWLLW')) //17
console.log(g(12,'WWLWWWLLWL')) //17
console.log(g(13,'WWWWLWLWWW')) //21
console.log(g(15,'LLLW')) //16
console.log(g(15,'LLLL')) //0
console.log(g(14,'LLLL')) //7
console.log(g(2,'LW')) //1
console.log(g(2,'LL')) //1
console.log(g(2,'WLL')) //0