Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created December 27, 2023 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/12d591bcc906810650cabdccb374c326 to your computer and use it in GitHub Desktop.
Save primaryobjects/12d591bcc906810650cabdccb374c326 to your computer and use it in GitHub Desktop.
// Solved by calculating difference between each point diagonally and straight remainder.
const minTimeToVisitAllPoints = (points: number[][]): number => {
let moves = 0;
for (let i=1; i<points.length; i++) {
const dist_x = Math.abs(points[i-1][0] - points[i][0]);
const dist_y = Math.abs(points[i-1][1] - points[i][1]);
const dist_diag = Math.min(dist_x, dist_y);
const dist_straight = Math.abs(dist_y - dist_x);
moves += dist_diag + dist_straight;
}
return moves;
}
// Solved by walking each step from one point to the next.
const minTimeToVisitAllPoints = (points: number[][]): number => {
const path = [];
let index = 1;
// Go through each point, starting at the initial point.
let point1 = points[0];
while (index < points.length) {
const point2 = points[index];
// Move closer to point2.
if (point1[0] < point2[0]) {
point1[0]++;
}
else if (point1[0] > point2[0]) {
point1[0]--;
}
if (point1[1] < point2[1]) {
point1[1]++;
}
else if (point1[1] > point2[1]) {
point1[1]--;
}
// Store the move.
path.push(point1);
// Check for waypoint.
if (point1[0] === point2[0] && point1[1] === point2[1]) {
// We've reached the next point.
point1 = point2;
index++;
}
}
return path.length;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment