Skip to content

Commit

Permalink
Merge 18d5659 into 2ba41b4
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Apr 21, 2019
2 parents 2ba41b4 + 18d5659 commit 606d5be
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ problems from
* [Day 226](https://github.com/vaskoz/dailycodingproblem-go/issues/467)
* [Day 227](https://github.com/vaskoz/dailycodingproblem-go/issues/469)
* [Day 228](https://github.com/vaskoz/dailycodingproblem-go/issues/470)
* [Day 229](https://github.com/vaskoz/dailycodingproblem-go/issues/472)
* [Day 230](https://github.com/vaskoz/dailycodingproblem-go/issues/473)
* [Day 231](https://github.com/vaskoz/dailycodingproblem-go/issues/475)
* [Day 232](https://github.com/vaskoz/dailycodingproblem-go/issues/477)
Expand Down
42 changes: 42 additions & 0 deletions day229/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package day229

// Jump represents the movement that happens either up or down.
// Ladders give you a boost up, while a Snake lowers your position.
type Jump struct {
From, To int
}

// SnakesAndLaddersFewestTurns by playing all games.
func SnakesAndLaddersFewestTurns(ladders, snakes []Jump, maxDepth int) int {
jumps := make(map[int]int, len(ladders)+len(snakes))
for _, j := range ladders {
jumps[j.From] = j.To
}
for _, j := range snakes {
jumps[j.From] = j.To
}
return snakesAndLaddersFewestTurns(jumps, 0, 0, int(^uint(0)>>1), maxDepth)
}

func snakesAndLaddersFewestTurns(jumps map[int]int, pos, depth, bestSoFar, maxDepth int) int {
if pos == 100 {
return depth
} else if depth > maxDepth || depth > bestSoFar {
return bestSoFar
}
for roll := 6; roll >= 0; roll-- {
next := pos + roll
if jumpPos, found := jumps[next]; found && jumpPos < pos { // avoid all snakes
continue
} else if found && jumpPos > pos {
next = jumpPos
}
if next > 100 {
break
}
if turns := snakesAndLaddersFewestTurns(jumps, next, depth+1, bestSoFar, maxDepth); turns < bestSoFar {
bestSoFar = turns
}
}
return bestSoFar
}
15 changes: 15 additions & 0 deletions day229/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package day229

import "testing"

func TestSnakesAndLaddersFewestTurns(t *testing.T) {
t.Parallel()
fewestTurns := SnakesAndLaddersFewestTurns(
[]Jump{{1, 38}, {4, 14}, {9, 31}, {21, 42}, {28, 84}, {36, 44}, {51, 67}, {71, 91}, {80, 100}},
[]Jump{{16, 6}, {48, 26}, {49, 11}, {56, 53}, {62, 19}, {64, 60}, {87, 24}, {93, 73}, {95, 75}, {98, 78}},
6,
)
if fewestTurns != 7 {
t.Errorf("on the original game board best is 7, got %v", fewestTurns)
}
}

0 comments on commit 606d5be

Please sign in to comment.