Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
djpan0303 opened this issue Feb 19, 2022 · 0 comments
Open

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

djpan0303 opened this issue Feb 19, 2022 · 0 comments

Comments

@djpan0303
Copy link

第六题机器人坐标计算
如果命令字符串包含嵌套的命令,那么题中的代码就会有问题。
举个例子,输入的命令为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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant