仅在Processing中基于一个属性对对象数组进行排序

时间:2016-02-19 10:53:58

标签: processing

我有一系列名为Line的类随机绘制的线条。 我已将所有对象放入数组中。我想用虚线连接彼此靠近的任何线。我能想到的最简单的方法是说x1坐标是否与另一条线的x1相距<5像素,然后绘制一条连接两个x1坐标的虚线。 我遇到的问题是如何将所有x1坐标与所有其他x1坐标进行比较。我认为这应该涉及1.对数组进行排序然后2.比较连续的数组元素。但是我想只对x1进行排序,我不知道该怎么做。

到目前为止,这是我的代码:

 
class Line{
   public float x1; 
   public float y1;
   public float x2;
   public float y2;
   public color cB;
   public float rot;
   public float fat;

   public Line(float x1, float y1, float x2, float y2, color tempcB, float rot, float fat){
      this.x1 = x1;
      this.y1 = y1;
      this.x2 = x2;
      this.y2 = y2;
      this.cB = tempcB;
      this.rot = rot;
      this.fat = fat;
   };void draw(){
      line(x1, y1, x2, y2);
       //float rot = random(360);
       float fat = random(5);
       strokeWeight(fat);
       ////stroke (red,green,blue,opacity)
       stroke(fat*100, 0, 0);
      rotate(rot);
   }

}


//Create array of objects 
ArrayList<Line> lines = new ArrayList<Line>();

void setup(){
  background(204);
  size(600, 600); 

   for(int i = 0; i < 200; i++){
       float r = random(500);
       float s = random(500);
       lines.add(new Line(r,s,r+10,s+10,color(255,255,255),random(360),random(5)));

   }

    //Draw out all the lines from the array

    for(Line line : lines){
      line.draw();

    //Print them all out
      println(line.x1,line.y1,line.x2,line.y2,line.cB,line.rot,line.fat);
 }
}

//Now create connections between the elements

//If the x1 of the line is <5 pixels from another line then create a dotted line between the x1 points.

2 个答案:

答案 0 :(得分:1)

就像其他答案所说的那样,你需要比较两个终点才有意义。您也无需对任何内容进行排序。

您应该使用dist()函数,而不是仅尝试比较x坐标。 dist()函数需要2点并给出它们的距离。您可以使用它来检查两个点是否彼此接近:

 
float x1 = 75;
float y1 = 100;
float x2 = 25;
float y2 = 125;

float distance = dist(x1, y1, x2, y2);
if(distance < 100){
   println("close");
}

您可以在Line课程中使用此功能循环浏览其他行并检查近点,或找到最近的点,无论您想要什么。

与往常一样,我建议您尝试一些问题并在遇到问题时提出另一个问题。

答案 1 :(得分:0)

问题在于Line由两个点组成,尽管被绑在一起(双关语),你需要独立检查每一行的 points 。您真正不需要检查的唯一一点是同一个Line实例中的其他点。

在这种情况下,拥有Point类可能符合您的最佳利益。然后,Line将使用Point实例来定义两端而不是原始浮点坐标。通过这种方式,您既可以拥有行列表,也可以拥有点列表。

通过这种方式,您可以按x坐标或y坐标对点进行排序,并抓住点的5个像素内的所有点(当然,这不是Line实例中的相同实例或其他点)。

能够将处理拆分为点和线很重要,因为您使用多个视图来处理相同的数据。作为一般规则,只要处理当前形式的繁琐数据,就应该重新排列数据。但是,如果我可以提出建议,那么排序并不是绝对必要的。如果您使用所有其他点检查单个点,则必须根据当前点重复排序,这比简单地在列表中传递以处理所有其他关闭点更重要足够。