开发者

Combination without repetition

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开发者_StackOverflow)
    {
      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


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>
    }
}


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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