-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoogleQ7.java
More file actions
78 lines (63 loc) · 2.46 KB
/
GoogleQ7.java
File metadata and controls
78 lines (63 loc) · 2.46 KB
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
import java.util.*;
public class GoogleQ7 {
private static class WorkerBike {
public int workerId;
public int bikeId;
public WorkerBike(int workerId, int bikeId) {
this.workerId = workerId;
this.bikeId = bikeId;
}
};
private static int computeDistance(int[] worker, int[] bike) {
return Math.abs(worker[0] - bike[0]) + Math.abs(worker[1] - bike[1]);
}
private List<Integer> removeValue(List<Integer> list, int value) {
for (int i = 0; i < list.size(); ++i) {
if (list.get(i) == value) {
list.remove(i);
return list;
}
}
return null;
}
public int[] assignBikes(int[][] workers, int[][] bikes) {
SortedMap<Integer, List<WorkerBike>> workerBikePairs = new TreeMap<>();
List<Integer> workersL = new ArrayList<>();
List<Integer> bikesL = new ArrayList<>();
// Let's compute list with closest workers per bike
for (int j = 0; j < bikes.length; ++j) {
bikesL.add(j);
int minDistance = Integer.MAX_VALUE;
for (int i = 0; i < workers.length; ++i) {
if (!workersL.contains(i)) {
workersL.add(i);
}
int distance = computeDistance(workers[i], bikes[j]);
List<WorkerBike> workerBike = workerBikePairs.get(distance);
if (workerBike == null) {
workerBike = new ArrayList<>();
}
workerBike.add(new WorkerBike(i, j));
workerBikePairs.put(distance, workerBike);
}
}
// Let's pick best bike for a worker
int[] ret = new int[workers.length];
for (List<WorkerBike> workerBikeL : workerBikePairs.values()) {
for (WorkerBike workerBike : workerBikeL) {
if (workersL.contains(workerBike.workerId) && bikesL.contains(workerBike.bikeId)) {
ret[workerBike.workerId] = workerBike.bikeId;
workersL = removeValue(workersL, workerBike.workerId);
bikesL = removeValue(bikesL, workerBike.bikeId);
}
}
}
return ret;
}
public void run() {
int[][] workers = { {0, 0}, {2, 1} };
int[][] bikes = { {1, 2}, {3, 3} };
int[] ret = assignBikes(workers, bikes);
System.out.println(Arrays.toString(ret));
}
}