简体   繁体   English

连接形状中所有点的算法

[英]Algorithm to connect all points in a shape

I'm trying to figure out how to connect all points in a shape, with the amount of points being dynamic. 我试图弄清楚如何将形状中的所有点连接起来,并且点的数量是动态的。

I'll use a square to demonstrate, there's four points: 我将使用一个正方形进行演示,有四个要点:

a - top left, b - top right, c - bottom right, d - bottom left a-左上方,b-右上方,c-右下方,d-左下方

So... 所以...

var connections = [
    new Connection(a, b),
    new Connection(a, c),
    new Connection(a, d),
    new Connection(b, c),
    new Connection(b, d),
    new Connection(c, d)
];

Connects all points in a square (or any four sided polygon), but I want to do this automatically by looping through an array of points (displayed as abcd here for simplicity's sake) so it will work for any polygon. 连接正方形(或任何四边形多边形)中的所有点,但我想通过遍历点数组(为简单起见在此显示为abcd)来自动执行此操作,因此它适用于任何多边形。 I tried to work out a pattern and implement it in a couple of for-loops but that failed. 我试图找出一种模式,并在几个for循环中实现它,但是失败了。 I expect it's really simple... 我希望这真的很简单...

Any help is appreciated, thanks. 任何帮助表示赞赏,谢谢。

Pseudocode: 伪代码:

for (var i=0; i<Shape.Count; i++) {
  for (var j=i+1; j<Shape.Count; j++) {
    List.Add(i,j);
  }
}
var Connection = function (a, b) {
    console.log('Connecting ' + a + ' and ' + b);
}

var points = ['a','b','c','d','e'];

(function traverse() {
    for (var i = 0; i < points.length - 1; i += 1) {
        new Connection(points[0], points[ i + 1 ]);
    }
    points = points.slice(1);
    if (points.length > 1) {
        traverse(points);
    }
}());

That will output: 将会输出:

Connecting a and b
Connecting a and c
Connecting a and d
Connecting a and e
Connecting b and c
Connecting b and d
Connecting b and e
Connecting c and d
Connecting c and e
Connecting d and e 

Demo: http://jsfiddle.net/1j5n5x55/ 演示: http//jsfiddle.net/1j5n5x55/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM