scala Bloxroz分配解决方案错误

时间:2017-07-15 09:06:29

标签: scala

我正在解决第7周的课程学习课程。我已经创建了解决方案的核心功能,但是测试用例失败了。

这是我的from()函数:

def from(initial: Stream[(Block, List[Move])],
           explored: Set[Block]): Stream[(Block, List[Move])] = initial match {

    case Stream() => Stream.Empty
    case head #:: rest => {
        val unfilteredSequences = neighborsWithHistory(head._1, head._2)
       val nextSequences = newNeighborsOnly(unfilteredSequences, explored)
       Stream.concat(rest, from(nextSequences, explored ++ nextSequences.map( entry => entry._1)))
    }
  }


def neighborsWithHistory(b: Block, history: List[Move]): Stream[(Block, List[Move])] = {

    def neighborHistoryHelper(xs: List[(Block, Move)], hist: List[Move], acc: List[(Block, List[Move])]): List[(Block, List[Move])] = xs match{
      case Nil => acc
      case tuple :: rest => neighborHistoryHelper(rest, tuple._2 :: hist, acc :+ (tuple._1, tuple._2 :: hist))
    }

    neighborHistoryHelper(b.legalNeighbors, history, Nil).toStream
  }



def newNeighborsOnly(neighbors: Stream[(Block, List[Move])],
                       explored: Set[Block]): Stream[(Block, List[Move])] = {

    def newNeighborHelper(n: Stream[(Block, List[Move])],
                          expl: Set[Block] , acc: Stream[(Block, List[Move])] ) : Stream[(Block, List[Move])] = n match{
      case Stream.Empty => acc
      case head #:: rest => {
        if(expl contains head._1)
          newNeighborHelper(rest, expl , acc )
        else
          newNeighborHelper(rest, expl + head._1, acc :+ head)
      }
    }

    newNeighborHelper(neighbors, explored, Stream.empty)
  }

想法是处理头部并将可能的序列附加到流的其余部分。

以下是失败的测试用例:

    test("optimal solution for level 1") {
    new Level1 {
      assert(solve(solution) == Block(goal, goal))
    }
  }

以下是当前的结果:

Exception in thread "main" java.lang.StackOverflowError
    at scala.collection.immutable.Stream$Cons.tail(Stream.scala:1233)

我怀疑这种方法是原因,不确定原因。

def isLegal: Boolean = b1.row > -1 && b1.col > -1 && b2.row > -1 && b2.col > -1 && b1.row <= b2.row && b1.col <= b2.col

请让我知道我的解决方案有什么问题。如果需要,我可以提供更多信息。

已更新添加地形功能,我怀疑即使这可能有问题。

def terrainFunction(levelVector: Vector[Vector[Char]]): Pos => Boolean = {

    Pos => {
      if(Pos.row >= levelVector.size || Pos.col >= levelVector(0).size || Pos.row <0 || Pos.col <0 )
          false
      else
        levelVector(Pos.row)(Pos.col) != '-'
    }
  }

代码更正

def terrainFunction(levelVector: Vector[Vector[Char]]): Pos => Boolean = {

    Pos => {
      if(Pos.row <0 || Pos.col <0  || Pos.row >= levelVector.size || Pos.col >= levelVector(Pos.row).size )
          false
      else
        levelVector(Pos.row)(Pos.col) != '-'
    }
  }

def isLegal: Boolean = terrain(b1) && terrain(b2)

通过这些更改,我得到了错误的答案,它没有给出堆栈溢出错误。

结果如下:

- optimal solution for level 1 *** FAILED ***
[info]   Block(Pos(1,1),Pos(1,1)) did not equal Block(Pos(4,7),Pos(4,7)) (BloxorzSuite.scala:70)

我某处仍有问题。这里很难理解这个问题。

0 个答案:

没有答案