Skip to content

Instantly share code, notes, and snippets.

@samacs
Last active May 20, 2019 23:54
Show Gist options
  • Save samacs/ef33724cb5c21b2f49e1a808bf7cf4c2 to your computer and use it in GitHub Desktop.
Save samacs/ef33724cb5c21b2f49e1a808bf7cf4c2 to your computer and use it in GitHub Desktop.
Shortest path in grid
package main
import (
"fmt"
"math"
)
// Language: Go
//
// Running:
//
// ```go
// $ go run main.go
// [(5, 5), (6, 6)] 1 step left up
// [(6, 6), (5, 6)] 1 step right down
// 2
// ```
type Point struct {
X float64
Y float64
}
func main() {
points := []Point{
{5, 5},
{6, 6},
{5, 6},
}
steps := countSteps(points)
fmt.Printf("%d\n", steps)
}
func (p Point) String() string {
return fmt.Sprintf("(%0.0f, %0.0f)", p.X, p.Y)
}
func countSteps(points []Point) (steps int) {
length := len(points)
for i := 0; i < length-1; i++ {
point1 := points[i]
point2 := points[i+1]
currentSteps := findShortestPath(point1, point2)
steps += currentSteps
stepsWord := "step"
if currentSteps > 1 {
stepsWord = "steps"
}
fmt.Printf("[%s, %s] %d %s %s\n", point1, point2, currentSteps, stepsWord, direction(point1, point2))
}
return
}
func direction(point1 Point, point2 Point) (direction string) {
var (
horizontal string
vertical string
)
if point1.Y < point2.Y {
vertical = "up"
} else {
vertical = "down"
}
if point1.X < point2.X {
horizontal = "left"
} else {
horizontal = "right"
}
if len(horizontal) > 0 {
direction += horizontal
}
direction = fmt.Sprintf("%s %s", horizontal, vertical)
return
}
func findShortestPath(point1 Point, point2 Point) int {
xDistance := math.Abs(point1.X - point2.X)
yDistance := math.Abs(point1.Y - point2.Y)
return int(math.Max(xDistance, yDistance))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment