Skip to content

Commit f835a78

Browse files
author
Mauricio Klein
committed
Add solution for challenge #47
1 parent a3af490 commit f835a78

File tree

6 files changed

+55
-0
lines changed

6 files changed

+55
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,4 @@
4646
- [x] [Challenge 44: Find the k-th Largest Element in a List](challenge-44/)
4747
- [x] [Challenge 45: Occurrences of a number in a sorted array](challenge-45/)
4848
- [x] [Challenge 46: Sudoku solver](challenge-46/)
49+
- [x] [Challenge 47: Closest coin](challenge-47/)

challenge-47/Makefile

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test:
2+
python test_*.py
3+
4+
.PHONY: test

challenge-47/README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Closest coin
2+
3+
This problem was asked by Google.
4+
5+
## Description
6+
7+
You are writing an AI for a 2D map game. You are somewhere in a 2D grid, and there are coins strewn about over the map.
8+
9+
Given the position of all the coins and your current position, find the closest coin to you in terms of Manhattan distance. That is, you can move around up, down, left, and right, but not diagonally. If there are multiple possible closest coins, return any of them.
10+
11+
## Example
12+
```
13+
Input:
14+
coins: [(0,4), (1,0), (2,0), (2,4), (3,2)] # Pair (row, column)
15+
your position: (0,2)
16+
17+
Output: (0,4)
18+
```

challenge-47/__init__.py

Whitespace-only changes.

challenge-47/solver.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
def closest_coin(coins, p):
2+
if not coins:
3+
return None
4+
5+
closest_dist = float('inf')
6+
closest_point = None
7+
8+
for coin in coins:
9+
dist = distance(p, coin)
10+
11+
if dist < closest_dist:
12+
closest_dist = dist
13+
closest_point = coin
14+
15+
return closest_point
16+
17+
def distance(p1, p2):
18+
x1, y1 = p1
19+
x2, y2 = p2
20+
21+
return abs(x1 - x2) + abs(y1 - y2)

challenge-47/test_solver.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import unittest
2+
from solver import closest_coin
3+
4+
class TestSolver(unittest.TestCase):
5+
def test_closest_coin(self):
6+
self.assertEqual(closest_coin([(0,4), (1,0), (2,0), (3,2)], (0,2)), (0,4))
7+
self.assertEqual(closest_coin([(0,0), (0,4) ], (0,2)), (0,0))
8+
self.assertEqual(closest_coin([ ], (0,2)), None )
9+
10+
if __name__ == "__main__":
11+
unittest.main()

0 commit comments

Comments
 (0)