Skip to content

Commit

Permalink
Update q006.md
Browse files Browse the repository at this point in the history
使用更简单有效的方式解决问题
  • Loading branch information
tsunhua authored Dec 24, 2020
1 parent d6e5767 commit 6a12973
Showing 1 changed file with 52 additions and 79 deletions.
131 changes: 52 additions & 79 deletions question/q006.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,95 +13,68 @@
**源码参考**

```
func run(s string) (x, y int) {
cmdList := resolveCmd(s)
package main
face := "Y"
for _,c := range cmdList {
if c == "L" {
if face == "Y" {
face = "-X"
}else if face == "-Y"{
face = "X"
}else if face == "X" {
face = "Y"
}else {
face = "-Y"
}
}else if c == "R" {
if face == "Y" {
face = "X"
}else if face == "-Y"{
face = "-X"
}else if face == "X" {
face = "-Y"
}else {
face = "Y"
import (
"unicode"
)
const (
Left = iota
Top
Right
Bottom
)
func main() {
println(move("R2(LF)", 0, 0, Top))
}
func move(cmd string, x0 int, y0 int, z0 int) (x, y, z int) {
x, y, z = x0, y0, z0
repeat := 0
repeatCmd := ""
for _, s := range cmd {
switch {
case unicode.IsNumber(s):
repeat = repeat*10 + (int(s) - '0')
case s == ')':
for i := 0; i < repeat; i++ {
x, y, z = move(repeatCmd, x, y, z)
}
}else if c == "F" {
if face == "Y" {
y += 1
}else if face == "-Y" {
y -= 1
}else if face == "X" {
x+=1
}else {
x-=1
repeat = 0
repeatCmd = ""
case repeat > 0 && s != '(' && s != ')':
repeatCmd = repeatCmd + string(s)
case s == 'L':
z = (z + 1) % 4
case s == 'R':
z = (z - 1 + 4) % 4
case s == 'F':
switch {
case z == Left || z == Right:
x = x - z + 1
case z == Top || z == Bottom:
y = y - z + 2
}
}else if c == "B" {
if face == "Y" {
y-=1
}else if face == "-Y" {
y+=1
}else if face == "X" {
x+=1
}else {
x-=1
case s == 'B':
switch {
case z == Left || z == Right:
x = x + z - 1
case z == Top || z == Bottom:
y = y + z - 2
}
}
}
return
}
func resolveCmd(s string) ([]string){
cmdList := make([]string,0)
repeatCount := 0
isStart := false
tempCmd := ""
for _,v := range s {
ns := string(v)
//如果是字符串,则标识下一步是重复步骤
if ns >= "0" && ns <= "9" {
t,_ := strconv.Atoi(ns);
repeatCount = t
}else if ns == "(" {
isStart = true
}else if ns == ")" {
c := strings.Repeat(tempCmd,repeatCount)
tempList := make([]string,strings.Count(c,""))
for i,v1 := range c {
tempList[i] = string(v1)
}
//当解析结束时,重复命令并保存到列表中
cmdList = append(cmdList,tempList...)
isStart = false
repeatCount = 0
tempCmd = ""
}else if isStart{
tempCmd += ns
}else{
cmdList = append(cmdList,ns)
}
}
return cmdList
}
```

**源码解析**

这里用了最笨的方法,枚举方向和行动,逐字解析命令。示例中只实现了一次重复指令。更复杂的是多次重复指令。例如`R2(B2(LF)BF2(BF))FBF``R2(B2(LF2(RF)))F`
这里使用三个值表示机器人当前的状况,分别是:x表示x坐标,y表示y坐标,z表示当前方向。
L、R 命令会改变值z,F、B命令会改变值x、y。
值x、y的改变还受当前的z值影响。

如果是重复指令,那么将重复次数和重复的指令存起来递归调用即可。

0 comments on commit 6a12973

Please sign in to comment.