• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
GuyWithBeard

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

11 posts in this topic

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!

0

Share this post


Link to post
Share on other sites

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

Edited by Ashaman73
0

Share this post


Link to post
Share on other sites
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
2

Share this post


Link to post
Share on other sites

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).

0

Share this post


Link to post
Share on other sites

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!

1

Share this post


Link to post
Share on other sites
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
2

Share this post


Link to post
Share on other sites

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.

2

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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.
0

Share this post


Link to post
Share on other sites

edit: ok. apparently I misread the question.

 

[source]

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

[/source]

 

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0