gpt4 book ai didi

javascript - source, destination, distance - 计算距离最长的源和目的地

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:36:45 28 4
gpt4 key购买 nike

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

我希望输出能够计算行进距离最长的源和目标对。

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

在这种情况下,我的输出将是 highestDistance = [a, b, 300] ( between a and b => 200 + 100 = 300)

我正在尝试用 javascript 编写一个函数。什么数据结构适合这里?

我最初尝试创建一个 map 并将 [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]

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

最佳答案

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

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}

关于javascript - source, destination, distance - 计算距离最长的源和目的地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56536768/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com