我正在为游戏编写军队移动算法。我有工作代码,但是它具有三个嵌套的“ for”语句,它们在相当大的对象集合上进行迭代。这将驱动动画,并以大约60fps的速度运行)。我正在寻找最佳性能。
起始位置是对象(单位)的数组(军队)。每个单元对象都有两个属性:
( unit.pathChain )-表示两个节点之间完整路径链的数组数组(例如,通过nodeB从nodeA移到nodeC看起来像[[A,B],[B ,C]])。
( unit.distance )-一个整数,描述仅在路径链的第一条路径上行驶的距离。
该算法的挑战在于以最小的行进距离减少所有可能的路径(对于超出第一个路径的所有路径,其距离都被视为0。对于链中的第一个路径,距离是从单位继承的。
我已经编写了以下内容,并且可以正常工作,但是直观上感觉笨拙且缓慢,我正努力对其进行优化(以提高性能-并非专门针对代码长度/样式等)。
//set up test units with distances and pathchains
let unit1 = {distance: 5, pathChain: [["a", "b"]]};
let unit2 = {distance: 2, pathChain: [["c", "d"],["d", "e"]]};
let unit3 = {distance: 1, pathChain: [["c", "d"],["d", "a"],["a","b"]]};
let unit4 = {distance: 6, pathChain: [["a", "b"]]};
let unit5 = {distance: 3, pathChain: [["e", "f"]]};
let unit6 = {distance: 4, pathChain: [["e", "f"]]};
//assign test units to an army
let army = [unit1, unit2, unit3, unit4, unit5, unit6];
//container for results
let resultObjects = [];
//iterate over all units
for (let i = 0; i < army.length; i++){
let unit = army[i];
//for each unit iterate over each path chain
for (let i2 = 0; i2 < unit.pathChain.length; i2++){
let testingPath = unit.pathChain[i2];
let pathFound = false;
//testing distance is 0 unless it is the first path in the chain in which case distance is inherited from unit
testingDistance = 0;
if(i2 == 0){
testingDistance = unit.distance;
}
//iterate over all previously seen paths
for (let i3 = 0; i3 < resultObjects.length ; i3++){
let resultObject = resultObjects[i3];
let resultPath = resultObject.path;
//test to see if we have already seen this path before
if (testingPath[0] == resultPath[0] && testingPath[1] == resultPath[1]){
pathFound = true;
//if we have seen this path before but this path has a lower distance update the result record to denote a lower distance
if (testingDistance < resultObject.minimumDistance){
resultObject.minimumDistance = testingDistance;
}
}
}
//if we have not seen this path before add it to the results array
if (pathFound == false){
let newResultObject = {path:[testingPath[0], testingPath[1]], minimumDistance: testingDistance};
resultObjects.push(newResultObject);
}
}
}
console.log(resultObjects);
预期输出:
//results should be:
//[
// {'path':['a','b'],'minimumDistance':0}
// ,{'path':['c','d'],'minimumDistance':1}
// ,{'path':['d','e'],'minimumDistance':0}
// ,{'path':['d','a'],'minimumDistance':0}
// ,{'path':['e','f'],'minimumDistance':3}
//]