Skip to content

Instantly share code, notes, and snippets.

@awostenberg
Last active September 3, 2020 18:33
Show Gist options
  • Save awostenberg/5c55557217a2fc1301fdd0d91d0b1264 to your computer and use it in GitHub Desktop.
Save awostenberg/5c55557217a2fc1301fdd0d91d0b1264 to your computer and use it in GitHub Desktop.
scala random walk over a unit cube
// Consider an ant taking a random walk over corners of a cube.
// What are the average number of steps to arrive at the far corner?
// user interface is next line: you can change the sample size
val nSamples = 100_000
abstract class Direction
case class X() extends Direction
case class Y() extends Direction
case class Z() extends Direction
// walk one step along the given direction
def along(n:Int) = if (n==0) 1 else 0
def walk(point:Tuple3[Int,Int,Int], d: Direction) =
//var x,y,z = point //why not?
d match {
case X() => (along(point._1),point._2,point._3)
case Y() => (point._1,along(point._2),point._3)
case Z() => (point._1,point._2,along(point._3))
}
def toDirection(n:Int) = if (n==0) X() else if (n==1) Y() else Z()
val one = (0,0,0)
val two = walk(one,X())
val three = walk(two,Y())
val four = walk(three,Z())
println (one,two,three,four)
val r = scala.util.Random
// random direction dispenser
def randir =
// val r = scala.util.Random // why not?
() => toDirection(r.nextInt(3))
// run one simulation
def simant (here:Tuple3[Int,Int,Int], rdd:() => Direction):Int =
if (here==(1,1,1)) 0 else 1+simant( walk(here,rdd()), rdd)
println("test run")
println(s"done in ${simant((0,0,0),randir)}")
println(s"${nSamples} ants walking")
val results = new Array[Int](nSamples)
for (i <- 0 until nSamples)
results(i) = simant((0,0,0),randir)
val average = results.sum * 1.0 / nSamples
println(s"average=$average")
println(s"max=${results.max}")
val sortedResults = results.sorted
println(s"median=${sortedResults(nSamples/2)}")
//todo https://docs.scala-lang.org/overviews/parallel-collections/overview.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment