# 增量博彩

19

1. 第一个参数是一个整数`a`，它是我们开始下注时所拥有的初始资金。
2. 第二个参数是一个字符串`r`。结果的第i个字符将是“ W”（胜利）或“ L”（失败），表示第i回合的结果。

``````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
``````

`1`在这种情况下函数返回

1

1

@quincunx对不起，我从未在这里发布过，但有趣的是，发布了创建时迁移到这里的许多原始问题。在某种程度上，我是进行此堆栈交换的原因之一。我以为都是代码高尔夫，笔记本电脑的电池快要用完了，所以我急于完成。抱歉。漫漫长夜。
TheSoftwareJedi 2014年

5

### GolfScript，33个字符

``````{
1\{2\$2\$<!{1&{+1}{:b-b.+}if.}*;}/;
}:g;
``````

``````> 13 'LLLWLLLL'
6
> 4 'LWWLWLWWWL'
9
> 5 'LLLWWWLLWLWW'
2
> 2 'LW'
1
``````

``````1\            # prepare stack a b r
{             # for each char in r
2\$2\$<!{     #   if a>=b
1&        #     take last bit of character (i.e. 0 for L and 1 for W)
{         #     if W
+       #       a <- a+b
1       #       b <- 1
}{        #     else
:b-     #       a <- a-b
b.+     #       b <- 2*b
}if       #     end if
.         #     create dummy value
}*          #   end if
;           #   drop (i.e. either the dummy or the character)
}/            # end for
;             # discard current bet value
``````

5

# Python 2，72 68 62字节

``````def g(a,s,n=1):
for c in s:
if a>=n:a,n=((a+n,1),(a-n,2*n))[c<'W']
return a``````

``````import random
def g(a,s,n=1):
for c in s:
if a>=n:a,n=((a+n,1),(a-n,2*n))[c<'W']
return a

for i in range(14):
s=''.join(('L','W')[random.randint(0, 1)] for e in range(random.randint(10, 15)))
print'g(%i,%s):'%(i,`s`),
print g(i,s)``````

``````g(0,'LLWWWWWWLWWWWW'): 0
g(1,'WLLWWWWWWWW'): 1
g(2,'WWWLLLWLLW'): 2
g(3,'LLLLWLWLWWWWLL'): 0
g(4,'LWWWWLWLWWW'): 12
g(5,'WWLWWLLWWW'): 12
g(6,'LLLWWWLLLLWLLWL'): 3
g(7,'WWLLWWLWLWLWLLL'): 7
g(8,'WLLLWWWWWLLWLL'): 2
g(9,'WWWLLWLLLLLWL'): 6
g(10,'LWWWWLLLWL'): 7
g(11,'WLLLLWLWWWW'): 5
g(12,'WLLWWLWWWL'): 17
g(13,'LLLWLLWLWLWLWW'): 6``````

``````import random
def g(a,s,n=1):
for c in s:
if a>=n:a,n=((a+n,1),(a-n,2*n))[c<'W']
return a

r=[]
for i in range(5000):
for i in range(1000):
s=''.join(('L','W')[random.randint(0, 1)] for e in range(random.randint(10, 15)))
r+=[i-g(i,s)]
a=0
for n in r:
a+=n
print float(a)/len(r)``````

``-0.0156148``

2014年

@Howard Hmm。我尝试了这个`b,n=`技巧（`[`在外面带有s），但是python抱怨。让我们再试一次。

1

Danny

1
@Quincinx：不，<仅表示小于。串字典顺序，所以“L” <“W”返回true，这被解释为1，而“W” <“W”返回FALSE，其被解释为0。
isaacg

4

### R，95个字符

``````g=function(a,r){n=1;for(i in 1:nchar(r)){s=substr(r,i,i);if(s=='L'){a=a-n;n=n*2}else{a=a+n;n=1};if(n>a)break};a}
``````

