Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -309,3 +309,4 @@ problems from
* [Day 299](https://github.com/vaskoz/dailycodingproblem-go/issues/611)
* [Day 300](https://github.com/vaskoz/dailycodingproblem-go/issues/612)
* [Day 302](https://github.com/vaskoz/dailycodingproblem-go/issues/615)
* [Day 303](https://github.com/vaskoz/dailycodingproblem-go/issues/616)
35 changes: 35 additions & 0 deletions day303/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package day303

import "math"

// AngleClockHands returns the nearest angle between clock hands.
// Works at minute granularity.
func AngleClockHands(hh, mm int) int {
if hh < 0 || hh >= 24 || mm < 0 || mm >= 60 {
panic("invalid time")
}
if hh >= 12 {
hh -= 12
}
hourAngle := 360.0 * float64(hh) / 12.0
minuteAngle := 360.0 * float64(mm) / 60.0
diffAngle := math.Abs(hourAngle - minuteAngle)
if diffAngle > 180 {
diffAngle -= 360
}
return int(math.Round(math.Abs(diffAngle)))
}

// TimesOverlappingHands returns all the [hh:mm] pairs with overlapping
// clock hands by checking all possible 12*60 hour/minute possibilities.
func TimesOverlappingHands() [][]int {
var result [][]int
for h := 0; h < 12; h++ {
for m := 0; m < 60; m++ {
if angle := AngleClockHands(h, m); angle == 0 {
result = append(result, []int{h, m})
}
}
}
return result
}
59 changes: 59 additions & 0 deletions day303/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package day303

import (
"reflect"
"testing"
)

// nolint
var testcases = []struct {
hh, mm int
angle int
}{
{12, 00, 0},
{11, 00, 30},
}

func TestAngleClockHands(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if angle := AngleClockHands(tc.hh, tc.mm); angle != tc.angle {
t.Errorf("Expected %v, got %v", tc.angle, angle)
}
}
}

func TestAngleClockHandsBadTime(t *testing.T) {
t.Parallel()
defer func() {
if err := recover(); err == nil {
t.Errorf("Expected a panic with an invalid time")
}
}()
AngleClockHands(20, 60)
}

func BenchmarkAngleClockHands(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
AngleClockHands(tc.hh, tc.mm)
}
}
}

func TestTimesOverlappingHands(t *testing.T) {
t.Parallel()
result := TimesOverlappingHands()
expected := [][]int{
{0, 0}, {1, 5}, {2, 10}, {3, 15}, {4, 20}, {5, 25}, {6, 30}, {7, 35}, {8, 40}, {9, 45}, {10, 50}, {11, 55},
}
if !reflect.DeepEqual(result, expected) {
t.Errorf("Expected %v, got %v", result, expected)
}
}

func BenchmarkTimesOverlappingHands(b *testing.B) {
for i := 0; i < b.N; i++ {
TimesOverlappingHands()
}
}