【问题标题】:Accessing an index in a list in Scala在 Scala 中访问列表中的索引
【发布时间】:2013-12-03 23:20:58
【问题描述】:

我必须编写一个返回元组列表的方法“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())

【问题讨论】:

    标签: list scala collections


    【解决方案1】:

    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))   
    

    【讨论】:

    • 我不能使用循环,它必须是递归的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2016-09-16
    相关资源
    最近更新 更多