Skip to content

Commit

Permalink
Merge 822de44 into a5785ed
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Nov 30, 2019
2 parents a5785ed + 822de44 commit 3b89dde
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

30 changes: 30 additions & 0 deletions day376/problem.go
Original file line number Diff line number Diff line change
@@ -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
}
30 changes: 30 additions & 0 deletions day376/problem_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}

0 comments on commit 3b89dde

Please sign in to comment.