``````g=function(a,r){
n=1
for(i in 1:nchar(r)){
s=substr(r,i,i)
if(s=='L'){
a=a-n
n=n*2
}else{
a=a+n
n=1
}
if(n>a)break
}
a
}
``````

``````> g(15,'LLWLLLL')
[1] 1
> g(20,'WLLW')
[1] 22
> g(13,'LLWLLLLWWLWWWLWLWW')
[1] 7
``````

3

# J- 63 55字符

``````((+/\@,(0{<#[)_,~|@]);@('W'<@(2^i.@#);.1@,}:)*_1^=&'L')
``````

``````;@('W'<@(2^i.@#);.1@,}:)*_1^=&'L'   NB. win/loss as sole argument
_1^=&'L'   NB. -1 for every L, +1 for W
<@(      );.1                 NB. split vector into streaks:
'W'              ,}:             NB.  cut on wins, shift right by 1
2^i.@#                     NB. for each, make doubling run
;@(                    )*           NB. unsplit, multiply by signs

(+/\@,(0{<#[)_,~|@])   NB. money on left, above result on right
|@]    NB. absolute value of bets
_,~       NB. append infinity to end
+/\@,                 NB. partial sums with initial money
(  <  )          NB. 1 whenever money in account < bet
#[           NB. select those money values corresp. to 1s
0{              NB. take first such item
``````

``````   15 ((+/\@,(0{<#[)_,~|@]);@('W'<@(2^i.@#);.1@,}:)*_1^=&'L') 'LLLWLLLL'
1
NB. naming for convenience
f =: ((+/\@,(0{<#[)_,~|@]);@('W'<@(2^i.@#);.1@,}:)*_1^=&'L')
20 f 'WLLW'
22
2 f 'LW'
1
13 f 'LLWLLLLWWLWWWLWLWW'
7
12 13 14 15 28 29 30 31 (f"0 _) 'LLWLLLLWWLWWWLWLWW'  NB. for each left argument
6 7 0 1 14 15 39 40
``````

2

TheSoftwareJedi 2014年

@TheSoftwareJedi是的，这是正确的。现在，实际上有一个J解释器的在线Javascript版本，您可以在tryj.tk上尝试。
algorithmhark

TheSoftwareJedi 2014年

3

# 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
``````

nderscore，2014年

MT0

-1个字节：`a>=b&&(c=r[t])?g((c=c>'L')?a+b:a-b,r,t+1,c||2*b):a`
nderscore 2014年

1

# Python，74个字节

``````def g(a,r,b=1):
for l in r:
if l>"L":a+=b;b=1
else:a-=b;b*=2
return a
``````

``````print g(20,"WLLW") # 22
print g(15,"LLLWLLLL") # 1
``````

1

# C，107个字符

``f(int a,char*r,int n){return*r&&n<a?*r<77?f(a-n,r+1,n*2):f(a+n,r+1,1):a;}g(int a, char*r){return f(a,r,1);}``

``````f(int a,char*r,int n){
return *r&&n<a
?*r<77
?f(a-n,r+1,n*2)
:f(a+n,r+1,1)
:a;
}
g(int a,char*r){
return f(a,r,1);
}``````

1

# C，90

``````g(int a,char*r){int c=1;while(*r){*r++%2?c=1,a++:(c*=2);if(c>a){c/=2;break;}}return++a-c;}
``````

1

# Javascript，63

``````function g(a,s){x=1;for(i in s)if(x<=a)s[i]>'L'?(a+=x,x=1):(a-=x,x*=2);return a}
``````

``````console.log(g(15, 'LLLWLLLL'));  //1
console.log(g(20, 'WLLW'));  //22
console.log(g(13, 'LLWLLLLWWLWWWLWLWW')); //7
``````

``````function g(a,s){
x=1;                //bet starts at 1
for(i in s)         //loop through win/lose string
if(x<=a)          //check if we still have money to bet
s[i]>'L'?
(a+=x,x=1):   //win: add the bet amount to your total, and reset bet to 1
(a-=x,x*=2);  //lose: subtract the bet amount from your total, and double your bet
}
``````

1

# 函数内的Javascript（ES5）69 64 60字节

``function g(a,r){b=1;for(i in r)b=b>a?b:r[i]>'L'?(a+=b,1):(a-=b,b*2);return a}``

``function g(a,r,b){for(i in r)b=b?b>a?b:r[i]>'L'?(a+=b,1):(a-=b,b*2):1;return a}``

``````g(15,'LLWLLLL'); // 1
g(20,'WLLW'); // 22
g(13,'LLWLLLLWWLWWWLWLWW'); // 7``````

`g(20,'WLLW')`在我的FireFox控制台中返回25- `for...in`循环拾取字符串中的三个额外属性，并对其进行迭代。
MT0

@ MT0在我的Firefox控制台中也会发生同样的事情。但是，如果我打开一个新的私人浏览窗口，则会进入`22`控制台。考虑一下打开控制台后您所访问的某个站点会修改`String`原型。我知道stackexchange确实会对其进行修改并添加三个额外的功能。
Danny

nderscore 2014年

1

# 哈斯克尔（62）

``````g a=fst.foldl(\(t,b)l->if l=='W'then(t+b,1)else(t-b,2*t))(a,1)
``````

``````g a r=fst\$foldl(\(t,b)l->if l=='W'then(t+b,1)else(t-b,2*t))(a,1)r
``````

``````g a r=a+1+l(filter(=='W')r)-2^l(takeWhile(/='W')(reverse r))
l=length
``````

PetrPudlák'14

Zaq 2014年

@zaq其实是的，问题明确表明是这种情况。
TheSoftwareJedi 2014年

1

# Python 2 – 65字节

``````def g(r,a,b=1):
if r>"">a>=b:a=g(r[1:],*[(a+b,1),(a-b,b*2)][r[0]<"W"])
return a``````

1

# Ruby，76个64（在函数体内）字节

``````n=1;r.each_char{|c|;c>'L'?(a+=n;n=1):(a-=n;n*=2);break if n>a};a
``````

``````def g(a,r);n=1;r.each_char{|c|;c>'L'?(a,n=a+n,1):(a,n=a-n,n*2);break if n>a};a;end
``````

``````g=->a,r{n=1;r.each_char{|c|;c>'L'?(a,n=a+n,1):(a,n=a-n,n*2);break if n>a};a}
``````

``````p g.call(15, 'LLLWLLLL') # 1
p g.call(20, 'WLLW') # 22
p g.call(13, 'LLWLLLLWWLWWWLWLWW') # 7
``````

1

# C＃，方法内部74个字符

``````int b=1;foreach(var c in r)if(b<=a){a+=c>'L'?b:-b;b=c>'L'?1:b*2;}return a;
``````

``````int bet = 1;
foreach (var chr in r)
{                       // these brackets are left out in short version
if (bet <= a)
{
a += chr > 'L' ? bet : -bet;
bet = chr > 'L' ? 1 : bet * 2;
}
}
return a;
``````

1

# Golfscript，51 41 36 35字节

### 内部功能

``````1\{@2\$-@2*@(1&{@@+1@}*.3\$3\$<!*}do;;
``````

### 例

``````{
# Push initial bet amount.
1\
# STACK: Money Bet Outcomes
{
# Subtract bet amount from money.
@2\$-
# STACK: Bet Outcomes Money
# Double bet amount.
@2*
# STACK: Outcomes Money Bet
# Remove first character from win-loss string and check if its ASCII code is odd.
@(1&
# STACK: Money Bet Outcomes Boolean
# If it is, we've won, so add the doubled bet amount to the money and push 1 as the
# new bet amont.
{@@+1@}*
# STACK: Money Bet Outcomes
# Duplicate win-loss string, bet amonut and money.
.3\$3\$
# STACK: Money Bet Outcomes Outcomes Bet Money
# If the next bet amount is less than our money and the win-loss string is not empty,
# repeat the loop.
<!*
# STACK: Money Bet Outcomes Boolean
}do
# STACK: Money Bet Outcomes
;;
# STACK: Money
}:f                                      # Define function.

];                                       # Clear stack.

20 'WLLW'               f
2  'LW'                 f
13 'LLWLLLLWWLWWWLWLWW' f
14 'LLWLLLLWWLWWWLWLWW' f

]p                                       # Print results as array.
``````

``````[22 1 7 0]
``````

1

## C＃，123

``return q.Aggregate(new{b=1,c=w,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;``

.NET小提琴

TheSoftwareJedi 2014年

TheSoftwareJedi 2014年

0

# Ruby，84个字符

``````def g(a,r,n=1)
return a if !r[0]||n>a
s=r[1..-1]
r[0]<?M?g(a-n,s,n*2):g(a+n,s,1)
end
``````

0

# K，76

``````g:{x+/-1_last'{(,1_*x),(("LW"!/:((2*;{1});(-:;::)))@\:**x)@\:x 1}\[(y;1;0)]}
``````

``````k)g[15;"LLLWLLLL"]
1
k)g[20;"WLLW"]
22
k)g[50;"WLLLWLWLWLWLW"]
56
``````

0

# Python，86

``````def y(a,s):
for l in s.split('W'):
a+=1;k=2**len(l)
if k>a:return int(bin(a)[3:],2)
return a-k``````

0

# C- 64 59（内部功能）

``````f(int s,char*r){
int a=1;
for(;*r&&(*r++%2?s+=a,a=1:s<a?0:(s-=a,a*=2)););
a=s;
}``````

0

## 批次-212

``````@echo off&setlocal enabledelayedexpansion&set r=%2&set a=%1&set c=1&powershell "&{'%2'.length-1}">f&set/pl=<f
for /l %%a in (0,1,%l%)do if "!r:~%%a,1!"=="L" (set/aa-=!c!&set/ac*=2) else set/aa+=!c!&set c=1
echo %a%
``````

``````H:\uprof>bet.bat 15 LLLWLLLL
1
``````

0

# Japt，38个字节

``````V¬r@Z=WX<Z?X:Y¶'L?W=ZÑX-Z:(W=1X+Z}UW=1
``````

Transpiled JS解释：

``````// V: input string of W's and L's
V
// split V into an array of characters
.q()
// reduce
.r(function(X, Y, Z) {
return
// W contains the current bet,
// save it to a temp variable Z
Z = W,
// do we have enough to bet?
X < Z
// not enough to bet, return the previous amount
? X
// we can bet, did we lose this round
: Y === "L"
// we lost, increment bet and decrease holdings
? (W = Z * 2, X - Z)
// we won, reset bet and increase holdings
: (W = 1, X + Z)
},
// U: initial holdings
U,
// initialize bet to 1
W = 1
)
``````

0

# PowerShell，68 81字节

``param(\$n,\$s)\$w=1;\$s|% t*y|%{if(\$n-ge\$w){\$n+=(-\$w,\$w)[\$_%2];\$w/=(.5,\$w)[\$_%2]}};\$n``

0

# 05AB1E，19 个字节

``````vDX@iy'WQiX+1UëXxU-
``````

@Howard的GolfScript答案端口，因此请确保也对他进行投票

``````v               # Loop over each character `y` of the (implicit) input-string:
D              #  Duplicate the current integer
#  (which is the implicit input-integer in the first iteration)
X@i           #  If the integer is larger than or equal to variable `X`:
#  (NOTE: variable `X` is 1 by default)
y'WQi     '#   If the current character `y` is a 'W':
X+    #    Increase the integer by `X`
1U    #    And reset variable `X` to 1
ë      #   Else (the current character `y` is an 'L' instead):
X  -  #    Decrease the integer by `X`
xU   #    And set variable `X` to double its current value
# (the integer at the top of the stack is implicitly output after the loop)``````