Initializing a 2-dimensional array in Scala

(Scala 2.7.7 :) I'm not used to 2d arrays. Arrays are mutable, but how can I specify a 2d array that is, say, 3x4 in size. Dimension (2D) is fixed, but the size of each dimension must be initialized. I've tried this:

class Field (val rows: Int, val cols: Int, sc: java.util.Scanner) {
 var field = new Array [Char](rows)(cols)

 for (r <- (1 to rows)) {
  val line = sc.nextLine ()
  val spl = line.split (" ")
  field (r) = spl.map (_.charAt (0))
 }

   def put (row: Int, col: Int, c: Char) =
       todo ()
}

      

I am getting this error:: 11: error: update value is not a member Char field (r) = spl.map (_. CharAt (0))

If it were Java, this would be a lot more code, but I would know how to do it, so I show what I mean:

public class Field
{
 private char[][] field;

 public Field (int rows, int cols, java.util.Scanner sc) 
 {
  field = new char [rows][cols]; 
  for (int r = 0; r < rows; ++r) 
  {
   String line = sc.nextLine ();
   String[] spl = line.split (" ");
   for (int c = 0; c < cols; ++c)
    field [r][c] = spl[c].charAt (0);
  }
 }

 public static void main (String args[])
 {
  new Field (3, 4, new java.util.Scanner ("fraese.fld"));
 }
}

      

and fraese.fld would look like this:

M M M 
M . M 

      

I am doing several steps with

val field = new Array [Array [Char]](rows)

      

but how could I implement "put"? Or is there a better way to implement a 2D array. Yes, I could use a one-dimensional matrix and work with

put (y, x, c) = field (y * width + x) = c

      

but I would prefer a notation that looks more than 2d-ish.

+2


a source to share


1 answer


for (r <- (1 to rows)) {

      

If it is true:

for (r <- (0 to rows - 1)) {

      

... starting at 0 instead of 1?

field (r) = spl.map (_.charAt (0))

      

If it uses operator syntax like:



field (r) = spl map (_.charAt (0))

      

... without the "." between spl and map?


This is my version - I replaced Scanner with Array [String] as I'm not really sure what the input for the scanner should be. It compiles and runs on Scala 2.7.5:

class Field (val rows: Int, val cols: Int, lines: Array[String]) {
    var field = new Array [Array[Char]](rows)

    // These get replaced later on, but this is how to initialize a 2D array.
    for (i <- (0 to rows - 1)) {
        field(i) = new Array[Char](cols)
    }

    for (r <- (0 to rows - 1)) {
        val line = lines(r)
        val spl = line.split (" ")
        field(r) = spl map (_.charAt (0))
    }
}

var lines = Array[String] ("A A A A A", "B B B B B", "C C C C C", "D D D D D", "E E E E E")
var test  = new Field(5, 5, lines)
test.field

      

+2


a source







All Articles