Skip to content

Commit

Permalink
day 245: refactor to account for impassable puzzles
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Apr 24, 2019
1 parent fa48c54 commit 2390fee
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 13 deletions.
26 changes: 21 additions & 5 deletions day245/problem.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,38 @@
package day245

import "errors"

var errImpassable = errors.New("impossible to reach the end")

// ErrImpassable returns the error associated with an impassable
// route.
func ErrImpassable() error {
return errImpassable
}

// MinimumJumps returns the minimum steps to reach the end.
// Each element contains the max steps that can be taken
// in a single jump.
func MinimumJumps(maxSteps []int) int {
// Returns an error if impassable.
func MinimumJumps(maxSteps []int) (int, error) {
if len(maxSteps) < 2 {
return 0
return 0, nil
}
minJumps := int(^uint(0) >> 1)
if maxSteps[0] == 0 { // can't jump from this cell
return minJumps
return 0, errImpassable
}
impassable := true
for jump := maxSteps[0]; jump > 0; jump-- {
if jump < len(maxSteps) {
if result := MinimumJumps(maxSteps[jump:]); result < minJumps {
if result, impass := MinimumJumps(maxSteps[jump:]); impass == nil && result < minJumps {
impassable = false
minJumps = result
}
}
}
return minJumps + 1
if impassable {
return 0, errImpassable
}
return minJumps + 1, nil
}
20 changes: 12 additions & 8 deletions day245/problem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,34 @@ package day245

import "testing"

// nolint
var testcases = []struct {
maxSteps []int
expectedJumps int
impassable error
}{
{[]int{6, 2, 4, 0, 5, 1, 1, 4, 2, 9}, 2},
{[]int{9}, 0},
{[]int{}, 0},
{nil, 0},
{[]int{1, 1, 1, 1, 1, 1, 1}, 6},
{[]int{6, 2, 4, 0, 5, 1, 1, 4, 2, 9}, 2, nil},
{[]int{9}, 0, nil},
{[]int{}, 0, nil},
{nil, 0, nil},
{[]int{1, 1, 1, 1, 1, 1, 1}, 6, nil},
{[]int{1, 1, 0, 1, 1}, 0, ErrImpassable()},
{[]int{1, 2, 0, 1, 1}, 3, nil},
}

func TestMinimumJumps(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if jumps := MinimumJumps(tc.maxSteps); jumps != tc.expectedJumps {
t.Errorf("Expected %v, got %v", tc.expectedJumps, jumps)
if jumps, impassable := MinimumJumps(tc.maxSteps); impassable != tc.impassable || jumps != tc.expectedJumps {
t.Errorf("Expected (%v,%v), got (%v,%v)", tc.expectedJumps, tc.impassable, jumps, impassable)
}
}
}

func BenchmarkMinimumJumps(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
MinimumJumps(tc.maxSteps)
MinimumJumps(tc.maxSteps) //nolint
}
}
}

0 comments on commit 2390fee

Please sign in to comment.