-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #759 from vaskoz/day376
Day376
- Loading branch information
Showing
3 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |