【问题标题】:Finding index of row from a list从列表中查找行的索引
【发布时间】:2013-11-30 09:18:56
【问题描述】:

我正在尝试使用 Scala 从由整数列表 List[List[Int]] 组成的列表中获取行的索引。我已经有两个函数,将行索引/列索引和网格作为参数,它输出该行中的所有元素。我需要的是一个给定特定元素的函数(例如:0),它会找到它的行索引和列索引并将它们放在一个列表中:List[(Int, Int)]。我尝试编写一个在遇到 0 时返回索引的函数,然后将该函数传递给整个网格。我不知道我的做法是否正确。另外,我不知道如何返回列表。

另外,我不能使用任何循环。

提前致谢。

 def Possibilities(): List[Int] =  {

     def getRowIndex(elem: Int): Int = elem match
   {
     case 0 => sudoku.grid.indexOf(sudoku.row(elem))
     case x => x
    } 

 val result1 = sudoku.grid map {row => row map getRowIndex}
}

【问题讨论】:

    标签: list scala search scala-collections


    【解决方案1】:

    我认为在二维情况下使用for 理解编写这样的方法要容易得多。

    给定一个像这样的List[List[Int]]

    val grid = List(
         List(1, 2, 3),
         List(4, 5, 6),
         List(3, 2, 1))
    

    我们可以简单地遍历所有的行和列,并检查每个元素是否是我们正在寻找的元素:

    def possibilities(findElem: Int): List[(Int, Int)] = {
      for (
        (row, rowIndex) <- grid.zipWithIndex;
        (elem, colIndex) <- row.zipWithIndex
        if elem == findElem
      ) yield (rowIndex, colIndex)
    }
    

    yield 关键字创建for 循环结果的集合。您可以找到有关 Scala 的 forloop 语法 here 的更多详细信息(以及关于这与 mapflatMaphere 的关系的更全面讨论)。

    因此,如果您不想使用for 循环,只需使用map 将其“翻译”为等效表达式。 flatMap,和withFilter

    def possibilities(findElem: Int): List[(Int, Int)] = {
      grid.zipWithIndex flatMap { rowAndIndex =>
        rowAndIndex._1.zipWithIndex.withFilter(_._1 == findElem) map { colAndIndex =>
          (rowAndIndex._2, colAndIndex._2)
        }
      }
    } 
    

    【讨论】:

    • 我被限制使用任何循环
    • 啊,抱歉 --- 没有意识到这一点。没问题,for 推导可以映射到mapflatMap 等的组合(参见artima.com/pins1ed/for-expressions-revisited.html)。
    • 能否解释一下这条线的作用:grid.zipWithIndex
    • zipWithIndex 由列表定义(参见此处:scala-lang.org/api/current/…);它将一个列表(如List("Alice", "Bob"))转换为一个列表,其中每个元素都包含一个原始元素的元组及其索引(例如,对于上面的示例:List(("Alice",0), ("Bob", 1)))。只需使用 Scala REPL 并使用它! :-)
    • 并非所有方法都是错误的(例如,您认为应该使用map),但某些方面是错误的(例如possibilities 的签名应该返回List[(Int,Int)]),并且在其他方面,您的解决方案只是不完整的(例如,需要返回索引)。我建议您只是在 REPL 中使用代码,并阅读所有重要主题以解决任务(例如for 表达式、元组、List)。
    【解决方案2】:

    第 1 步,使用 for 理解创建所有可能的索引元组的集合(for 看起来像一个循环,但实际上不是)

    val tuples = for (i <- grid.indices; j <- grid.head.indices) yield (i, j)
    

    第 2 步,过滤此集合

    tuples.filter { case (i, j) => grid(i)(j) == valueToFind }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 2019-05-27
      • 2013-01-07
      相关资源
      最近更新 更多