DEV Community

Discussion on: Daily Challenge #6 - Grandma and her friends

Collapse
 
alvaromontoro profile image
Alvaro Montoro

JavaScript

let friends = [["A1", "X1"], ["A2", "X2"], ["A3", "X3"], ["A4", "X4"]];
let distances = [["X1", 100.0], ["X2", 200.0], ["X3", 250.0], ["X4", 300.0]];

// transform the array into an object to make it easier to process later
// solution from https://stackoverflow.com/q/26454655/3695983
distances = distances.reduce(function(p, c) { p[c[0]]=c[1]; return p; }, {});

function calculateDistance(friends, distances) {
  let total = 0;
  for (let x = 0; x < friends.length; x++) 
    if (friends[x].length === 2) 
      total += (distances[friends[x][1]] * 2);
  return total;
}

It doesn't use a smart algorithm to calculate the distance: grandma will visit a friend and then go back home, and continue with the next friend. If she doesn't know the city where a friend lives, she'll stay at home and meet the next friend.

Another version using array methods (and kind of unreadable):

let distances = { "X1": 100.0, "X2": 200.0, "X3": 250.0, "X4": 300.0 };
let friends = [ ["A1", "X1"], ["A2", "X2"], ["A3", "X3"], ["A4", "X4"] ];

const calculateDistance = (friends, distances) => friends.reduce((acc, curr) => curr.length === 2 ? acc + (distances[curr[1]] * 2) : acc, 0);

Here is a demo on CodePen.