Get which Quarter of the Year in Golang

The challenge

Given a month as an integer from 1 to 12, return to which quarter of the year it belongs as an integer number.

For example: month 2 (February), is part of the first quarter; month 6 (June), is part of the second quarter; and month 11 (November), is part of the fourth quarter.

The solution in Golang

Option 1:

package solution func QuarterOf(month int) int { return (month + 2) / 3 }
Code language: Go (go)

Option 2:

package solution import("math") func QuarterOf(month int) int { quarter := math.Ceil(float64(month)/3) return int(quarter) }
Code language: Go (go)

Option 3:

package solution func QuarterOf(month int) int { q := [12]int{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4} return q[month-1] }
Code language: Go (go)

Test cases to validate our solution

package our_test import ( "time" "math" "math/rand" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Test Example", func() { It("should test all values", func() { for i := 1; i < 13; i++ { Expect(QuarterOf(i)).To(Equal(solution(i))) } }) It("should test random values", func() { rand.Seed(time.Now().UnixNano()) for i := 1; i < 100; i++ { n := rand.Intn(12)+1 Expect(QuarterOf(n)).To(Equal(solution(n))) } }) }) func solution(month int) int { return int(math.Ceil(float64(month) / 3)) }
Code language: Go (go)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments