Skip to content

Commit

Permalink
day 283: faster version of regular numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Jun 2, 2019
1 parent ef6324d commit 9cd982c
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
40 changes: 40 additions & 0 deletions day283/problem.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,45 @@
package day283

// RegularNumbersFaster returns n regular numbers
// using brute force.
func RegularNumbersFaster(n int) []int {
if n < 0 {
panic("negative values are not possible")
} else if n == 0 {
return []int{}
}
result := make([]int, n)
result[0] = 1
var i2, i3, i5 int
next2, next3, next5 := 2, 3, 5
for i := 1; i < n; i++ {
result[i] = min(next2, next3, next5)
if result[i] == next2 {
i2++
next2 = result[i2] * 2
}
if result[i] == next3 {
i3++
next3 = result[i3] * 3
}
if result[i] == next5 {
i5++
next5 = result[i5] * 5
}
}
return result
}

func min(vals ...int) int {
smallest := vals[0]
for _, v := range vals {
if v < smallest {
smallest = v
}
}
return smallest
}

// RegularNumbersBrute returns n regular numbers
// using brute force.
func RegularNumbersBrute(n int) []int {
Expand Down
26 changes: 26 additions & 0 deletions day283/problem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,32 @@ var testcases = []struct {
{26, []int{1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60}},
}

func TestRegularNumbersFaster(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := RegularNumbersFaster(tc.n); !reflect.DeepEqual(result, tc.expected) {
t.Errorf("Expected %v, got %v", tc.expected, result)
}
}
}

func TestRegularNumbersFasterBadInput(t *testing.T) {
defer func() {
if err := recover(); err == nil {
t.Errorf("Expected a panic for a negative input")
}
}()
RegularNumbersFaster(-2)
}

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

func TestRegularNumbersBrute(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
Expand Down

0 comments on commit 9cd982c

Please sign in to comment.