如何检查一个数组中的值是否相等而不检查同一件事

时间:2019-01-15 02:19:30

标签: java logic

我有这个数组

Ball[] balls = new Ball[7]; // 7 just being an example

在我的Ball班上,我有x和y值的吸气剂和吸气剂。 我正在尝试比较x和y值,以确保它们不相交。

我首先想到的是使循环看起来像

for(Ball b1 : balls) {
    for(Ball b2 : balls) {
    if(b1.intersects(b1, b2)) {. . .} // I made intersects, not my issue 
    }
}

但这并不好,因为它比较:

  1. 球0到球0
  2. 第1球到第1球
  3. for(int i = 0; i < balls.length; i++) {
        System.out.println(f.getContentPane().getWidth() + "\n" + f.getContentPane().getHeight());
    
        int radius = 10 + rand.nextInt(20);
    
        balls[i] = new Ball(360, radius,
                rand.nextInt(f.getContentPane().getWidth() - 4 * radius - 5) + radius + 5,
                rand.nextInt(f.getContentPane().getHeight() - 4 * radius - 5) + radius + 5
        );
    }
    for(Ball b1 : balls) {
        for (Ball b2 : balls) {
            while (b1.intersects(b1, b2)) {
                System.out.println("Ball started out inside of another, replacing now.");
                b1.setX(rand.nextInt(f.getContentPane().getWidth() - 2 * b1.getRadius() - 5) + b1.getRadius() + 5);
                b1.setY(rand.nextInt(f.getContentPane().getHeight() - 2 * b1.getRadius() - 5) + b1.getRadius() + 5);
            }
        }
    }
    

//////////////班级变更//////////////////

class Ball {
private int direction;
private int radius;
private int x,y;

Ball(int direction, int radius, int x, int y) {
    this.direction = direction;
    this.radius = radius;
    this.x = x;
    this.y = y;
}

// Getters + Setters here

boolean intersects(Ball b1, Ball b2) {
    double x = Math.pow((b2.getX() - b1.getX()), 2);    // Distance formula
    double y = Math.pow((b2.getY() - b1.getY()), 2);    // Distance formula
    double r = b1.getRadius() + b2.getRadius();

    //System.out.println(x + " + " + y + " <= " + r );
    return x + y <= r;
}

}

(忽略我没有将我的第一批代码放在方法和类中,而是在我的实际代码中完成了。)

无论出于何种原因,如果没有大量的if语句,我想不出办法

(因此,我正在寻求执行此操作的最佳方法)

1 个答案:

答案 0 :(得分:2)

比较Ball的每对不同的for (int i = 0; i < balls.length; ++i) { Ball b1 = balls[i]; for (int j = i+1; j < balls.length; ++j) { Ball b2 = balls[j]; if (b1.intersects(b1, b2)) { // ... } } } 而不对任何两对以上进行比较的一种方法是:

balls

检测在解决以前的冲突过程中引入的新冲突仅意味着对boolean foundCollision; int numTries = 0; int maxTries = 1000000; do { foundCollision = false; for (int i = 0; i < balls.length; ++i) { Ball b1 = balls[i]; for (int j = i+1; j < balls.length; ++j) { Ball b2 = balls[j]; if (b1.intersects(b1, b2)) { foundCollision = true; // resolve collision... } } ++numTries; } while (foundCollision && numTries < maxTries); if (numTries >= maxTries) System.err.println("Couldn't sort out balls after " + maxTries + "tries: what now?"); 进行多次遍历,直到不再有任何冲突为止。一个简单的,也许是天真的方法是这样的:

az network dns record-set txt show -g myresourcegroup -z 'mydomain.com' -n 'mytxtvalues' --query "txtRecords[*].value[?starts_with(@, 'abc')]"