The problem
What’s your favorite day of the week? Test if it’s essentially the most frequent day of the week within the yr.
You’re given a yr as integer (e. g. 2001). You must return essentially the most frequent day(s) of the week in that yr. The consequence needs to be a listing of days sorted by the order of days in week (e. g. ['Monday', 'Tuesday']
, ['Saturday', 'Sunday']
, ['Monday', 'Sunday']
). Week begins with Monday.
Enter: Yr as an int.
Output:Â The checklist of most frequent days sorted by the order of days in week (from Monday to Sunday).
Preconditions:
- Week begins on Monday.
- Yr is between 1583 and 4000.
- Calendar is Gregorian.
Instance:
MostFrequentDays(2427) == []string{"Friday"}
MostFrequentDays(2185) == []string{"Saturday"}
MostFrequentDays(2860) == []string{"Thursday", "Friday"}
The answer in Golang
Choice 1:
bundle mostfrequentdays
import (
"time"
)
func MostFrequentDays(yr int) []string {
beg := time.Date(yr, time.January, 1, 0, 0, 0, 0, time.UTC).Weekday()
finish := time.Date(yr, time.December, 31, 0, 0, 0, 0, time.UTC).Weekday()
if beg == finish {
return []string{beg.String()}
}
if beg == time.Sunday {
beg, finish = finish, beg
}
return []string{beg.String(), finish.String()}
}
Choice 2:
bundle mostfrequentdays
import "time"
func MostFrequentDays(yr int) (consequence []string) {
jan_1 := time.Date(yr, time.January, 1, 0, 0, 0, 0, time.UTC)
consequence = append(consequence, jan_1.Weekday().String())
if yr % 4 == 0 {
jan_2 := jan_1.Add(24*time.Hour)
if consequence[0] == "Sunday" {
consequence = append([]string{jan_2.Weekday().String()}, consequence...)
} else {
consequence = append(consequence, jan_2.Weekday().String())
}
}
return consequence
}
Choice 3:
bundle mostfrequentdays
import ("time";"kind")
func MostFrequentDays(yr int) (r []string) {
first := time.Date(yr, 1, 1, 0, 0, 0, 0, time.UTC)
final := time.Date(yr, 12, 1, 0, 0, 0, 0, time.UTC).AddDate(0, 1, -1)
for {
r = append(r, first.Weekday().String())
if first.Weekday() == final.Weekday() { break }
first = first.Add(24 * time.Hour)
}
m := map[string]int{"Monday": 1, "Tuesday": 2, "Wednesday": 3, "Thursday": 4, "Friday": 5, "Saturday": 6, "Sunday": 7}
kind.Slice(r, func(i, j int) bool { return m[r[i]] < m[r[j]] })
return
}
Take a look at circumstances to validate our resolution
bundle mostfrequentdays_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func check(enter int, anticipated ...string) {
Anticipate(MostFrequentDays(enter)).To(Equal(anticipated))
}
var _ = Describe("Pattern Checks", func() {
It("Pattern Checks", func() {
check(2427, "Friday")
check(2185, "Saturday")
check(1167, "Sunday")
check(1770, "Monday")
check(1785, "Saturday")
check(1984, "Monday", "Sunday")
check(3076, "Saturday", "Sunday")
})
})