繁体   English   中英

在Scala中访问列表中的索引

[英]Accessing an index in a list in Scala

我必须编写一个方法“ all()”,该方法返回一个元组列表; 当函数在列表中满足0时,每个元组将包含与特定给定行和列相关的行,列和集合。 我已经编写了“ hyp”函数,该函数返回所需的设置部分,例如:Set(1,2)。 我正在使用列表列表:

| 0 | 0 | 9 |
| 0 | x | 0 |
| 7 | 0 | 8 |

如果Set(1,2)引用标记为x的单元格,则all()应该返回:(1,1,Set(1,2))其中1,1是行和列的索引。

我通过使用zipWithIndex编写了此方法,但无法使用此功能。 在这种情况下,有没有更简单的方法来访问索引? 提前致谢

码:

 def all(): List[(Int, Int, Set[Int])] = 
 {
    puzzle.list.zipWithIndex flatMap 
    { 
      rowAndIndex =>
      rowAndIndex._1.zipWithIndex.withFilter(_._1 == 0) map 
      { 
        colAndIndex =>
        (rowAndIndex._2, colAndIndex._2,  hyp(rowAndIndex._2, colAndIndex._2)) 
      }
    }
 } 

(_._ 1 == 0)是因为该函数仅在网格中找到0时才必须返回(Int,Int,Set())

all函数可以简化为:

// Given a list of list
puzzle.list = List(List(0, 0, 9), List(0, 5, 0), List(7, 0, 8))

for {

  (row, rIndex) <- puzzle.list.zipWithIndex   // List of (row, index)
                                              // List( (List(0,0,9), 0) ...

  (col, cIndex) <- row.zipWithIndex;          // List of (col, index)
                                              // List( (0,0), (0,1), (9, 2) ...

  if (col == 0)                               // keep only col with 0

} yield (rIndex, cIndex, hyp(rIndex, cIndex))   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM