Skip to content

Commit

Permalink
Merge a103de7 into 7479a3e
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 1, 2018
2 parents 7479a3e + a103de7 commit fc90500
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,4 @@ problems from
* [Day 97](https://github.com/vaskoz/dailycodingproblem-go/issues/203)
* [Day 98](https://github.com/vaskoz/dailycodingproblem-go/issues/204)
* [Day 99](https://github.com/vaskoz/dailycodingproblem-go/issues/205)
* [Day 100](https://github.com/vaskoz/dailycodingproblem-go/issues/209)
39 changes: 39 additions & 0 deletions day100/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package day100

// Point is a X and Y coordinate.
type Point struct {
X, Y int
}

// MinimumStepsPath returns the minimum number of steps required
// to walk the path. The path must be walked in order.
// 8 directions possible: 4 cardinal and 4 intercardinal.
func MinimumStepsPath(path []Point) int {
if len(path) < 2 {
return 0
}
steps := 0
current := path[0]
for i := 1; i < len(path); i++ {
next := path[i]
dx, dy := delta(current, next)
if dx < dy {
steps += dy
} else {
steps += dx
}
current = next
}
return steps
}

func delta(from, to Point) (int, int) {
return abs(to.X - from.X), abs(to.Y - from.Y)
}

func abs(x int) int {
if x < 0 {
return -x
}
return x
}
32 changes: 32 additions & 0 deletions day100/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package day100

import "testing"

var testcases = []struct {
path []Point
minimumSteps int
}{
{[]Point{{0, 0}, {1, 1}, {1, 2}}, 2},
{[]Point{}, 0},
{nil, 0},
{[]Point{{100, 100}}, 0},
{[]Point{{0, 0}, {-10, -10}, {20, 20}}, 40},
{[]Point{{0, 0}, {-10, -10}, {20, 40}}, 60},
}

func TestMinimumStepsPath(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if steps := MinimumStepsPath(tc.path); steps != tc.minimumSteps {
t.Errorf("Expected %v got %v", tc.minimumSteps, steps)
}
}
}

func BenchmarkMinimumStepsPath(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
MinimumStepsPath(tc.path)
}
}
}

0 comments on commit fc90500

Please sign in to comment.