Skip to content

Commit d4a3806

Browse files
Amazon SDE questions try
1 parent 4451cd6 commit d4a3806

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*Amazon SDE Assessment // QUESTION: There are a set of locations, represented by points.
2+
Find the closest locations for the truck with start point (0,0), for the number of deliveries to be made
3+
4+
For eg: if the locations are "[[1,-1], [-2,4], [1,1], [3,2]]"
5+
numDeliveries = 2
6+
Closest locations would be [[1, -1], [1, 1]]
7+
*/
8+
9+
function findKClosest(numDestinations, allLocations, numDeliveries) {
10+
// Array to store coordinates and distance
11+
let pointsWithDistance = [];
12+
const outputArray = [];
13+
for (let i = 0; i < allLocations.length; i++) {
14+
let currentLocation = allLocations[i];
15+
distance = Math.sqrt(
16+
currentLocation[0] * currentLocation[0] +
17+
currentLocation[1] * currentLocation[1]
18+
);
19+
pointsWithDistance.push({ location: currentLocation, distance: distance });
20+
}
21+
22+
pointsWithDistance.sort(function(a, b) {
23+
if (a.distance > b.distance) {
24+
return 1;
25+
}
26+
27+
if (a.distance < b.distance) {
28+
return -1;
29+
}
30+
return 0;
31+
});
32+
33+
for (let i = 0; i < numDeliveries; i++) {
34+
outputArray.push(pointsWithDistance[i].location);
35+
}
36+
return outputArray;
37+
}

exercises/misc/findOptimalRoute.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
function findOptimalRoute(forwardRouteArr, returnRouteArr, maxTravelDistance) {
2+
let routeWithDistance = [];
3+
4+
for (let i = 0; i < forwardRouteArr.length; i++) {
5+
let currentForwardRoute = forwardRouteArr[i];
6+
for (let j = 0; j < returnRouteArr.length; j++) {
7+
let currenReturnRoute = returnRouteArr[j];
8+
let distance = currentForwardRoute[1] + currenReturnRoute[1];
9+
routeWithDistance.push({
10+
route: [currentForwardRoute[0], currenReturnRoute[0]],
11+
distance: distance
12+
});
13+
}
14+
}
15+
16+
routeWithDistance.sort((a, b) => {
17+
if (a.distance > b.distance) {
18+
return -1;
19+
}
20+
21+
if (a.distance < b.distance) {
22+
return 1;
23+
}
24+
25+
return 0;
26+
});
27+
28+
let optimalDistance = routeWithDistance[0].distance;
29+
outputArray.push(routeWithDistance[0].route);
30+
31+
for (let i = 1; i < routeWithDistance.length; i++) {
32+
if (
33+
routeWithDistance[i].distance <= maxTravelDistance &&
34+
routeWithDistance[i].distance === optimalDistance
35+
) {
36+
outputArray.push(routeWithDistance[i].route);
37+
}
38+
}
39+
40+
return outputArray;
41+
}

0 commit comments

Comments
 (0)