-4

Given an array of four Points produce a new array/vector/arraylist (whatever is easier) with the same Points but if there are Points with duplicate X values, only save the Point which has the highest Y value.

For example:

If given (3, 2), (3, 1), (1, 2), (1, 1) this method should output only (3, 2) and (1, 2).

If given (3, 2), (3, 3), (3, 4), (3, 5) this method should output only (3, 5).

Any ideas on how I should proceed with this? My solutions keep running into a ConcurrentModificationException.

(for each point a in array) {
    (for each point b in newArray) {
        (if a and b have the same x and a has a greater y) {
            remove a 
            add b
        } else {
            add b
    }
}
Giga Tocka
  • 191
  • 3
  • 3
  • 11
  • 2
    Show your solution, please. You get that error if you are changing the list/array concurrently.. You cannot modify it while looping it. To solve the problem save the new points in a new array instead of trying to modify the given one. – Sully Jan 01 '14 at 08:40
  • I editted my post with some pseudocode. – Giga Tocka Jan 01 '14 at 08:48
  • possible duplicate of [Collection Alternative - ConcurrentModificationException](http://stackoverflow.com/questions/911462/collection-alternative-concurrentmodificationexception) – Robin Green Jan 01 '14 at 15:23

4 Answers4

1

Simple HashMap<Integer,Integer> will work. Just check with ContainsKey() and compare values, conditionally add or don't add.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

If your code is in multi Threaded environment then use

ConcurrentHashMap<Integer, Integer>

and traverse each element and compare element and place the highest element in the Map

Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
0
put the first point in result list
for each of the other three:
    if last X in result list not equal to this X:
        append point
    else if last Y < this Y:
        replace last point
return result list

I'll leave the javafication to you

norlesh
  • 1,749
  • 11
  • 23
0

By javadocs, may be you are doing something like, modify a Collection and iterating over it at the same time by another thread.

Cause of ConcurrentModificationException

Ashish
  • 735
  • 1
  • 6
  • 15