Incremental Betting
Python 2, 72 68 62 bytes
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
Call it like so: g(15,'LLLWLLLL')
.
This simply loops through the string, changing the value of the money that we have based on the character.
Here is a sample program that runs tests on this function:
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
With a little change to the tester, we can get the average profit of many runs:
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)
Sample output (took quite a while, since we are calling the function 5000000
times):
-0.0156148
Edit: Thanks to Howard and Danny for further golfing.
EDIT: now the program checks for whether there is enough money to make the bet. This actually saves bytes.
GolfScript, 33 characters
{
1\{2$2$<!{1&{+1}{:b-b.+}if.}*;}/;
}:g;
Examples (online):
> 13 'LLLWLLLL'
6
> 4 'LWWLWLWWWL'
9
> 5 'LLLWWWLLWLWW'
2
> 2 'LW'
1
Annotated code:
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
R, 95 characters
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}
Indented:
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
}
Usage:
> g(15,'LLWLLLL')
[1] 1
> g(20,'WLLW')
[1] 22
> g(13,'LLWLLLLWWLWWWLWLWW')
[1] 7