Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Monte Carlo Simulation
- /*
- -> The program creates a n*n grid filled with zeros
- -> It starts puting 1's in random places
- -> When there is a path of 1's connecting top and bottom it stops
- */
- object monteCarloPercolation{
- class MonteCarloFiller(val n:Int) {
- val rnd = new scala.util.Random
- val monteAr = Array.fill[String](n,n)("0")
- val boxes = Array.fill[Int](n*n)(-1)
- // CoordsToOneDimension
- def ctod(i : Int , j : Int) : Int = n*i + j
- def addRanomPiece() = {
- val i = rnd.nextInt(n)
- val j = rnd.nextInt(n)
- monteAr(i)(j) = "1"
- (i,j)
- }
- def union(p:Int , q:Int) {
- val pboxes = boxes(p)
- val qboxes = boxes(q)
- (0 until boxes.length).foreach{ i =>
- if ( boxes(i) == pboxes ) boxes(i) = qboxes
- }
- }
- def hasPercolated() : (Boolean , Int) = {
- // check if the virtual top side is
- // connected to the virtual bottom side
- for (i<-0 until n){
- for (j<-n*(n-1) until n*n){
- if ( boxes(i) == boxes(j) && boxes(i) != -1 ) {
- return (true , i)
- }
- }
- }
- (false , -1)
- }
- def getNeighbors( i : Int , j : Int ) = {
- var neighbors: List[Int] = List.empty
- try{
- if ( monteAr( i - 1 )(j) != "0")
- neighbors = ctod( i - 1 , j) :: neighbors
- }
- catch {case e:Exception =>}
- try {
- if ( monteAr( i + 1 )(j) != "0")
- neighbors = ctod( i + 1 , j) :: neighbors
- }catch{case e:Exception =>}
- try {
- if ( monteAr( i )(j - 1) != "0")
- neighbors = ctod( i , j - 1) :: neighbors
- }catch{case e:Exception =>}
- try {
- if ( monteAr( i )(j + 1) != "0")
- neighbors = ctod( i , j + 1) :: neighbors
- }catch{ case e:Exception => }
- neighbors
- }
- def doUntilPercolation() : Int = {
- def inner(times:Int) : Int = {
- val per = hasPercolated()
- if ( per._1 ) return times
- else {
- val coords = addRanomPiece()
- val sumindex = ctod( coords._1 , coords._2 )
- val neighbors = getNeighbors( coords._1 , coords._2)
- boxes(sumindex) = sumindex
- for ( i<-0 until neighbors.length ) {
- union(sumindex , neighbors(i) )
- }
- }
- inner(times+1)
- }
- inner(0)
- }
- def showArray() {
- println("-"*20)
- for (i<-0 until n){
- for (j<-0 until n){
- print(monteAr(i)(j) + " ")
- }
- println()
- }
- println("-"*20)
- }
- }
- def main(args: Array[String]): Unit = {
- val mc = new MonteCarloFiller(10)
- mc.doUntilPercolation()
- mc.showArray()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement