连接形状中所有点的算法

时间:2013-03-02 06:56:40

标签: javascript connection polygon point

我正在试图找出如何连接形状中的所有点,其中点的数量是动态的。

我将使用一个正方形来演示,有四点:

a - 左上角, b - 右上角, c - 右下角, d - 左下角

因此...

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)
];

连接正方形(或任何四边形多边形)中的所有点,但我想通过循环遍历点阵列(为简单起见在此处显示为abcd)自动执行此操作,因此它适用于任何多边形。我试图找出一个模式,并在几个for循环中实现它,但失败了。我希望它真的很简单......

感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:2)

伪代码:

for (var i=0; i<Shape.Count; i++) {
  for (var j=i+1; j<Shape.Count; j++) {
    List.Add(i,j);
  }
}

答案 1 :(得分:2)

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);
    }
}());

那将输出:

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 

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