I've seen something like:
def matInit(n:Int):Array[Array[Int]]={
val maxval=5
val rnd=new Random(100)
Array.tabulate(n){_=>Array.tabulate(n){_=>rnd.nextInt(maxval 1) 1}}
}
but in this template above, the way of initialization is complicated, and the number of rows and columns is equal. Is there an improved way based on it? Thanks.
CodePudding user response:
Array.fill
allows creating of 2D arrays and makes the logic a bit simpler.
def matInit(n: Int, m: Int): Array[Array[Int]] = {
val maxval = 5
val rnd = new Random(100)
Array.fill(n, m)(rnd.nextInt(maxval 1) 1)
}
This works because fill
takes a by name argument which means that the expression is evaluated for each element in the new Array
rather than being calculated once and passed as a value.