# Here is a closed-form approximation that works well enough:
probRunKofN <-function(n,k,p)
{ alpha <- function(n,k,p)
{ rho <- (1 - k * (1 - p) * p^k) / (1 - (k + 1) * (1 - p) * p^k)
(1 / rho^(n+1)) * (1 / (1 - (k + 1) * (1 - p) * p^k * rho^k))
}
1 - alpha(n,k,p) + p^k * alpha(n-k,k,p)
}
# Test it:
n <- 20
k <- 5
p <- 1/2
probRunKofN(n,k,p)
>> 0.2486627
There is also a two-line recursive function that gives an exact answer. I'll post it later or over the weekend if I have time. Also an exact closed-form n-state Markov representation but I haven't seen that one coded up algebraically.
probRunKofN <-function(n,k,p)
{ alpha <- function(n,k,p)
{ rho <- (1 - k * (1 - p) * p^k) / (1 - (k + 1) * (1 - p) * p^k)
(1 / rho^(n+1)) * (1 / (1 - (k + 1) * (1 - p) * p^k * rho^k))
}
1 - alpha(n,k,p) + p^k * alpha(n-k,k,p)
}
# Test it:
n <- 20
k <- 5
p <- 1/2
probRunKofN(n,k,p)
>> 0.2486627
There is also a two-line recursive function that gives an exact answer. I'll post it later or over the weekend if I have time. Also an exact closed-form n-state Markov representation but I haven't seen that one coded up algebraically.