Skip to content

Commit

Permalink
Merge pull request #847 from vaskoz/day419
Browse files Browse the repository at this point in the history
Day419
  • Loading branch information
vaskoz authored Jan 14, 2020
2 parents ca35c03 + 93b2c74 commit d8d2dea
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -415,4 +415,5 @@ problems from
* [Day 416](https://github.com/vaskoz/dailycodingproblem-go/issues/840)
* [Day 417](https://github.com/vaskoz/dailycodingproblem-go/issues/842)
* [Day 418](https://github.com/vaskoz/dailycodingproblem-go/issues/844)
* [Day 419](https://github.com/vaskoz/dailycodingproblem-go/issues/846)

46 changes: 46 additions & 0 deletions day419/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package day419

import "math"

// SmallestStepsToOne returns the smallest possible
// number of steps to reach run using two rules.
// First, n-1
// Second, a*b=N goto the larger of a and b.
// This is effectively BFS.
func SmallestStepsToOne(n int) int {
if n < 1 {
panic("n must be greater than 0")
}

seen := make(map[int]struct{})
q := []int{n}

var steps int

for len(q) != 0 {
nextQ := make([]int, 0, 2*len(q))

for _, v := range q {
if v == 1 {
nextQ = nil
break
} else if _, found := seen[v]; !found {
seen[v] = struct{}{}
nextQ = append(nextQ, v-1)
a := v
for b := int(math.Sqrt(float64(v))); b > 0; b-- {
if v%b == 0 {
a = v / b
break
}
}
nextQ = append(nextQ, a)
}
}

q = nextQ
steps++
}

return steps - 1
}
45 changes: 45 additions & 0 deletions day419/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package day419

import "testing"

// nolint
var testcases = []struct {
n, expected int
}{
{100, 5},
{1, 0}, // 1
{2, 1}, // 2 -> 1
{3, 2}, // 3 -> 2 -> 1
{4, 2}, // 4 -> 2 -> 1
{5, 3}, // 5 -> 4 -> 2 -> 1
{6, 3}, // 6 -> 3 -> 2 -> 1
}

func TestSmallestStepsToOne(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if result := SmallestStepsToOne(tc.n); result != tc.expected {
t.Errorf("Expected %v, got %v", tc.expected, result)
}
}
}

func TestSmallestStepsToOneBadInput(t *testing.T) {
t.Parallel()

defer func() {
if err := recover(); err == nil {
t.Errorf("Expected an error, but got nil")
}
}()
SmallestStepsToOne(0)
}

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

0 comments on commit d8d2dea

Please sign in to comment.