Skip to content

Instantly share code, notes, and snippets.

@Jimbly
Created March 27, 2017 03:42
Show Gist options
  • Select an option

  • Save Jimbly/180f5b0b9af02b31017646d43e2cdaf8 to your computer and use it in GitHub Desktop.

Select an option

Save Jimbly/180f5b0b9af02b31017646d43e2cdaf8 to your computer and use it in GitHub Desktop.
let pos = [
[0, 0],
[-35, -12],
[-50, -50],
[-80, -40],
[-50, 50],
[0, -66],
[35, -35],
[68, -50],
[70, -4],
[35, 12],
[0, 12],
];
function dist(ii, jj) {
return Math.max(Math.abs(pos[ii][0] - pos[jj][0]), Math.abs(pos[ii][1] - pos[jj][1]));
}
let best = Infinity;
let best_arr;
function search(cur_pos, cur_dist, mask) {
/* jshint bitwise:false*/
let m = 1;
let b = false;
let r = false;
for (let ii = 0; ii < pos.length - 1; ++ii) {
if (!(m & mask)) {
b = true;
if (search(ii, cur_dist + dist(cur_pos, ii), mask | m)) {
best_arr.push(cur_pos);
r = true;
}
}
m = m << 1;
}
if (!b) {
cur_dist += dist(cur_pos, pos.length - 1);
if (cur_dist < best) {
best = cur_dist;
best_arr = [pos.length - 1, cur_pos];
return true;
}
}
return r;
}
search(0, 0, 1);
best_arr = best_arr.reverse();
// best_arr = [0,1,2,3,4,5,6,7,8,9,10];
let sum = 0;
for (let ii = 1; ii < best_arr.length; ++ii) {
sum += dist(best_arr[ii-1], best_arr[ii]);
}
console.log(sum, best_arr.map(function (idx, ii) { return pos[idx].toString(', ') + (ii > 0 ? ' (' + dist(best_arr[ii-1], idx) + ')' : ''); }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment