-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathapartmentHunting.py
85 lines (68 loc) · 2.61 KB
/
apartmentHunting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# def apartmentHunting(blocks, reqs):
# maxDistanceAtBlock = [float("-inf") for block in blocks]
# for i in range(len(blocks)):
# for req in reqs:
# closestReqDistance = float("inf")
# for j in range(len(blocks)):
# if blocks[j][req]:
# closestReqDistance = min(
# closestReqDistance, distanceBetween(i, j))
# maxDistanceAtBlock[i] = max(
# maxDistanceAtBlock[i], closestReqDistance)
# return getIdxAtMinValue(maxDistanceAtBlock)
# def distanceBetween(a, b):
# return abs(a-b)
# def getIdxAtMinValue(array):
# idxAtMinValue = 0
# minValue = float("inf")
# for i in range(len(array)):
# currentValue = array[i]
# if currentValue < minValue:
# minValue = currentValue
# idxAtMinValue = i
# return idxAtMinValue
def apartmentHunting(blocks, reqs):
minDistancesFromBlocks = list(
map(lambda req: getMinDistances(blocks, req), reqs))
maxDistancesFromBlocks = getMaxDistancesAtBlocks(
blocks, minDistancesFromBlocks)
return getIdxAtMinValue(maxDistancesFromBlocks)
def getMaxDistancesAtBlocks(blocks, minDistancesFromBlocks):
maxDistancesFromBlocks = [0 for block in blocks]
for i in range(len(blocks)):
minDistancesFromBlock = list(map(lambda distances: distances[i], minDistancesFromBlocks))
maxDistancesFromBlocks[i] = max(minDistancesFromBlock)
return maxDistancesFromBlocks
def getMinDistances(blocks, req):
minDistances = [0 for block in blocks]
closestReqIdx = float("inf")
for i in range(len(blocks)):
if blocks[i][req]:
closestReqIdx = i
minDistances[i] = distanceBetween(i, closestReqIdx)
for i in reversed(range(len(blocks))):
if blocks[i][req]:
closestReqIdx = i
minDistances[i] = min(
minDistances[i], distanceBetween(i, closestReqIdx))
return minDistances
def getIdxAtMinValue(array):
idxAtMinValue = 0
minValue = float("inf")
for i in range(len(array)):
currentValue = array[i]
if currentValue < minValue:
minValue = currentValue
idxAtMinValue = i
return idxAtMinValue
def distanceBetween(a, b):
return abs(a-b)
blocks = [
{"gym": False, "school": True, "store": False},
{"gym": True, "school": False, "store": False},
{"gym": True, "school": True, "store": False},
{"gym": False, "school": True, "store": False},
{"gym": False, "school": True, "store": True}
]
reqs = ["gym", "school", "store"]
print(apartmentHunting(blocks, reqs))