一个最佳路径的问题
区域内有很多不规则的点,要求4个点为一组组成一个路线后删除,路线利用最佳。 PS:地图内任意一点为起点。问了好多人…
8 回复
function gendata(n, x, y) {
var data = [];
for (var i = 0; i < n; i++) {
data.push({
x: Math.ceil(Math.random() * x),
y: Math.ceil(Math.random() * y)
});
}
return data;
}
function gencombine(n, m) {
var combine = [];
if (m > n) return combine;
var stack = [];
var first = []
for (var i = 0; i < m; i++) {
stack[i] = i;
first[i] = i;
}
combine.push(first);
var last = [];
var end = n - m;
for (var i = 0; i < m; i++) {
last[i] = end + i;
}
var pos = m - 1;
var lastm = m - 1;
var temp;
while (true) {
if (stack[pos] < last[pos]) {
stack[pos]++;
temp = stack[pos];
pos++;
if (pos <= lastm) {
stack[pos] = temp;
}
} else {
pos--;
if (pos < 0) break;
}
if (pos > lastm) {
var tmp = [];
for (var i = 0; i < m; i++) {
tmp[i] = stack[i];
}
combine.push(tmp);
pos = lastm;
}
}
return combine;
}
var num = 20;
var X = 50;
var Y = 50;
var data = gendata(num, X, Y);
var combine = gencombine(num, 4);
function caldist(c) {
var temp = [];
for (var i = 0; i < c.length; i++) {
temp[i] = data[c[i]];
}
temp.sort(function(a, b){
if (a.x > b.x) {
return 1;
} else if (a.x == b.x) {
if (a.y > b.y) {
return 1;
} else {
return -1;
}
} else {
return -1;
}
});
var val = 0;
var first = temp[0];
for (var m = 1; m < temp.length; m++) {
var next = temp[m];
var xx = next.x - first.x;
var yy = next.y - first.y;
val = xx * xx + yy * yy;
first = next;
}
return val;
}
var min_value = caldist(combine[0]);
var min_index = 0;
for (var i = 1; i < combine.length; i++) {
var val = caldist(combine[i]);
if (val < min_value) {
min_value = val;
min_index = i;
}
}
console.log(min_value);
console.log(min_index);
console.log(combine[min_index]);
var c = combine[min_index];
for (var i = 0; i < c.length; i++) {
console.log(data[c[i]]);
}