funcexecuteInstructions(n int, startPos []int, s string) []int { answer := make([]int, len(s)) for i := 0; i < len(s); i++ { task := s[i:] time := 0 nowPos := startPos for _, action := range task { next, out := move(action, nowPos, n) if out { break } time++ nowPos = next } answer[i] = time } return answer }
// U: 85 L: 76 D: 68 R: 82 funcmove(action int32, location []int, n int)(next []int, out bool) { if action == 76 { next = []int{location[0], location[1] - 1} out = location[1]-1 < 0 return } if action == 82 { next = []int{location[0], location[1] + 1} out = location[1]+1 > n-1 return } if action == 68 { next = []int{location[0] + 1, location[1]} out = location[0]+1 > n-1 return } if action == 85 { next = []int{location[0] - 1, location[1]} out = location[0]-1 < 0 return } returnnil, true }
funcgetDistances(arr []int) []int64 { dic := make(map[int][]int) for i, v := range arr { if dic[v] != nil { dic[v] = append(dic[v], i) } else { dic[v] = []int{i} } } answer := make([]int64, len(arr)) for i, v := range arr { sum := 0 for _, same := range dic[v] {
if same > i { sum += same - i } else { sum += i - same } } answer[i] = int64(sum) } return answer }
optimize
funcgetDistances(arr []int) []int64 { dic := make(map[int][]int) for i, v := range arr { if dic[v] != nil { dic[v] = append(dic[v], i) } else { dic[v] = []int{i} } } answer := make([]int64, len(arr)) for _, indexArr := range dic { for i := range indexArr { answer[indexArr[i]] = countSub(indexArr, i) } } return answer }
funccountSub(arr []int, i int)int64 { var sub int64 = 0 for _i := range arr { if arr[_i] > arr[i] { sub += int64(arr[_i] - arr[i]) } else { sub += int64(arr[i] - arr[_i]) } } return sub }