Scala迭代在由板表示的地图上

时间:2016-03-29 00:42:47

标签: list scala dictionary

我已经创建了一个解析长度为81个字符的字符串的函数。解析它时,我需要使用一个名为neighbors(Int: row, Int: col)的函数,它返回指定行和列的垂直,水平和对角线的所有坐标。使用此坐标列表,我需要从每个坐标列出的每个可能值中删除我放置的值。该板表示为一个映射,我需要在功能上执行此操作,即不使用var。

这是我的解析功能:

str.zipWithIndex.map{
    case (digit, index) => ((index / 9, index % 9), List(digit.asDigit))
  }.toMap

以下是我对neighbors函数的了解:

def neighbors(row: Int, col: Int): List[(Int, Int)]

例如,如果解析器位于坐标(0,2)上,并且输入到地图中的数字为4,则必须从垂直,水平的所有坐标中删除4 ,从那一点开始的对角线。每个点的值都表示为可能值的列表。

我也没有得到neighbor函数的实现。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如果我正确地理解了你的问题,它是关于如何在保持功能的同时改变事物(在这种情况下从Map删除)?

如果是,有两种方法:

  1. 创建为每次迭代调用的尾递归函数,其中包含要处理的剩余元素列表以及" mutable"的当前状态。数据:

    @tailrec
    def process(
         input: List[(Char, Int)],
         board: Map[Any, Any],
         resultAccum: List[Result]): List[Result] = input match {
      case Nil => resultAccum.reverse
      case (char, pos) :: tail =>
        // do the processing
        val updatedBoard = board - ??? // create update version of the board
        val updateResults = ??? :: resultAccum
        process(tail, updatedBoard, updateResults)
    }
    
  2. 或者您可以使用foldLeft,这样做但看起来更短:

    input.foldLeft((initialBoard, List[Result]())) {
      case ((board, resultsAccum), (char, pos)) =>
        val updatedBoard = board - ??? // create update version of the board
        val updateResults = ??? :: resultsAccum
        (updatedBoard, updateResults)
    }._2.reverse
    

    foldLeft的初始状态包含董事会的初始状态和空的结果列表。

相关问题