Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 二维scala阵列迭代_Arrays_Scala - Fatal编程技术网

Arrays 二维scala阵列迭代

Arrays 二维scala阵列迭代,arrays,scala,Arrays,Scala,我有一个布尔类型的2d数组(不重要) 以非函数式风格迭代数组很容易。 如何以FP风格进行 var matrix = Array.ofDim[Boolean](5, 5) 对于ex,我希望遍历给定列的所有行,并返回与特定函数匹配的int列表。 示例:对于第3列,如果(4,3)、(5,3)处的单元格与指定函数匹配,则遍历第1行到第5行以返回4,5。太多了 def getChildren(nodeId: Int) : List[Int] = { info("getChildren("+no

我有一个布尔类型的2d数组(不重要) 以非函数式风格迭代数组很容易。 如何以FP风格进行

var matrix = Array.ofDim[Boolean](5, 5) 
对于ex,我希望遍历给定列的所有行,并返回与特定函数匹配的int列表。 示例:对于第3列,如果(4,3)、(5,3)处的单元格与指定函数匹配,则遍历第1行到第5行以返回4,5。太多了

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
  }
def getChildren(nodeId:Int):List[Int]={
信息(“getChildren(“+nodeId+”))
变量列表=列表[Int]()
val nodeIndex=id2indexMap(nodeId)
对于(rowIndex

(1 to 5) filter {i => predicate(matrix(i)(3))}
其中
谓词
是您的函数

请注意,使用(5,5)索引初始化的值从0到4

更新:基于您的示例

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
}
如果您愿意,您也可以移动fiter中的打印,如果您愿意,也可以完全按照示例中的方式反转列表

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 
  }
)
通过提取只在一行中查找索引的函数,可以将其重构得更好一些:

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

matrix.map(row  => findIndices2(row, pred))

如果您不习惯使用过滤器和拉链,您可以坚持使用,以便理解,但可以以更实用的方式使用:

for {
  rowIndex <- matrix.indices
  if matrix(rowIndex)(nodeIndex)
} yield { 
  println("Row Index = " + rowIndex)
  rowIndex
}
还应该提到,通常情况下,如果在数组中进行迭代,则根本不需要引用索引

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

如果初始结构是2d数组,我想你的sol会返回一个数组?啊,另一个区别是我想直接在2d数组上过滤,但是这样做,我失去了行索引:val children=matrix.filter(行=>row(nodeIndex))它返回2个1d数组-但我不知道是哪一个。实际上,我所使用的结构是一个范围,而不是一个数组(因为它是您希望在输出中使用的索引)。结果类型是IndexedSeq[Int],它正好是一个向量。如果你想要一个列表,只需执行.toList,但向量通常比列表更好。这是我想要实现的非FP版本(编辑主)
for {
  row  <- matrix 
  elem <- row
} yield f(elem)