Jump to content

  • Log In with Google      Sign In   
  • Create Account

Fastest way to get elements in one list but not in other and vice versa


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
11 replies to this topic

#1 GuyWithBeard   Members   -  Reputation: 932

Like
0Likes
Like

Posted 24 April 2014 - 11:16 PM

Hi,

 

There might be a term for this (list intersection?) but I am not sure so lets open it up a little bit.

 

I have two lists of integers, A and B. I need a fast way to get two new lists based on the elements in them. One of the new lists should contain all elements found in A but not in B, and the other list should contain all elements found in B but not in A. Since I am not really sure what to call this, I am having a hard time finding good info on it online.

 

I am looking for a general algorithm or best practice on how to do this sort of thing. If it matters, I am using C# for this. The length of the lists are usually quite small (less than 50 elements) but the algorithm needs to be quick since I need to do it every 10 frames or so.

 

I can think of a brute force way to do it, but is there anything faster?

 

Cheers!



Sponsor:

#2 Ashaman73   Crossbones+   -  Reputation: 8351

Like
0Likes
Like

Posted 25 April 2014 - 12:08 AM

Oppps, delete, fastcall22 is right, it doesnt work for single elements.


Edited by Ashaman73, 25 April 2014 - 12:47 AM.


#3 fastcall22   Crossbones+   -  Reputation: 4610

Like
2Likes
Like

Posted 25 April 2014 - 12:19 AM

Ashaman, I don't think that works. Consider A=[1,2,3,110,115] and B=[100,200]. With your code, A-B = [1,2,3] and B-A = [200]; the expected differences should be A and B respectively.

If linq is an option, you can use the Except filter:
List<int> a = new List<int>();
List<int> b = new List<int>();

for ( int i = 3; i <= 6; ++i )
	a.Add(i);
for ( int i = 5; i <= 8; ++i )
	b.Add(i);

IList<int> a_without_b, b_without_a;
a_without_b = a.Except(b).ToList();
b_without_a = b.Except(a).ToList();

foreach ( IList<int> l in new IList<int>[]{a_without_b,b_without_a})
	Console.WriteLine(string.Join(",", l.Select(x=>x.ToString()).ToArray()));
Sample with output

Edited by fastcall22, 25 April 2014 - 12:36 AM.

c3RhdGljIGNoYXIgeW91cl9tb21bMVVMTCA8PCA2NF07CnNwcmludGYoeW91cl9tb20sICJpcyBmYXQiKTs=

#4 SeraphLance   Members   -  Reputation: 1592

Like
1Likes
Like

Posted 25 April 2014 - 12:26 AM

http://msdn.microsoft.com/en-us/library/bb397894.aspx

 

Essentially the C# version of the standard library algorithm fastcall22 listed.

 

LINQ is magic.

 

EDIT:  More specifically, it's the Except function you want.

 

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except.aspx


Edited by SeraphLance, 25 April 2014 - 12:27 AM.


#5 GuyWithBeard   Members   -  Reputation: 932

Like
0Likes
Like

Posted 25 April 2014 - 12:50 AM

Thank you so far!

 

Yeah Ashaman's solution probably does not work in this situation since the lists are overlapping and can contain holes etc. Unfortunately, I cannot rely on LINQ in this case either as I am using Unity for mobile and it limits what I can do with LINQ (eg. runtime JIT required in most cases).



#6 Bacterius   Crossbones+   -  Reputation: 9576

Like
1Likes
Like

Posted 25 April 2014 - 01:11 AM

Well, you could just reimplement Except using the standard approach (it will likely be fast enough, for 50 items every 10 frames even the naive method would do it even on mobile I think), but theoretically it can be done in O(n log n) time by using the following approach:

 

1. sort lists a and b [O(n log n)]

2. for every element in a, check if it exists in list b via binary search, and same for b [n * O(log n) => O(n log n)]

 

And, if you don't mind using some extra memory, it can in fact be done in O(n) time, by replacing the sort and binary search with a lookup into a hash table:

 

1. put every element of a and b in hash tables Ha, Hb [n * amortized O(1) => O(n)]

2. for every element in a, check if it exists in Hb, and same for b [n * amortized O(1) => O(n)]

 

Astute readers will notice this is actually the naive algorithm, just implemented using a HashSet and its Contains method, because HashSets are awesome.

 

If the order of the resulting list needs to reflect the order of the two original lists, then you must iterate in the order of the original lists in step 2 (which will require making a copy of the list to sort it in the first case, otherwise you lose the order). But you didn't mention if this was the case, and if it isn't, then it just becomes a straightforward set intersection!


The slowsort algorithm is a perfect illustration of the multiply and surrender paradigm, which is perhaps the single most important paradigm in the development of reluctant algorithms. The basic multiply and surrender strategy consists in replacing the problem at hand by two or more subproblems, each slightly simpler than the original, and continue multiplying subproblems and subsubproblems recursively in this fashion as long as possible. At some point the subproblems will all become so simple that their solution can no longer be postponed, and we will have to surrender. Experience shows that, in most cases, by the time this point is reached the total work will be substantially higher than what could have been wasted by a more direct approach.

 

- Pessimal Algorithms and Simplexity Analysis


#7 fastcall22   Crossbones+   -  Reputation: 4610

Like
2Likes
Like

Posted 25 April 2014 - 01:32 AM

Bacterius, we can eliminate binary searching altogether since accessing the elements in both lists are sequential:
IList<int> a, b;
a.Sort();
b.Sort();

List<int> a_without_b = new List<int>();
List<int> b_without_a = new List<int>();

int adx = 0;
int bdx = 0;
while ( adx < a.Count && bdx < b.Count ) {
	int aa = a[adx];
	int bb = b[bdx];
	if ( aa < bb ) {
		a_without_b.Add(aa);
		adx++;
	} else if ( bb < aa ) {
		b_without_a.Add(bb);
		bdx++;
	} else {
		adx++;
		bdx++;
	}
}
for ( ; adx < a.Count; ++adx )
	a_without_b.Add(a[adx]);
for ( ; bdx < b.Count; ++bdx )
	b_without_a.Add(b[bdx]);
It should be the fastest out of all proposed solutions, as it doesn't make unnecessary iterations through binary search, and it doesn't occur any of the associated costs with hashing collisions. Of course, this is assuming both lists are sorted before hand; it could be that the HashSet approach might be faster if it takes less time than the sorting of both lists in this approach.

Edited by fastcall22, 25 April 2014 - 01:41 AM.

c3RhdGljIGNoYXIgeW91cl9tb21bMVVMTCA8PCA2NF07CnNwcmludGYoeW91cl9tb20sICJpcyBmYXQiKTs=

#8 duckflock   Members   -  Reputation: 580

Like
2Likes
Like

Posted 25 April 2014 - 03:06 AM

There might be a term for this (list intersection?) but I am not sure so lets open it up a little bit.

I have two lists of integers, A and B. I need a fast way to get two new lists based on the elements in them. One of the new lists should contain all elements found in A but not in B, and the other list should contain all elements found in B but not in A. Since I am not really sure what to call this, I am having a hard time finding good info on it online.

 

 

The elements that are in A and not in B are called the difference of A and B, written A \ B ( see wikipedia Complement ).

To my knowledge there is no mathematical term for both sets; it is simply A \ B and B \ A.

 

On another note I will bite the bullet and ask you why you are concerned about performance given your description:

  • Lists contain integers (cheap comparison)
  • Less than 50 elements per list (small data set)
  • Needs to be done every ~10th frame (low call amount)

Mobile devices aren't that slow nowadays. Converting the lists to sets and performing two difference operations shouldn't matter if you only do it every 10th frame.



#9 GuyWithBeard   Members   -  Reputation: 932

Like
0Likes
Like

Posted 25 April 2014 - 04:13 AM

Valid question, duckflock. In this case I could probably do it the brute force way (which is actually not that different from the code fastcall22 posted, I need to test that, thanks man!), but this is not the first time I have come across this problem and sometimes the conditions haven't been so forgiving. That's why I was wondering if there is some defacto way to do this, even for complicated cases.



#10 SeraphLance   Members   -  Reputation: 1592

Like
0Likes
Like

Posted 25 April 2014 - 10:53 AM

Valid question, duckflock. In this case I could probably do it the brute force way (which is actually not that different from the code fastcall22 posted, I need to test that, thanks man!), but this is not the first time I have come across this problem and sometimes the conditions haven't been so forgiving. That's why I was wondering if there is some defacto way to do this, even for complicated cases.

 

Any set difference implementation that relies on sorted lists is probably going to look something like that.  Any set difference implementation that doesn't rely on sorted lists is probably going to be slower, standard library or otherwise.

 

Standard library functions tend to be very fast for their given constraints, but if you have stronger constraints (like a sorted list in this case), it's not hard to beat them.



#11 Pink Horror   Members   -  Reputation: 1285

Like
0Likes
Like

Posted 25 April 2014 - 05:24 PM

Valid question, duckflock. In this case I could probably do it the brute force way (which is actually not that different from the code fastcall22 posted, I need to test that, thanks man!), but this is not the first time I have come across this problem and sometimes the conditions haven't been so forgiving. That's why I was wondering if there is some defacto way to do this, even for complicated cases.


There's a pretty big difference in complexity between a brute force method and what fastcall22 posted. Maybe the code is somewhat similar, but that's all the more reason to not use the brute force method, because you're not saving yourself much programming time by going that way. You might as well implement it the proper way.

#12 alnite   Crossbones+   -  Reputation: 2180

Like
-1Likes
Like

Posted 25 April 2014 - 05:35 PM

edit: ok. apparently I misread the question.

 

std::vector<T> difference(const std::vector<T>& A, const std::vector<T>& B) {
  std::vector<T> result(std::max(A.size(), B.size());
  for (auto &e : A) {
    if (std::find(B.begin(), B.end(), e) == B.end()) {
      result.push_back(e);
    }   
  }
  return result;
}
 
difference(A, B); // A - B
difference(B, A); // B - A

 

Possible optimizations:

  • Sorted A and B can use binary search.
  • Only perform this operation when A/B change.  If you can identify a part in your code where A and B change, you can minimize the recalculation.

Edited by alnite, 26 April 2014 - 05:28 PM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS