源,目的地,距离-计算距离最长的源和目的地

时间:2019-06-11 05:01:31

标签: javascript algorithm data-structures

我正在尝试解决一个计算任何两点之间的最大距离的问题。

我希望输出能够计算出旅行距离最大的源对和目的地对。

      obj = [{
                source: a,
                destination: b,
                distance: 200
              },
              {
                source: b,
                destination: a,
                distance: 100
              },
              {
                source: a,
                destination: c,
                distance: 100
              }
            ]     

在这种情况下,我的输出将是maximumDistance = [a,b,300](在a和b之间=> 200 + 100 = 300)

我正在尝试用JavaScript编写函数。哪种数据结构适合这里?

我最初尝试创建地图并将[source,destination]元组添加为键,如下所示:

 {
   [a, b]: 200,
   [a, c]: 100
 }

const obj = [{
                source: a,
                destination: b,
                distance: 200
              },
              {
                source: b,
                destination: a,
                distance: 100
              },
              {
                source: a,
                destination: c,
                distance: 100
              }
            ]

    function highestDistance(obj) {
          const highestPair = obj[0];
          const myMap = new Map();
          obj.forEach(pair => {
            let [source, destination] = [pair.source, pair.destination];
            if( myMap.has([source, destination]) || myMap.has([source, destination])){
                myMap.set() 
                 // not sure how to proceed and add the tuple to map here
                // I intend to compare the current highest and update highestPair value if the current pair distance is collectively bigger.
            } else {
              myMap.set([source, destination], pair[distance])
           }

          })

          return obj;
        }

输入:

      {
        source: a,
        destination: b,
        distance: 200
      },
      {
        source: b,
        destination: a,
        distance: 100
      },
      {
        source: a,
        destination: c,
        distance: 100
      }

输出:

[a, b, 300]

您能帮我解决这个问题吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以创建具有距离的对象。以后您需要找到最大距离。

var obj = [{
                source: 'a',
                destination: 'b',
                distance: 200
              },
              {
                source: 'b',
                destination: 'a',
                distance: 100
              },
              {
                source: 'a',
                destination: 'c',
                distance: 100
              }
            ]

var distMap = obj.reduce((f, n)=> {
  const {source,destination, distance } = n;
  const key  = `${source}->${destination}`
  const key2 = `${destination}->${source}`

  if(f[key2]){
    f[key2] = distance+ f[key2]
  } else {
    f[`${source}->${destination}`] = distance
  }
  return f
}, {}) // {a->b: 300, a->c: 100}