2d scala array iteration

I have a 2d array of type boolean (not important) It is easy to iterate over an array in a non-functional style. How to do this FP style?

var matrix = Array.ofDim[Boolean](5, 5) 

for ex, I would like to iterate over all the rows for a given column and return an int list that matches a specific function. Example: for column 3 iterations over rows 1 to 5 to return 4, 5 if the cell in (4, 3), (5, 3) corresponds to a certain function. thanks v much

def getChildren(nodeId: Int) : List[Int] = {
    info("getChildren("+nodeId+")")

    var list = List[Int]()
    val nodeIndex = id2indexMap(nodeId)

    for (rowIndex <- 0 until matrix.size) {
      val elem = matrix(rowIndex)(nodeIndex)
      if (elem) {
        println("Row Index = " + rowIndex)
        list = rowIndex :: list
      }
    }

    list
  }
+5
source share
3 answers

What about

(1 to 5) filter {i => predicate(matrix(i)(3))}

where predicateis your function?

Note that it is initialized with (5.5) indices from 0 to 4.

Update : based on your example

def getChildren(nodeId: Int) : List[Int] = {
  info("getChildren("+nodeId+")")
  val nodeIndex = id2indexMap(nodeId)

  val result = (0  until matrix.size).filter(matrix(_)(nodeIndex)).toList
  result.forEach(println)
  result
}

, , , , ,

+4

, , :

for {
  rowIndex <- matrix.indices
  if matrix(rowIndex)(nodeIndex)
} yield { 
  println("Row Index = " + rowIndex)
  rowIndex
}

yield , , . seq.indices - , 0 until seq.size. , , :

for (rowIndex <- matrix.indices; if matrix(rowIndex)(nodeIndex)) yield rowIndex

, , Array, . -

for {
  row  <- matrix 
  elem <- row
} yield f(elem)

, , ( , , ). , Map[Int, Boolean] case class .

+2
def findIndices[A](aa: Array[Array[A]], pred: A => Boolean): Array[Array[Int]] =
  aa.map(row => 
    row.zipWithIndex.collect{ 
      case (v,i) if pred(v) => i 
  }
)

You can reorganize it a little better by extracting a function that finds indexes on only one line:

def findIndices2[A](xs: Array[A], pred: A => Boolean): Array[Int] =
  xs.zipWithIndex.collect{ 
    case (v,i) if pred(v) => i 
  }

And then write

matrix.map(row  => findIndices2(row, pred))
+1
source

All Articles