Skip to content

Instantly share code, notes, and snippets.

@kavu
Created March 5, 2014 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kavu/9363279 to your computer and use it in GitHub Desktop.
Save kavu/9363279 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strings"
)
type Position struct {
X, Y int
}
type Line []string
var (
preprocessDone bool = false
selectedDirtIdx int = -1
dirtsCoordinates []Position
)
func printNextMove(position *Position) {
coordinate := dirtsCoordinates[selectedDirtIdx]
if position.X == coordinate.X && position.Y == coordinate.Y {
dirtsCoordinates = append(dirtsCoordinates[:selectedDirtIdx], dirtsCoordinates[selectedDirtIdx+1:]...)
selectedDirtIdx = -1
fmt.Println("CLEAN")
} else if position.X > coordinate.X {
fmt.Println("UP")
} else if (coordinate.Y > coordinate.Y) || (position.Y > coordinate.Y && position.X == coordinate.X) {
fmt.Println("LEFT")
} else if position.X < coordinate.X {
fmt.Println("DOWN")
} else {
fmt.Println("RIGHT")
}
}
func findAllDirts(field *[]Line) {
for i, line := range *field {
for j, place := range line {
if place == "d" {
dirtsCoordinates = append(dirtsCoordinates, Position{i, j})
}
}
}
preprocessDone = true
}
func findClosestDirt(position *Position) {
var (
min_idx, dist, dist_x, dist_y int
min_dist int = 9
)
for i := 0; i < len(dirtsCoordinates); i++ {
coordinate := dirtsCoordinates[i]
if position.X > coordinate.X {
dist_x = position.X - coordinate.X
} else {
dist_x = coordinate.X - position.X
}
if position.Y > coordinate.Y {
dist_y = position.Y - coordinate.Y
} else {
dist_y = coordinate.Y - position.Y
}
dist = dist_x + dist_y
if dist < min_dist {
min_idx = i
min_dist = dist
}
}
selectedDirtIdx = min_idx
}
func nextMove(position *Position, field *[]Line) {
if preprocessDone == false {
findAllDirts(field)
}
if selectedDirtIdx == -1 {
findClosestDirt(position)
}
printNextMove(position)
}
func main() {
var (
line string
position *Position = &Position{}
field []Line = make([]Line, 5)
)
fmt.Scanf("%d", &position.X)
fmt.Scanf("%d", &position.Y)
for i := 0; i < 5; i++ {
fmt.Scanf("%s", &line)
field[i] = strings.Split(line, "")
}
nextMove(position, &field)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment