The problem
What’s your favorite day of the week? Examine if it’s probably the most frequent day of the week within the 12 months.
You might be given a 12 months as integer (e. g. 2001). It’s best to return probably the most frequent day(s) of the week in that 12 months. The outcome must be an inventory 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 listing 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(12 months int) []string {
beg := time.Date(12 months, time.January, 1, 0, 0, 0, 0, time.UTC).Weekday()
finish := time.Date(12 months, 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(12 months int) (outcome []string) {
jan_1 := time.Date(12 months, time.January, 1, 0, 0, 0, 0, time.UTC)
outcome = append(outcome, jan_1.Weekday().String())
if 12 months % 4 == 0 {
jan_2 := jan_1.Add(24*time.Hour)
if outcome[0] == "Sunday" {
outcome = append([]string{jan_2.Weekday().String()}, outcome...)
} else {
outcome = append(outcome, jan_2.Weekday().String())
}
}
return outcome
}
Choice 3:
bundle mostfrequentdays
import ("time";"type")
func MostFrequentDays(12 months int) (r []string) {
first := time.Date(12 months, 1, 1, 0, 0, 0, 0, time.UTC)
final := time.Date(12 months, 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}
type.Slice(r, func(i, j int) bool { return m[r[i]] < m[r[j]] })
return
}
Check instances to validate our answer
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 Exams", func() {
It("Pattern Exams", func() {
check(2427, "Friday")
check(2185, "Saturday")
check(1167, "Sunday")
check(1770, "Monday")
check(1785, "Saturday")
check(1984, "Monday", "Sunday")
check(3076, "Saturday", "Sunday")
})
})