Search code examples
scalaarraybuffer

Scala: adding element to ArrayBuffer on index


I just started learning Scala, trying to code a simple game to learn it's syntax and some basic rules. I'd be grateful if anyone could help me with a simple problem. I created simple board filled with ".". Now I want to change one "." on the certain index and put there "X". In java it would look like this:

board[col][row] = symbol;

This is the board part:

val board = {
 collection.mutable.ArrayBuffer[String]()
 collection.mutable.ArrayBuffer.fill(cols, rows)(".")
}

def show(): Unit = {
 board.foreach(x => println(x.mkString))
}

def setField(col:Int, row:Int, fieldSymbol:String): Unit = {
 //fieldSymbol on index, which is (col*row) as it's 1d array
 //thought board.apply(col*row): fieldSymbol might work but it's not 
 //correct I guess
}

Any help would be much appreciated. Thanks in advance for advice.


Solution

  • You could implement setField for a flat array like this

    def setField(c: Int, r: Int, v: String) {
      board(c * rows + row) = v
    }
    

    This is however only a good idea if you want to store your multi dimensional data in a single array (which can be interesting if you care about allocation structure and stuff like that). In this case I would recommend to write a generic method setField though.

    If you instead want arrays of arrays fill already gives you that

    val board = ArrayBuffer.fill(rows, cols)(".")
    

    and then just update like this

    board(x)(y) = "something"
    

    You should however ask yourself whether you really need a mutable data structure and your program cannot be expressed more elegantly using immutable data structures. And also, if you really want a two dimensional vector if you want to represent something as a board of objects, especially if most of the board is "empty". It could be much more elegant to use a map:

    val board = Map[(Int, Int), String]() // empty board
    val nextBoard = bord + ((2,3) -> "something")