Advertisement
Guest User

TripLength

a guest
Jan 23rd, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function findTripLength(paramsArr) {
  2.     let points = {};
  3.     let counter = 1;
  4.     for (let index = 0; index < paramsArr.length; index += 2) {
  5.         points[counter] = [paramsArr[index], paramsArr[index + 1]];
  6.         counter++;
  7.     }
  8.  
  9.     function calcDistance(pointA, pointB) {
  10.         return Math.sqrt(Math.pow(pointA[0] - pointB[0], 2) + Math.pow(pointA[1] - pointB[1], 2));
  11.     }
  12.  
  13.     let shortestPath = Number.MAX_VALUE;
  14.     let allDistances = {};
  15.     for (let i = 1; i <= 3; i++) {
  16.         for (let j = 1; j <= 3; j++) {
  17.             if (j === i) {
  18.                 continue;
  19.             }
  20.  
  21.             for (let k = 1; k <= 3; k++) {
  22.                 if (k === j || i === k) {
  23.                     continue;
  24.                 }
  25.  
  26.                 let distance = calcDistance(points[i], points[j]) + calcDistance(points[j], points[k]);
  27.                 allDistances["" + i + j + k] = distance;
  28.                 if (distance <= shortestPath) {
  29.                     shortestPath = distance;
  30.                 }
  31.             }
  32.         }
  33.     }
  34.  
  35.     let filtered = {};
  36.     for (let distance in allDistances) {
  37.         if (allDistances[distance] <= shortestPath) {
  38.             filtered[distance] = allDistances[distance];
  39.         }
  40.     }
  41.  
  42.     let keys = [];
  43.     for (let key in filtered) {
  44.         keys.push(key);
  45.     }
  46.  
  47.     keys.sort();
  48.     let pointOrder = keys[0].split("").join("->");
  49.     return `${pointOrder}: ${filtered[keys[0]]}`;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement