views:

327

answers:

3

I have Collection List<Car>.

How to compare each item from this collection with rest without repeatition.

Ex:

  1. iteration:

this car is Audi and secondCar is BMW

bool IsSimilar(Car secondCar)
{
  if(this.Name==secondCar.Name) return true;
  return false;
}

this is not permitted:

n iteration

this car is BMW and secondCar is Audi

bool IsSimilar(Car secondCar)
{
  if(this.Name==secondCar.Name) return true;
  return false;
}

Clearer:

List<Car> car=new List<Car>();
List<Pair> pairs=new List<Pair>();
pairs.Cars=new List<Car>();

foreach(Car car in cars)
{
  foreach(Car secondCar in cars)
  {
    if(secondCar!=car)
    {
      if(car.Name==secondCar.name && car.Owner==secondCar.Owner)
      {
        Pair pair=new Pair();
        pair.Cars.Add(car);
        pair.Cars.Add(secondCar);
        pairs.Add(pair);
      }
    }
  }
}

I'm just don't want to compare cars twice(you know first iteration compare car 1 with car2, next car2 is base car and car1 is secondCar)

Sorry for my terrible English

+3  A: 

Here is a simple way to get unique combinations from a list.

for(int i = 0; i < list.Count; i++)
    for(int j = i + 1; j < list.Count; j++)
        // perform operation
P Daddy
no, it is not this.Look:i=0, and j=1we have car1 and car2.i=1, and j=0we have car2 and car 1.I don't wanna repeat the same job(checking properties of object, because it has done in previous iteration)
@phenevo: When i=1, j will start at 2 and will never be 0. That's the point.
P Daddy
+3  A: 

Don't loop over the collection, loop over the indices

for (i = 0; i < length(cars); i++) {
    for (j = i+1; j < length(cars); j++) {
        <do comparison>
    }
}
no, it is not this.Look:i=0, and j=1we have car1 and car2.i=1, and j=0we have car2 and car 1.I don't wanna repeat the same job(checking properties of object, because it has done in previous iteration)
when i = 1, j will start from i + 1 = 1 + 1 = 2, so you won't compare things twice. j will never be 0 when i = 1.
IVlad
@phenevo, using sirlark's method you could never have i=1 and j=0 because j always starts 1 higher than the current value of i.
Theran
yeah, sorry (coffe was ended yesterday :) )
+2  A: 

I'm going to repeat what others have said and explain your comments to them (which was erroneous):

for (int i = 0; i < N; i++) {
    for (int j = i+1; j < N; j++) {
        <do something>
    }
}

You commented about this technique that "no, it is not this. Look: i=0, and j=1 we have [...]. i=1, and j=0 we have [...]".

What you have missed is that j always starts from i+1. So it will never be the case that i=1 and j=0 as you mentioned!

polygenelubricants