lifei6671 / interview-go

golang面试题集合

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

第六题机器人坐标计算有问题

djpan0303 opened this issue · comments

第六题机器人坐标计算
如果命令字符串包含嵌套的命令,那么题中的代码就会有问题。
举个例子,输入的命令为2(F3(B)),正确的答案是(0,-4)。然而给出的代码输出是(0,0)
正确的代码可以参考如下:

const (
	NORTH = iota
	EAST
	SOUTH
	WEST
)

type Offset struct {
	x int
	y int
}

var dirlist []Offset
var dirname []string

func init() {
	dirname = []string{"NORTH", "EAST", "SOUTH", "WEST"}
	dirlist = []Offset{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
}

func getOffset(offset Offset, sign int, x int, y int) (int, int) {
	return x + offset.x*sign, y + offset.y*sign
}

func rmove(dir int, x int, y int, start int, s string) (int, int, int, int) {

	times := 0

	i := start
	//fmt.Printf("start:%d\n", start)
	for ; i < len(s); i++ {
		ch := s[i]
		//fmt.Printf("ch:%d,", ch)
		if ch >= '0' && ch <= '9' {
			times = times*10 + int(ch-'0')
		} else if ch == '(' {
			next := 0
			for j := 0; j < times; j++ {
				x, y, dir, next = rmove(dir, x, y, i+1, s)
			}
			i = next
		} else if ch == ')' {
			break
		} else if ch == 'R' {
			dir = (dir + 1) % 4
		} else if ch == 'L' {
			dir = (dir + 3) % 4

		} else if ch == 'F' {
			x, y = getOffset(dirlist[dir], 1, x, y)

		} else if ch == 'B' {
			x, y = getOffset(dirlist[dir], -1, x, y)
		}
	}
	//fmt.Printf("s:%s,x:%d,y:%d,dir:%d,i:%d\n", s, x, y, dir, i)
	return x, y, dir, i
}

// @返回参数1: 作标
// @返回参数2:方向
func move(s string) ([]int, int) {

	dir := NORTH
	x, y, dir, _ := rmove(dir, 0, 0, 0, s)
	//fmt.Printf("dir:%s\n", dirname[dir])
	return []int{x, y}, dir
}