edwardmlyte
edwardmlyte

Reputation: 16577

Comparing object in array to everything else in same array

I want to compare each item in an array to every other item in said array. I'm doing this at the moment, is it ok or is there a prettier/faster/more logical way of doing it?

for(int i=0; i<array1.size(); i++){
  for(int j=0; j<array1.size(); j++){
    if(i!=j){
      ..do stuff..
    }
  }
}

Upvotes: 3

Views: 9037

Answers (4)

occulus
occulus

Reputation: 17014

You're doing too many comparisons, plus you're comparing every item to itself needlessly. What you want is this:

for(int i=0; i<array1.size(); i++){
  for(int j=i + 1; j<array1.size(); j++){
     if(arr[i] != arr[j]){
        ..do stuff..
     }
  }
}

(This is assuming that your idea of equality is commutative, which equality normally is.)

If there are N items in your array, your original snippet would be doing N^2 comparisons, whereas my snippet is doing N(N-1)/2 comparisons.

Upvotes: 8

aioobe
aioobe

Reputation: 420971

Provided your comparison-relation is symmetrical you could do away with

for(int i = 0; i < array1.size(); i++) {

    // Note the initial value of j
    for(int j = i + 1; j < array1.size(); j++) {
        if (i != j) {
            ..do stuff..
        }
    }
}

An alternative style (which keeps indentation down) is to do

for(int i = 0; i < array1.size(); i++) {

    // Note the initial value of j
    for(int j = i + 1; j < array1.size(); j++) {
        if (i == j)
            continue;

        ..do stuff..
    }
}

Upvotes: 4

Marcus Fr&#246;din
Marcus Fr&#246;din

Reputation: 12882

As far as speed goes you could just loop until j < i instead of the whole array in the inner clause and that should cover you.

eg if array is = [1,2,3,4] you'd get

  • For 1: Don't compare.
  • For 2: Compare to 1.
  • For 3: Compare to 1 2.
  • For 4: Compare to 1 2 3.

So all are compared.

Upvotes: 2

Phil Quinn
Phil Quinn

Reputation: 111

I don't see why that wouldn't work.

Although I always thought that you had to call .length on arrays (as it's a field and not a method).

Upvotes: 0

Related Questions