Efficient compare among vector elements

Hi guys,
I've a basic question, I've solved it with lots of nester for and I'm sure it's not the best way to do it, so I hope you can help me.
I've a vector of object User, so Vector<User> and user object has a property age.
What I want is simply:
1) iterating this vector and make comparing of age field for each user with each user (for example, 3 user, user1 - user2, user2 -user3,user3-user1).
2) User older for each compare must be entered in a new vector.
So starting from a vector of n element I should have a new vector with dimension equal to n*(n-1)/2.
Could someone help me to find most efficient code? (please show some code example)
Thanks,
Regards

new_to_java123 wrote:
What I want is simply:
1) iterating this vector and make comparing of age field for each user with each user (for example, 3 user, user1 - user2, user2 -user3,user3-user1).
2) User older for each compare must be entered in a new vector.
So starting from a vector of n element I should have a new vector with dimension equal to n*(n-1)/2.Well what you want is simply a very inefficient way to solve the problem. As you describe it you will use an algorithm of complexity O(n**2), while it can be done in O(n)!
What you should do:
1) Parse the vector once and determine the minAge and maxAge
2) Create an array[min-age, max-age] which contains a list of users for each index. As this is not directly supported in Java, use an ArrayList of size (maxAge - minAge ++1) and populate it with an empty List for each index 0 .. maxAge - minAge. Each entry with index i in that ArrayList is a List of persons whose age is (i ++ minAge).
3) Now iterate over the original Vector and append each user to the List of persons of his age (in code: ageList.get(user.getAge() - minAge()).add(user); )
Voilá. Only two scans of the original Vector and you have a structure that holds
1) List of the users of a given age (ageList.get(age - minAge()).
2) All users older than the given age can be found by iterating the lists with greater index as (age - minAge()).
And of course the memory requirements are much lower also!
It needs to store only maxAge - minAge + 1 plus the outer ageList. if you store null instead of an empty list if no user has a specific age this can be further reduced at the cost of havein to do more null checks.

Similar Messages

  • Performance issues comparing two vectors

    I need some advice on what is the fastest way to compare two vectors. My question is all about performance;
    I have two vectors one(Vect A) of which has more than 20000 string values and the other Vector B would hold typically around 200 strings.I compare them both to find out if Vector B has values in Vector A and remove those.
    I iterate thro each element in a loop from the smaller to the bigger vector comparing element by element.But it takes a long time.
    Is there any quick way to do this comparison and can I use contains/compare methods instead of iterating thro the vectors.will it speeden up things
    Arn

    first of all, you should probably examine your collection choice and make sure that java.util.Vector is your best option (assumming you can change the class). Do not use a Hashtable as the previous poster suggested- it doesn't sound like you have a key/value type relationship in your elements, making a Map implementation superflous. Will there be duplicate elements in either Collection? If you will not have duplicate elements, you should probably use a Set collection instead of a List. Does your collection have to be thread-safe? If not, one of the unsynchronized collections should give you better performance (e.g. ArrayList should be quicker then Vector). For the best possible performance, you could use an ordered collection and write your own comparator, so that it does not iterate beyond what ever element assurres that there is no match (i.e. if the first element is "fred" in an ordered collection, you know there will be no match for "adam"). Sun has some good tutorials on the java.util.Collection package that will help you understand the benefit of each implemenation...
    although, and I suppose this is neither here nor there, I wouldn't use java objects to sort through 20K string items- sounds like storing them in a database might be superior. Take care.

  • Copy vector elements to array

    if i create a vector called aList,
    and it had 2 elements "peter" and "june"
    and i create a new array >>String[] name = new String[5];
    how to use this method
    copyInto(Object[] anArray)
    Copies the components of this vector into the specified array.
    to copy the 2 elements in aList vector to my name[1]?

    if i create a vector called aList,
    and it had 2 elements "peter" and "june"
    and i create a new array >>String[] name = new
    String[5];
    how to use this method
    copyInto(Object[] anArray)
    Copies the components of this vector into
    ctor into the specified array.
    to copy the 2 elements in aList vector to my name[1]?A confusing question: you want to put two Vector elements into one array element? Can't put ten pounds of @%^@%^@^ in a five pound bag, can you?
    If you really want two Vector elements to be stored in one array element you'll have to combine them in some way. String concatenation will do.
    If you mean you'd like to copy all the Vector elements into the array, you'll have to do something like this:
    Vector aList = new Vector();
    // add some elements to aList
    int numNames = aList.size();
    String [] names = new String[numNames];
    for (int i = 0; i < numNames; ++i)
       names[i] = (String)aList.get(i);MOD

  • Comparing to Photoshop Elements 4

    I'm new to digital photography editing, could someone please tell me how does Aperture compares to Photoshop Elements 4?
    How does Aperture's photo editing perform when comparing to Photoshop?

    I agree to a certain degree. Aperture's focus is to simply and streamline your photo processing. If you take a lot of pictures and want a way to quickly sort through them and make adjustments like exposure, saturation or tint, then Aperture is probably a great choice. However, if you're doing editing that involves layers and changing the background and such, you'll be much better off with Elements 4.
    Personally, I use Aperture WITH Elements (they can interface quite nicely - with Elements being your external editor for those pictures that you can fix with Aperture). Obviously, the price tag is a quite a bit different - Aperture retails for $300 while Elements retails for $100.

  • If I'm copying text and/or vector elements from Indesign to Photoshop how come their pixel sizes change even though I opened the same sized document and my indesign file is a web file?

    If I'm copying text and/or vector elements from Indesign to Photoshop how come their pixel sizes change even though I opened the same sized document and my indesign file is a web file?

    >my indesign file is a web file
    Pardon?
    Or do you mean that, when you created a new document, you choose Web as intent maybe?

  • Comparing two vectors of objects

    Hi,
    This is just a small example of what I am trying to do.
    Trying to just compare the objects of type FileInfo in the vectors, do I have to create a compareTo function or something to define what is equal when comparing the objects? Where would I create this and how would I implement it?
              Vector v1 = new Vector();
              Vector v2 = new Vector();
              v1.addElement(new FileInfo("blah", "name"));
              v1.addElement(new FileInfo("blah", "name"));
              System.out.println(v1.equals(v2));
    // Returns falseThanks

    Only way I have thought of is change the vector to an
    array and use Sort(Object, Compator)
    Seems the easiest way. It is wierd [weird] how Vectors don't
    have any functions that allow you to compare things.Vector DOES compare things. But, it uses "equals" on those objects. If you didn't write an "equals" method for FileInfo, it will only compare the REFERENCES of FileInfo objects, not the data within those objects. I assume you want to have your "equals" methods compare the two "blah"s and the two "name"s (using String.equals). Give it a shot. If your "equals" doesn't work, then post it and tell us what "doesn't work" about it.

  • Compare 2 ArrayList elements

    Hi,
    I want to compare 2 arraylist elements and set only the elemnts which doesnot match in either of the List.
    For example:-
    List<String> list1 = new ArrayList<String>();
              list1.add("Italy");
              list1.add("US");
              list1.add("England");
              list1.add("Australia");
              list1.add("China");
              List<String> list2 = new ArrayList<String>();
              list2.add("Italy");
              list2.add("US");
              list2.add("England");
              List<String> finalList = new ArrayList<String>();
    for (String country1 : list1) {
              for (String country2 : list2) {
              if (!country1.equalsIgnoreCase(country2)) {
                   finalList.add(country1);
    Here I am comparing both the arraylist elements, and in the FinalList I need capture the elements which are not matching , hence the final List should contains
    Australia and China which is not there in the second arraylist (list2). But the output that is displayed for tha above is wriong as it is comparing the each elemnt of list1 with all the elemnts of list2. Instead I want list1.elemnt[0] not equals list2.elemnt[0] followed by list1.element[1] not equal to list2.element[1] , etc.
    So that i can capture the elements which doesnot match and set it in the finalList. Here the output should be Australia & China. How we can do the above.
    Please clarify.
    Thanks.

    The test is wrong.
    List<String> list1 = new ArrayList<String>();
    list1.add("Italy");
    list1.add("US");
    list1.add("England");
    list1.add("Australia");
    list1.add("China");
    List<String> list2 = new ArrayList<String>();
    list2.add("Italy");
    list2.add("US");
    list2.add("England");
    List<String> finalList = new ArrayList<String>();
    for (String s1 : list1) {
         boolean found = false;
         for (String s2 : list2) {
              if ((s1!=null && s1.equalsIgnoreCase(s2)) || s1==s2) {
                   found = true;
                   break;
         if (!found) finalList.add(s1);
    }or you can generalize the idea and do this:
    static <T> List<T> cmp(List<T> list1, List<T> list2, Comparator<T> comparator) {
         List<T> finalList = new ArrayList<T>();
         for (T s1 : list1) {
              boolean found = false;
              for (T s2 : list2) {
                   if (comparator.compare(s1, s2)==0) {
                        found = true;
                        break;
              if (!found) finalList.add(s1);
         return finalList;
    static final Comparator<String> stringComparator = new Comparator<String>() {
        @Override public int compare(String o1, String o2) { return o1!=null ? o1.compareToIgnoreCase(o2) : o1==o2 ? 0 : -1; }
    static List<String> cmp(List<String> list1, List<String> list2) { return cmp(list1, list2, stringComparator); }
    static void test() {
         List<String> list1 = new ArrayList<String>();
         list1.add("Italy");
         list1.add("US");
         list1.add("England");
         list1.add("Australia");
         list1.add("China");
         List<String> list2 = new ArrayList<String>();
         list2.add("Italy");
         list2.add("US");
         list2.add("England");
         List<String> finalList = cmp(list1, list2);
         for (String s : finalList) System.out.println(s);
    }Carlo

  • Something changed on my file and now my vector elements and fonts look pixelated in CS6

    Today an illustrator file with vector objects and fonts that I've been working on for days looked pixelated when enlarging at more than 400%. I couldn't find the fix so I started a new canvas, selected everything from my pixelated file, pasted it into a new canvas and everything transferred correctly so I was able to continue working with my vector elements again.  I was curious if anyone knows what made my vector elements change to pixels and how to fix it.  Thanks guys

    You are welcome Miss Modular.
    Even on web jobs people do not use that option too often, so really wish they would not assign a keyboard command to that, which is what I suspect happened to you.

  • I can't export vector elements with pdf

    Good morning,
    I have a problem.
    When I import a vector element from illustrator to photoshop with drag, from an application to other, my
    results is a vector element in photoshop (vector smart object).
    If I export in PDF (save as photoshop PDF) my results isn't a vector elements, the text and shape wrote in psd
    yes but the smart object no.
    Anyone have any suggestions?
    thank you very much.
    Nayaril

    There are a lot of features I would like to request, how about being able to rename a duplicate project.  Anyway, thanks for the answer.  I still can't send even a full project into compressor using the send to compressor button.  I did find I can use the export using compressor settings, then using the advanced menu I get a send to compressor button that does actually send my project to compressor.  I can then select an in and out point and render a small sellection from my timeline. 

  • Compare the cost element of each internal order

    Hello All,
    How can we compare the cost element of each internal order?
    let me know how can we maintain the budget for each cost element for each internal order.  so that along the year, we can compare budget and actual for controlling purpose.
    Thanks
    Naveen

    Hi,
    I guess you mean comparing plan value by cost element for different IOs.
    If you want to compare those (same as actual), you could put internal orders, ranges or groups into the respecitve columns. I also did this once I think for car costs, where the manager wanted to see 10 cars next to each other and compare them (in this case it was actual figures, but same is possible with plan values).
    You just need to unselect IO on general data selection and use this as characteristic in the columns then.
    hope this helps?
    regards
    Bjoern

  • Why does a excel pie chart fail to import as vector elements?

    Hello. I' m importing Excel 2008 excel pie charts to illustrator CS5. I am cutting and pasting content between the applications to import. When importing a pie chart - the chart imports OK, but the pie elements import as low resiolution non-vector elements. Is there a way to import as 100% vector elements? Note - all other chart types - bar graphs etc import fine!. thanks AH

    Hi Mylenium - thanks for your reply. I found this thread: http://forums.adobe.com/thread/732518. Looks like 'low budget dave' identited an 'excel' problem with conversion of pie charts to bitmap - thread was in 2010 - am hoping for more recent info or a solution. thanks.

  • Arch compared to Vector

    I'm quite newbie for Linux, but not afraid for commandline. It's the way to learn how things works, isn't it? Is that good enough to try Arch? I'll see.
    I've had it with Windows and like to get a working, good performing and stable desktop with basic SOHO apps installed and VMware to experiment with other distros and oses without multibooting.
    So I need a no nonsense, light weighted OS on top wich is compatible with al my hardware, and is capable to run VMware and.. eh... there was some very good performing whats-it-called program to run any other Linux.  So I can use windows in a virtual machine as long as I need it.
    Arch and Vector are both famous for speed.
    So...how is Arch compared to Vector on speed, compatibilty, stabilty?
    And since my computer is 24 hours a day online, security isn't unimportant.
    So.... are they... usable for my goal? If not.. does anyone have a better idea?

    I find Arch faster than Vector.  Vector is actually made for slower machines, while Arch is designed for PIII or AMD-K7 and up.
    Vector is more oriented towards the newcomer, more graphic configuration tools and the like, while Arch is aimed towards people more used to editing text configuration files.
    Security, well, both enable you to use iptables, which is how I usually secure a machine.   There are various other firewall implementations out there, which should work on either distribution.
    Vector makes it a ~bit~ (in my opinion, and this could just be because I haven't used it that much and didn't do that much research) harder to get under the hood, so to speak, and edit the various configuration files.
    Both are nice distributions, with different target audiences.  I think you'll learn more about Linux using Arch, but that could be my opinion. Vector is based on Slackware, which is sort of the classic vanilla Linux.
    On a 686 (PIII or K7 and up) I think you'll find Arch to be faster.

  • Comparing Vector Elements

    I am trying to compare the elements in two Vectors. The vectors may be of unequal size and are not sorted in any order. I need to determine the values of elements that exist in both Vectors and add them to a third. To do this I am starting a for loop that will take each element of the first vector and, using a second for loop that takes each element of the second Vector, compare them with an if statement. If they are equal, the value from the first Vector is added to the new Vector.
    The problem is that although I have two values in each Vector that I know are equal, nothing gets added to the new Vector.
    The code is:
    //=====================================================
    for (int j =0 ; j < v1.size();j++){ //Loop for each element in Vector v1
    for (int k = 0; k < v2.size(); k++){//Loop for each element in Vector v2
    if (v1.get(j)== v2.get(k)){
    System.out.println(v1.get(j));
    System.out.println(v2.get(k));
    vres.add(v1.get(j).toString());}//Add elements that match to Vector vres
    Any help is appreciated

    Hi,
    by using the == operator your doing a memory location comparison, which will only be true if the same instance of an object is added to v1 and v2. If two different instances of a perticular object are the same then use .equals
    For example
    Integer one = new Integer(1);
    Integer onep = new Integer(1);
    if (one == onep )
       // not the same
    if (one.equals(onep))
       // the same
    }I hope this addresses your problem,
    Carlo

  • Compare newly added Vector Element with all previous

    Hi all
    I am adding Point2D elements to a vector "Numbers" in such a way that every newly randomly created element that is at a distance of 0.3 from all the previous points is added else not.
    I have written a code that only checks from the last element but not all the previous elements.
    Can someone check what wrong am I doing.
    The code is runnable.
    import java.awt.geom.Point2D;
    import java.util.*;
    public class Distance
         Vector<Point2D> numbers = new Vector<Point2D>();
         Random rnd = new Random();
         void getList()
         double xCoord,yCoord;
         for(int i=0;i<5;i++)// is is the no. of coordinates stored later only "b" to be used
         xCoord = rnd.nextDouble();          // X-coord of AP
         yCoord = rnd.nextDouble();          // Y coord of AP
         if(i<2)
              numbers.addElement(new Point2D.Double(xCoord,yCoord));
              System.out.println("0th n 1st element added : "+i+ "   "+numbers.get(i));
         else
         for(int j=i-1;j>i-2;j--)
              if((numbers.get(j).distance(xCoord,yCoord))>0.3)
                   numbers.addElement(new Point2D.Double(xCoord,yCoord));
                   System.out.println("next element added : "+i+ "   "+numbers.get(j)+"  with distance: "
                             +(numbers.get(j).distance(xCoord,yCoord))+"from "+ xCoord + " "+ yCoord);
         Iterator it = numbers.iterator ();
           while (it.hasNext ())
            System.out.println(it.next());
         public static void main(String[] argv)
              Distance d = new Distance();
              d.getList();
    }Thanks a lot

    Hi all
    I am adding Point2D elements to a vector "Numbers" in such a way that every newly randomly created element that is at a distance of 0.3 from all the previous points is added else not.
    I have written a code that only checks from the last element but not all the previous elements.
    Can someone check what wrong am I doing.
    The code is runnable.
    import java.awt.geom.Point2D;
    import java.util.*;
    public class Distance
         Vector<Point2D> numbers = new Vector<Point2D>();
         Random rnd = new Random();
         void getList()
         double xCoord,yCoord;
         for(int i=0;i<5;i++)// is is the no. of coordinates stored later only "b" to be used
         xCoord = rnd.nextDouble();          // X-coord of AP
         yCoord = rnd.nextDouble();          // Y coord of AP
         if(i<2)
              numbers.addElement(new Point2D.Double(xCoord,yCoord));
              System.out.println("0th n 1st element added : "+i+ "   "+numbers.get(i));
         else
         for(int j=i-1;j>i-2;j--)
              if((numbers.get(j).distance(xCoord,yCoord))>0.3)
                   numbers.addElement(new Point2D.Double(xCoord,yCoord));
                   System.out.println("next element added : "+i+ "   "+numbers.get(j)+"  with distance: "
                             +(numbers.get(j).distance(xCoord,yCoord))+"from "+ xCoord + " "+ yCoord);
         Iterator it = numbers.iterator ();
           while (it.hasNext ())
            System.out.println(it.next());
         public static void main(String[] argv)
              Distance d = new Distance();
              d.getList();
    }Thanks a lot

  • Iteration on vector elements.

    hi
    i want to call a method for each element in the vector.
    as its inefficient to use iteration on array or vector as it demands for length check redundantly. so could you please give an example that is efficient.

    It's not inefficient. The Vector object stores its length in a field - it doesn't calculate its length every time an element is retrieved.
    Within the iterator, hasNext() simply compares the current index to the size of the Vector - so again, the length isn't recalculated every time.

Maybe you are looking for

  • Profit Center Derivation in GR and Invoice documetns form MM component

    Hi All, My clien wants to set a profit center(B/S)999999 for only GR/IR clearing account (not on expense line item) on Goods receipt and invoice documents. At present it is getting derived from cost object assgined to the purchase order. I tried usin

  • How do I use my iPad to veiw video on Apple TV?

    How do I use my iPad to view video on my Apple TV?

  • PO distribution amount

    Hi, Is there any table from where I can get PO distribution amount? I checked table po_distributions_all where there were two columns 'amount_billed' and 'encumbered_amount'. I don't know which one to refer. Also can anyone tell correspondance betwee

  • UCCX8.5 HA node 1 not master

    Hi, We are running UCCX8.5 in our dev lab (NFR kit) in HA (LAN) setup, when I reboot both servers node 1 is master (check by http://node1server/uccx/isDBMaster) but after a while (hour or so) suddenly node 2 is master. When I run CAD, I can login, go

  • I can't hook my ENVY 5530 printer to my Chromebook? Can you help me?

    I cannot hook up my ENVY 5530 all-in-one printer to my HP Chromebook.  Can anyone help me?  I can't even download the installation software onto my Chromebook.  Thanks.