我正在为 Advent of Code 进行编码挑战.我是 Scala 的新手,无法弄清楚我的解决方案有什么问题。
您被空投到某个城市的复活节兔子总部附近。不幸的是,“接近”是你能得到的最接近的—— Sprite 截获的复活节兔子招募文件的说明从这里开始,没有人有时间进一步研究。
文档指示您应该从给定的坐标(您刚着陆的地方)开始并面向北方。然后,按照提供的顺序:左转 (L) 或右转 (R) 90 度,然后向前走指定数量的街区,在新的路口结束。
不过,没有时间按照这些荒谬的指示步行,所以您需要花点时间算出目的地。鉴于你只能走城市的街道网格,到达目的地的最短路径是多远?
例如:
在 R2 之后,L3 向东 2 个街区,向北 3 个街区,即 5 个街区。
R2、R2、R2 离开您的起始位置以南 2 个街区,即 2 个街区。
R5、L5、R5、R3 离您 12 个街区远。 复活节兔子总部距离酒店有多少个街区?
如果您从北开始向左看然后步行,您将向西走;否则你要去东方。按照其余主要方向的逻辑,我提出了以下代码(我已经评论了第一 block 逻辑,希望其余部分遵循):
object Facing extends Enumeration {
val North, South, East, West = Value
}
// We're at (0, 0) facing north to begin with.
// directions is a list of instructions (i.e., ((LN)|(RM))+)
val (x, y, _) = directions.foldRight((0,0, Facing.North)){(d, prev) =>
println(s"Instruction is $d")
val dir = d(0)
val dist = d.substring(1).toInt
val (x, y, looking) = prev
println(s"x = ${x}, y = ${y}")
println(s"Prior is = $prev")
looking match {
case Facing.North => {
if(dir == 'R') {
// If we're facing north and told to go R<dist>, we face east
// then update the x to dist away. etc.
val res = (x + dist, y, Facing.East)
println(res)
res
} else {
val res = (x - dist, y, Facing.West)
println(res)
res
}
}
case Facing.South => {
if(dir == 'L') {
val res = (x + dist, y, Facing.East)
println(res)
res
} else {
val res = (x - dist, y, Facing.West)
println(res)
res
}
}
case Facing.East => {
if(dir == 'L') {
val res = (x, y + dist, Facing.North)
println(res)
res
} else {
val res = (x, y - dist, Facing.South)
println(res)
res
}
}
case Facing.West => {
if(dir == 'L') {
val res = (x, y - dist, Facing.South)
println(res)
res
} else {
val res = (x, y + dist, Facing.North)
println(res)
res
}
}
}
}
println(s"Distance is ${x.abs + y.abs}")
我的解决方案是错误的(抱歉,我没有比这更多的信息),所以我一定是在某个地方犯了一些逻辑错误。我想要一些有关如何解决此问题的提示!
最佳答案
您的错误是您折叠正确,因此您以错误的顺序应用说明。您应该使用 foldLeft
(或 reverse
directions
列表)。
关于algorithm - 代码的出现 2016 : Day 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40913634/