How to resolve the algorithm Forest fire step by step in the Scala programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Forest fire step by step in the Scala programming language

Table of Contents

Problem Statement

Implement the Drossel and Schwabl definition of the forest-fire model.

It is basically a 2D   cellular automaton   where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia) Neighborhood is the   Moore neighborhood;   boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition). At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve. Task's requirements do not include graphical display or the ability to change parameters (probabilities   p   and   f )   through a graphical or command line interface.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Forest fire step by step in the Scala programming language

Source code in the scala programming language

import scala.util.Random

class Forest(matrix:Array[Array[Char]]){
  import Forest._
  val f=0.01;	 // auto combustion probability
  val p=0.1;	 // tree creation probability
  val rows=matrix.size
  val cols=matrix(0).size

  def evolve():Forest=new Forest(Array.tabulate(rows, cols){(y,x)=>
    matrix(y)(x) match {
      case EMPTY => if (Random.nextDouble<p) TREE else EMPTY
      case BURNING => EMPTY
      case TREE => if (neighbours(x, y).exists(_==BURNING)) BURNING 
                  else if (Random.nextDouble<f) BURNING else TREE
    }
  })
  
  def neighbours(x:Int, y:Int)=matrix slice(y-1, y+2) map(_.slice(x-1, x+2)) flatten
  override def toString()=matrix map (_.mkString("")) mkString "\n"
}

object Forest{
  val TREE='T'
  val BURNING='#'
  val EMPTY='.'
  def apply(x:Int=30, y:Int=15)=new Forest(Array.tabulate(y, x)((y,x)=> if (Random.nextDouble<0.5) TREE else EMPTY))
}


object ForestFire{
  def main(args: Array[String]): Unit = {
    var l=Forest()
    for(i <- 0 until 20){
      println(l+"\n-----------------------")
      l=l.evolve
    }
  }
}


  

You may also check:How to resolve the algorithm Use another language to call a function step by step in the Pascal programming language
You may also check:How to resolve the algorithm FTP step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Create an HTML table step by step in the Visual Basic .NET programming language
You may also check:How to resolve the algorithm Runtime evaluation step by step in the Caché ObjectScript programming language
You may also check:How to resolve the algorithm A+B step by step in the Scratch programming language