user3316676
user3316676

Reputation: 109

Is there a way to fill a multi-dimensional array using Range class of Scala

I want to create a 2-d array in Scala. This array partitions a 2-d space into N blocks. Each element of this array has a minX,maxX, minY, and maxY values and an index (from 0 to N^2-1).

For example, if N=8, I want to create indices from 0 to 63, and each index corresponds to a range in space. If I have the minX, maxX, minY, maxY of the whole space, is there any way to use Scala's Range class to provide a step value in both x and y dimensions and create this array with index and individual ranges?

This is the class and function I am creating:

class Grid (index: Int, minX: Double, minY: Double, maxX: Double, maxY: Double){
  def buildgrid(spaceminX: Double, spaceminY: Double, spacemaxX: Double, spacemaxY: Double,num_partitions:Int): Unit =
  {
    val stepX=spacemaxX-spaceminX/num_partitions
    val stepY=spacemaxY-spaceminY/num_partitions
    ???

  }}

Here, the variables prefixed with space are the values for the whole space that needs to be divided into N blocks. I am stuck at how to create the array in the function. The expected output of this array would be: Array[(0,minX,maxX,minY,maxY),(1, minX,maxX, minY, maxY)...,(63, minX,maxX,minY,maxY)]

Upvotes: 0

Views: 875

Answers (2)

codenoodle
codenoodle

Reputation: 994

You could use a for comprehension:

object Example {

  def main(args: Array[String]): Unit = {
    /*
     X 0  1  2  3
    Y+--+--+--+--+
    0| 0| 1| 2| 3|
    1| 4| 5| 6| 7|
    2| 8| 9|10|11|
    3|12|13|14|15|
     +--+--+--+--+
    */

    val minX = 0
    val maxX = 3
    val minY = 0
    val maxY = 3

    val list = (for {
      y <- 0 to maxY-minY
      x <- 0 to maxX-minX
    } yield (y * (maxX-minX+1) + x, minX, maxX, minY, maxY)).toList

    println(list)
  }

}

Upvotes: 0

Tim
Tim

Reputation: 27421

All collections (including Array) have a single dimension and are indexed from 0. For a 2D Array you either need to compute the index yourself, or use a nested array Array[Array], and you will need to deal with the min_ offset with either option.

The library has support for creating nested Arrays. You can fill a 2D array with a fixed value by using Array.fill:

val array = Array.fill(n1, n2)(value)

Or you can fill with a computed value for each coordinate using tabulate:

val array = Array.tabulate(n1, 22){ case (a, b) => func(a, b) }

Note: Array.fill will compute value for each element of the Array so make sure you pass a value not an expression.

Upvotes: 3

Related Questions