I have an ArrayList<String>
that contains the following:
2#3#1#0
1#0#4#1
9#2#5#0
4#2#3#2
1#1#2#1
Output: 6 different numbers.
I'm trying to write an algorithm that removes duplicates of the highlighted numbers so I can then use a counter to see how many different numbers in total in all of those locations are.
I've tried many things including some of the following: [Java remove duplicates from array using loops][1], [Java - Removing duplicates in an ArrayList][2], the first option in [How to find duplicates in Java array?][3] and many more. I've spent at least 5-10h just trying to figure what I'm doing wrong, but I can not, so I've turned to you.
Most of the time the solutions I find online seem to work on simple stuff, but not in my case. In it, when I try to print the different characters, it always returns the wrong int
numbers.
I've also tried, also tried separating each line of numbers into a different int Array[]
and then comparing, but it just won't catch all the different values.
In another example where I had 5 different numbers in total, I kept getting "4 different" as a result, so I even tried long n = ArrayList.stream().distinct().count();
just to see if I was doing something wrong, but even this thing returned "4 different" numbers.
I know the easiest way is using Set
and Map
, but I don't want that. I'd like to have an algorithm.
EDIT:
One of the many things I've tried is the following:
for (int m = 0; m < (size-1); m++){
for (int j = m + 1; j < size; j++){
if (ArrayList.get(j).charAt(0) != ArrayList.get(m).charAt(0)){
continue;
}
current++;
ArrayList.remove(j).charAt(0);
j--;
size--;
}
}
With this one, I'd have to use another one for the ArrayList.get().charAt(4)
.
EDIT2:
I've found the following code [here][1], but how would it be implemented in this case?
public static <T> ArrayList<T> uniquefy(ArrayList<T> myList) {
ArrayList <T> uniqueArrayList = new ArrayList<T>();
for (int i = 0; i < myList.size(); i++){
if (!uniqueArrayList.contains(myList.get(i))){
uniqueArrayList.add(myList.get(i));
}
}
return uniqueArrayList;
}
EDIT3:
I've found a possible solution, but it gives me an IndexOutOfBoundsException.
I've put the numbers 2, 1, 9, 4, 1 into Array1
and 1, 4, 5, 3, 2 into Array2
, but when I try to compare them, I get the mentioned error.
boolean stopSequence = false;
for (int i = 0; i < Array1.length; i++){
for (int a = 0; a < Array2.length && !stopSequence;){
if (Array1[i] != Array2[a]){
Array1[i] = 0;
a++;
}
if (Array1[i] == Array2[a]){
Array1[i] = 0;
stopSequence = true;
}
}
stopSequence = false;
}
[1]: https://stackoverflow.com/questions/26998156/java-remove-duplicates-from-array-using-loops
[2]: https://stackoverflow.com/questions/2435156/java-removing-duplicates-in-an-arraylist
[3]: http://javarevisited.blogspot.com.es/2015/06/3-ways-to-find-duplicate-elements-in-array-java.html
[4]: https://stackoverflo
w.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist?rq=1