代码学校的最佳位置
Optimum Location for Code Schools
这是从代码战争中摘录的,但我不是在寻找作弊或任何东西。我几乎已经解决了这个问题,但我不确定我确定最佳位置的方法是否正确。
var optimumLocation = function(students, locations){
//your solution
var listOfLocations = [];
for (var key in locations) {
var obj = locations[key];
var totalDistance = 0;
for (var i = 0; i <= students.length-1; i+=1) {
console.log(students[i]);
var location = calculateDistance(students[i],[obj.x, obj.y]);
totalDistance += location;
}
listOfLocations.push({id:parseInt(key), dist:totalDistance});
}
listOfLocations.sort(function(a,b){
return a.dist - b.dist;
});
console.log(listOfLocations);
var id = listOfLocations[0].id;
return "The best location is number " + (id +1) + " with the coordinates x = " + locations[id].x + " and y = " + locations[id].y;
}
function calculateDistance (loc1, loc2) {
var distX = Math.abs(loc1[0] - loc2[0]);
var distY = Math.abs(loc1[1] - loc2[1]);
var distance = Math.sqrt(distX*distX + distY*distY);
return distance;
};
对于第一个测试用例
optimumLocation([[3,7],[2,2],[14,1]],[{id: 1, x: 3, y: 4}, {id: 2, x: 8, y: 2}]);
一切都很好。
但是对于第二个测试用例
optimumLocation([[152,7],[1,211],[14,56],[12,4],[142,7]],[{id: 1, x: 63, y: 55}, {id: 2, x: 55, y: 21},{id: 3, x: 144, y: 12}]);
正确的位置是位置 2,但我的功能认为它是位置 1。但是,根据我使用所有学生旅行的总距离最少的方法,位置 1 的距离最短,因此实际上应该是最佳解决方案位置 2。
任何帮助将不胜感激。
我已经设法自己解决了这个问题。对于那些想知道的人,我只是把问题复杂化了。题目说学生只能走直线,不能走对角线。因此,我没有使用毕达哥拉斯定理,而是只需将 x 和 y 距离相加即可找到总距离。
这是从代码战争中摘录的,但我不是在寻找作弊或任何东西。我几乎已经解决了这个问题,但我不确定我确定最佳位置的方法是否正确。
var optimumLocation = function(students, locations){
//your solution
var listOfLocations = [];
for (var key in locations) {
var obj = locations[key];
var totalDistance = 0;
for (var i = 0; i <= students.length-1; i+=1) {
console.log(students[i]);
var location = calculateDistance(students[i],[obj.x, obj.y]);
totalDistance += location;
}
listOfLocations.push({id:parseInt(key), dist:totalDistance});
}
listOfLocations.sort(function(a,b){
return a.dist - b.dist;
});
console.log(listOfLocations);
var id = listOfLocations[0].id;
return "The best location is number " + (id +1) + " with the coordinates x = " + locations[id].x + " and y = " + locations[id].y;
}
function calculateDistance (loc1, loc2) {
var distX = Math.abs(loc1[0] - loc2[0]);
var distY = Math.abs(loc1[1] - loc2[1]);
var distance = Math.sqrt(distX*distX + distY*distY);
return distance;
};
对于第一个测试用例
optimumLocation([[3,7],[2,2],[14,1]],[{id: 1, x: 3, y: 4}, {id: 2, x: 8, y: 2}]);
一切都很好。
但是对于第二个测试用例
optimumLocation([[152,7],[1,211],[14,56],[12,4],[142,7]],[{id: 1, x: 63, y: 55}, {id: 2, x: 55, y: 21},{id: 3, x: 144, y: 12}]);
正确的位置是位置 2,但我的功能认为它是位置 1。但是,根据我使用所有学生旅行的总距离最少的方法,位置 1 的距离最短,因此实际上应该是最佳解决方案位置 2。
任何帮助将不胜感激。
我已经设法自己解决了这个问题。对于那些想知道的人,我只是把问题复杂化了。题目说学生只能走直线,不能走对角线。因此,我没有使用毕达哥拉斯定理,而是只需将 x 和 y 距离相加即可找到总距离。