我正在尝试将python代码转换为scala。我是Scala的新手,它是一种与python截然不同的语言。你知道吗
我尝试过将所有python函数转换为Scala,如下所示:
def legalMoves(board: List[Int]): List[List[Int]] = {
val moves = List[List[Int]]()
for ((piece, pos) <- board.zipWithIndex) {
val jumpmove = pos + (piece * 2)
val move = pos + (piece)
if (piece != 0) {
if (!((jumpmove < 0) || (jumpmove >= board.size))) {
if (board(jumpmove) == 0) {
val t = List(board)
t.updated(pos, 0)
t.updated(jumpmove, piece)
moves :+ t
}
}
if (!((move < 0) || (move >= board.size))) {
if (board(move) == 0) {
val t = List(board)
t.updated(pos, 0)
t.updated(move, piece)
moves :+ t
}
}
}
}
return moves
}
def evalAll(current: List[List[Int]], target: List[Int]): List[List[Int]] = {
val next = List[List[Int]]()
for (a <- current) {
val n = legalMoves(a)
for (q <- n) {
val t = List(a)
t :+ q
if (q == target) {
return t
}
next :+ t
}
}
return next
}
def solve(start: List[Int]): List[List[Int]] = {
var temp = List(start)
val end = start.reverse
while (temp.last != end) {
temp = evalAll(temp, end)
}
return temp
}
def main(args: Array[String]) {
println(solve(List(1, 1, 1, 0, -1, -1, -1)))
}
这是我在尝试运行它时得到的错误:
[error] at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:791)
[error] at org.mq.frogsandtoads.Main$.legalMoves(Main.scala:6)
[error] at org.mq.frogsandtoads.Main$.$anonfun$evalAll$1(Main.scala:34)
[error] at org.mq.frogsandtoads.Main$.$anonfun$evalAll$1$adapted(Main.scala:33)
[error] at scala.collection.immutable.List.foreach(List.scala:392)
[error] at org.mq.frogsandtoads.Main$.evalAll(Main.scala:33)
[error] at org.mq.frogsandtoads.Main$.solve(Main.scala:51)
[error] at org.mq.frogsandtoads.Main$.main(Main.scala:57)
[error] Nonzero exit code returned from runner: 1
[error] (Compile / run) Nonzero exit code returned from runner: 1
[error] Total time: 3 s, completed Aug 23, 2019, 8:18:35 PM
我不明白怎么了。我很想被放在正确的方向上。你知道吗
我通过这样编辑代码找到了解决方案(列表中的更改太多):
欢迎来到斯卡拉的奇妙世界!你知道吗
事情有时肯定会有点混乱,但只要有一点毅力,一切皆有可能。:-)
异常的原因是无效的列表索引值。(如果不明显,如果您有一个包含
n
元素的列表,那么如果您试图访问任何索引超出范围[0, n - 1]
的成员,就会出现该异常。)不幸的是,您的“解决方案”只是添加了另一层列表,修复了症状,但我认为它没有解决问题。不过,对于给定的问题,您的代码正确地列出了一系列具有一个解决方案的电路板。你知道吗
然而,对于任何给定的电路板,这个问题有两种解决方案,它们是彼此的镜像。还有一些其他的规则是解决方案的特征,比如对于一个有
F
青蛙和T
蟾蜍的游戏:F x T
。你知道吗F + T
。你知道吗(F x T) + F + T
。你知道吗我试着理解你的代码,但我放弃了;我无法理解它!:-)相反,我编写了一个更详细一点的解决方案,但它会产生更易于理解的输出(希望您也能理解它)。你知道吗
顺便说一句,Scala
List
并不是真的要以您尝试的方式使用的。每个List
基本上由两个元素组成:一个head
(它是列表中的第一个元素)和一个tail
(它是包含其余元素的List
)。值Nil
表示空列表。这建立了一个递归关系,允许我们遍历List
,根据需要对连续的head元素执行操作。因此,当您需要根据元素在列表中的位置来查找它时,它的性能就不太好了(这种查找的效率是O(n)
)。一个Array
在这方面要好得多(顺序效率O(1)
)。你知道吗另外,Scala中不鼓励使用while循环和
var
,因为有更好的方法可用。为了说明这一点,我重新编写了您的程序,以利用Scala的函数式编程功能: 你知道吗这将产生以下输出: 你知道吗
会有很多你可能不明白的,马上。我鼓励您访问Scala API documentation,查找一些您不确定的细节。你知道吗
相关问题 更多 >
编程相关推荐