Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Say I have the following...

 

ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
ArrayList arr3 = new ArrayList();

arr1.AddRange(new int[] { 1,2,3,4,5,6,7,8,9 });
arr2.AddRange(new int[] { 2, 5, 7 });

 

I need to populate arr3 with values that are in both arr1 and arr2. I'm currently doing it with the following, does anyone know of a better way of achieving this?

 

for(int i = 0; i < arr1.Count; i++)
   if(arr2.Contains(arr1[i]))
       arr3.Add(arr1[i]);

 

Just to clarify arr3 should now contain 2, 5 and 7. As I've been typing this post I've realised that in this example arr1 is larger than arr2 so it would perhaps be prudent to loop through the smaller arr2 so I might add an if statement if nobody else can think of a better solution.

Anybody looking for a graduate programmer (Midlands, England)?
  • Leaders
Posted

Well, looks like you have a pretty good solution. If the arrays are going to be sorted, then you can also use BinarySearch and check for a positive result.

 

And the operation you are doing is a union. It is symmetric; you do not need to check anything from both array's point of view (i.e. if arr2 contains a point in arr1 and then again check if arr1 contains a point in arr2... if arr2 didn't check for it in arr1, then the point will continue to not-exist when arr1 checks for it).

Iceplug, USN

One of my coworkers thinks that I believe that drawing bullets is the most efficient way of drawing bullets. Whatever!!! :-(

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...