473,574 Members | 3,134 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comparing Two Lists for common elements

JoeMac3313
16 New Member
My Assignment was to compare two lists and print out the number of elments that are same.

It is supposed to look like this

Week 7 Homework
The number of common elements is: 3
The number of common elements is: 3

I get

Week 7 Homework
The number of common elements is: 0
The number of common elements is: 1

Which is better than my many other attempts, if you could offer any help I would appreciate it.

JoeMac3313


Expand|Select|Wrap|Line Numbers
  1. import ch06.lists.*;
  2.  
  3. public class CompareListsTest
  4. {
  5.  
  6.    private static int compareUnsortedLists(UnsortedListInterface list1, UnsortedListInterface list2) {
  7.  
  8.     int counter = 0;
  9.  
  10.         list1.reset();
  11.         list2.reset();
  12.  
  13.         if(list2.contains(list1.getNext())&& list1.getNext() != null)
  14.         {    
  15.             counter++;
  16.         }
  17.  
  18.     return counter;
  19.  
  20.    }
  21.  
  22.  
  23.    public static void main(String[] args) {
  24.  
  25.       // declare and populate list lst1
  26.       UnsortedListInterface lst1 = new RefUnsortedList();
  27.     lst1.add("alpha");
  28.     lst1.add("tau");
  29.     lst1.add("beta");
  30.     lst1.add("kappa");
  31.     lst1.add("gamma");
  32.     lst1.add("delta");
  33.  
  34.      // declare and populate list lst2
  35.      UnsortedListInterface lst2 = new RefUnsortedList();
  36.         lst2.add("tim");
  37.         lst2.add("gamma");        
  38.         lst2.add("beta");
  39.         lst2.add("peter");
  40.         lst2.add("kappa");
  41.  
  42.      // Self introduction
  43.      System.out.println("Week 7 Homework");
  44.  
  45.      // Call compareUnsortedLists
  46.      System.out.println("The number of common elements is: " + compareUnsortedLists(lst1, lst2));
  47.  
  48.      // The property should be symetric and therefore the same result should be
  49.      // obtained if the parameters are swapped in the method call
  50.      System.out.println("The number of common elements is: " + compareUnsortedLists(lst2, lst1));
  51.  
  52.   }
  53.  
  54. }
  55.  
  56.  
  57.  
  58.  
Jul 14 '07 #1
3 34593
JosAH
11,448 Recognized Expert MVP
If your lists contain n and m elements respectively you have to perform n*m
comparisons. If the elements nicely implement the equals() and hashCode()
methods you can the lists figure out the presence of an element. It would clean
up your code enormously:

Expand|Select|Wrap|Line Numbers
  1. List<YourType> listA= ...
  2. List<YourType> listB= ...
  3. int common= 0;
  4. for (YourType element: listA) 
  5.    if (listB.contains(element))
  6.       common++;
  7.  
kind regards,

Jos
Jul 14 '07 #2
JoeMac3313
16 New Member
I fixed it w/ this code. Thanks for the help!

Expand|Select|Wrap|Line Numbers
  1.  
  2. int counter = 0;
  3. int count = 0;
  4.  
  5.     list1.reset();
  6.  
  7.     while(counter < list1.size())
  8.     {
  9.         if(list2.contains(list1.getNext()))
  10.         {
  11.             count++;
  12.         }
  13.  
  14.         counter++;
  15.     }
  16.  
Jul 14 '07 #3
JosAH
11,448 Recognized Expert MVP
I fixed it w/ this code. Thanks for the help!
Good; you're welcome and best of luck with your Java projects.

kind regards,

Jos
Jul 14 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

29
3037
by: Joseph Haig | last post by:
I am trying to use descriptive lists, <DL>, as shown in <http://www.maths.man.ac.uk/~jhaig/tmp/test.html> with a style sheet at <http://www.maths.man.ac.uk/~jhaig/tmp/default-2.css>. With Mozilla and Opera they appear correctly, with a border round both the <DT> and <DD> parts but in Internet Explorer the borders are messed up. Can anyone...
9
3740
by: Dave H | last post by:
Hello, I have a query regarding definition lists. Is it good practice semantically to use the dt and dd elements to mark up questions and answers in a frequently asked questions list, or FAQ? Here is an example of just such a usage: <dl class="faq"> <di>
41
3926
by: Odd-R. | last post by:
I have to lists, A and B, that may, or may not be equal. If they are not identical, I want the output to be three new lists, X,Y and Z where X has all the elements that are in A, but not in B, and Y contains all the elements that are B but not in A. Z will then have the elements that are in both A and B. One way of doing this is of course...
1
1559
by: Grzegorz ¦lusarek | last post by:
Hi all. I my application i have situation when i have some lists and i must get from lists common elements. Exacly i don't know how many list I have so at the moment of creation each of one I append them to one list. So I get list wchich consist of lists of objects. And now i want to get common objects of this list. How to do it? Grzegorz
1
1455
by: Nishant | last post by:
Hi there, I am looking forward to your help for comparing matrix in C++ I want to find common elements between 2 or more different matrices,using C++ for eg: A=
11
10357
by: Sheldon | last post by:
Hi, I have two arrays that are identical and contain 1s and zeros. Only the ones are valid and I need to know where both arrays have ones in the same position. I thought logical_and would work but this example proves otherwise: >>> a = >>> b = >>> Numeric.logical_and(a==6,b==6) 0
12
4148
by: rshepard | last post by:
I'm a bit embarrassed to have to ask for help on this, but I'm not finding the solution in the docs I have here. Data are assembled for writing to a database table. A representative tuple looks like this: ('eco', "(u'Roads',)", 0.073969887301348305) Pysqlite doesn't like the format of the middle term: pysqlite2.dbapi2.InterfaceError:...
3
1656
by: Sean Dalton | last post by:
Hello, I have a two sets OLDLIST and REMOVE. I would like to remove every element in OLDLIST if it is also occuring in REMOVE and store the remaining elements from OLDLIST into NEWLIST. So far, I have read in both lists but I'm struggling comparing the elements
2
3267
by: antar2 | last post by:
Hello, I am a beginner in python. following program prints the second element in list of lists 4 for the first elements in list 4 that are common with the elements in list 5 list4 = ,,] list5 =
0
7764
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8110
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8273
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7862
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8138
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6514
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5336
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3794
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2277
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.