Skip to content

Commit

Permalink
Merge 447929d into ee3216b
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Feb 23, 2019
2 parents ee3216b + 447929d commit cc50e6c
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,4 @@ problems from
* [Day 178](https://github.com/vaskoz/dailycodingproblem-go/issues/367)
* [Day 179](https://github.com/vaskoz/dailycodingproblem-go/issues/371)
* [Day 180](https://github.com/vaskoz/dailycodingproblem-go/issues/373)
* [Day 184](https://github.com/vaskoz/dailycodingproblem-go/issues/378)
21 changes: 21 additions & 0 deletions day184/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package day184

// GcdSlice returns the greatest common denominator
// of all the values in the slice.
func GcdSlice(nums []int) int {
if len(nums) == 0 {
return 0
}
result := nums[0]
for i := 1; i < len(nums); i++ {
result = gcd(nums[i], result)
}
return result
}

func gcd(a, b int) int {
if a == 0 {
return b
}
return gcd(b%a, a)
}
30 changes: 30 additions & 0 deletions day184/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package day184

import "testing"

var testcases = []struct {
nums []int
expected int
}{
{[]int{42, 56, 14}, 14},
{[]int{14}, 14},
{nil, 0},
{[]int{}, 0},
}

func TestGcdSlice(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := GcdSlice(tc.nums); result != tc.expected {
t.Errorf("Expected %v, got %v for input %v", tc.expected, result, tc.nums)
}
}
}

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

0 comments on commit cc50e6c

Please sign in to comment.