diff --git a/README.md b/README.md index 19ae309..216311c 100644 --- a/README.md +++ b/README.md @@ -371,4 +371,5 @@ problems from * [Day 373](https://github.com/vaskoz/dailycodingproblem-go/issues/752) * [Day 374](https://github.com/vaskoz/dailycodingproblem-go/issues/754) * [Day 375](https://github.com/vaskoz/dailycodingproblem-go/issues/756) +* [Day 376](https://github.com/vaskoz/dailycodingproblem-go/issues/758) diff --git a/day376/problem.go b/day376/problem.go new file mode 100644 index 0000000..f5bdb5c --- /dev/null +++ b/day376/problem.go @@ -0,0 +1,30 @@ +package day376 + +// Pos is a position. +type Pos struct { + Row, Col int +} + +// ClosestCoinToMe returns the closest coin to my position +// using the Manhattan distance. +func ClosestCoinToMe(coins []Pos, me Pos) Pos { + closest := Pos{} + closestDistance := len(coins) * 2 + + for _, coin := range coins { + if dist := abs(me.Row-coin.Row) + abs(me.Col-coin.Col); dist < closestDistance { + closestDistance = dist + closest = coin + } + } + + return closest +} + +func abs(a int) int { + if a < 0 { + return -a + } + + return a +} diff --git a/day376/problem_test.go b/day376/problem_test.go new file mode 100644 index 0000000..552d9d5 --- /dev/null +++ b/day376/problem_test.go @@ -0,0 +1,30 @@ +package day376 + +import "testing" + +// nolint +var testcases = []struct { + coins []Pos + me Pos + expected Pos +}{ + {[]Pos{{0, 4}, {1, 0}, {2, 0}, {3, 2}}, Pos{0, 2}, Pos{0, 4}}, +} + +func TestClosestCoinToMe(t *testing.T) { + t.Parallel() + + for _, tc := range testcases { + if result := ClosestCoinToMe(tc.coins, tc.me); result != tc.expected { + t.Errorf("Expected %v, got %v", tc.expected, result) + } + } +} + +func BenchmarkClosestCoinToMe(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, tc := range testcases { + ClosestCoinToMe(tc.coins, tc.me) + } + } +}