Hacker News new | ask | show | jobs
by bacr 5189 days ago
Nice simulation work! Initially I thought this was a one dimensional random walk problem where the answer is a function of n (as other comments have pointed out). In that case, there (n choose k) paths that take k steps in a single direction of n total steps, and each occurs with p(0.5^n). In this problem we are given n, but not k. Given a starting point, we can easily calculate the probability of crossing 0.

So my question is, how are you dealing with the initial condition?

1 comments

The initial condition is assigned to you randomly, from the closed interval [1,1000].

Suppose there were [1,k] spots. You are assigned an intial value from [1,k] and you then have to reach 0 before time t=k. Here's my code to solve the general case

     object particle {
       def main(args:Array[String]) = {
         val simulations = args(0).toInt
         val rng = new util.Random
    
         (2 to 1000).foreach(spots=>{
             val reachedZero = (1 to simulations).map(_=> {
               var t = 0
               var z = 1+rng.nextInt(spots)     
               do {
                 z += {if (rng.nextBoolean) 1 else -1}
                 t +=1
               } while( z != 0 && t<spots)
               z==0
             })
             val prob = reachedZero.count(_==true)*1.0d/simulations
             printf("%4d spots: %.4f\n",spots,prob )
           })
       }
     }

     >scala particle 1000000
     2	0.3773
     3	0.329
     4	0.292
     5	0.2714
     6	0.2624
     7	0.2428
     8	0.2247
     9	0.222
     10	0.2157
     ....
So your chances drop from 37% to 21% as the interval expands to 10 spots. At 100 spots, its 8%. By 1000 spots, you have a meager 2.5% chance of crossing 0 before 1000 seconds.