How to find duplicate elements in array using for each loop - java

I am trying to print duplicate elements in one d array using for each loop. But my output was an unexpected one. Could anyone please assist?
package Login;
public class DupsArray {
static int[] a = {1,2,3,3};
public static void main(String[] args) {
int length = a.length;
for(int i=0;i<=length-1;i++) {
for(int j : a) {
for(j=1;j<=length-1;j++) {
if(a[i]==(a[j]) ) {
System.out.println("Found duplicate");
} else {
System.out.println("No duplicates found");
}
}
}
}
}
The results show as follows:
The expected results to be print duplicate found.

Try using the below logic which compares every element with all other element in the array, if any duplicate is found,it stops the execution to continue futher
for(int i = 0; i < a.length;i++) {
for (int j = i + 1 ; j < a.length; j++) {
if (a[i] == a[j]) {
System.out.println("Found duplicate");
return;
}
}
}
System.out.println("No duplicate Found");

We can do something like this
Integer[] arr = {1, 2, 3, 3, 5, 5, 7, 8, 7};
Set<Integer> set = new HashSet<Integer>();
for (Integer i : arr) {
if (set.add(i) == false)
{
System.out.println(i);
}
}

try this and update as per your requirement
public class Main{
public static void main(String[] args) {
int[] ar = new int[] {1, 1, 3, 3, 4, 5, 7, 8};
int size = ar.length;
int error = 0;
for(int i = 0; i < size; i++){
for(int j = i+1; j < size; j++){
if(ar[i] == ar[j]){
if(i != j){
error = error + 1;
System.out.println("dulicate element " + j);
}
}
}
}
System.out.println("total number of duplicate element " + error);
}
}

You can use Sets like that :
Integer[] a = {1, 2, 3, 3, 5, 5, 7, 8, 7};
Set<Integer> duplicatesSet = new HashSet<>();
Set<Integer> helperSet = new HashSet<>();
for (Integer element : a) {
if (!helperSet.add(element)) { // NOTE*
System.out.println("Duplicate found : " + element);
duplicatesSet.add(element);
}
}
Then you can do whatever you like with the duplicates set
for(Integer el : duplicatesSet){
System.out.println(el);
}
Note*
According to javadocs :
boolean add(E e);
Adds the specified element to this set if it is not already present
return true if this set did not already contain the specified element
This way we can know if the element is already in the set, if it is we can add it to our duplicates.

Related

numOfColors recursive function JAVA

I trying to write recursive function in Java.
The function needs to count for me all the diffrents values in array.
i.e
{{1,1,1,1},{4,4,4,4},{3,3,1,1}}
The recursive function returns 3 (1,4,3)
This is the function that i need to write:
int numOfColors(int[][] map)
What I have been tried:
public static int numOfColors(int[][] arr) {
int i=0;
int j=0;
int colors=0;
int contains = arr[i][j];
if (arr== null) {
return 0;
} else if (arr[i][j] != 0&& arr[i][j]!=contains) {
colors ++;
}
return numOfColors(arr) + 1;
}
Exception in thread "main" java.lang.StackOverflowError
How can i fix it?
Thanks!
Below is one way of finding count of unique values using recursion and without using any Set or List -
package test;
public class Main {
public static void main(String[] args) {
int[][] arr = { { 4, 2, 2, 1, 4 }, { 4, 4, 3, 1, 4 }, { 1, 1, 4, 2, 1 }, { 1, 4, 0, 2, 2 }, { 4, 1, 4, 1, 1 } };
System.out.println(numOfColors(arr));
}
public static int numOfColors(int[][] arr) {
int unique = 0;
if (arr.length == 0) {
return unique;
} else {
int[] subArr = arr[arr.length - 1];
outerLoop: for (int i = 0; i < subArr.length; i++) {
int j = i + 1;
for (; j < subArr.length; j++) {
if (subArr[i] == subArr[j]) {
break;
}
}
if (j == subArr.length) {
int k = 0;
for (; k < arr.length - 1; k++) {
for (int l = 0; l < arr[k].length; l++) {
if (subArr[i] == arr[k][l]) {
continue outerLoop;
}
}
}
if (k == arr.length - 1) {
unique++;
}
}
}
int[][] dest = new int[arr.length - 1][];
System.arraycopy(arr, 0, dest, 0, arr.length - 1);
unique += numOfColors(dest);
return unique;
}
}
}
Output
5
Note that this problem can be solved without recursion easily. Also, above code can be make easy using Set
I think you should store unique values in Set and build final result base on it size. Here is one from many solutions:
package com.company;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
int[][] map = new int[][] {{1,1,1,1},{4,4,4,4},{3,3,1,1}};
System.out.println(numOfColors(map));
}
public static int numOfColors(int[][] map) {
HashSet<Integer> result = new HashSet<Integer>();
numOfColorsImpl(map, 0, result);
return result.size();
}
private static void numOfColorsImpl(int[][] map, int rowIndex, Set<Integer> result) {
if (rowIndex == map.length)
return;
for (int value : map[rowIndex]) {
result.add(value);
}
numOfColorsImpl(map, rowIndex + 1, result);
}
}
You could use a recursive helper function that removes duplicates.
import java.util.*;
public class Main {
public static void main(String[] strg) {
int[][] arr = {{1, 1, 1, 1}, {4, 4, 4, 4}, {3, 3, 1, 1}};
numOfColors(arr);
}
static int numOfColors(int[][] map) {
ArrayList<Integer> intlist = new ArrayList<Integer>();
for (int o = 0; o < map.length; o++) {
for (int n = 0; n < map[o].length; n++) {
intlist.add(map[o][n]);
}
}
intlist = removeDuplicates(intlist, 0);
System.out.println(intlist.size()+" " +intlist);
return intlist.size();
}
static ArrayList<Integer> removeDuplicates(ArrayList<Integer> list, int counter) {
if (list == null) {
throw new NullPointerException();
}
if (counter < list.size()) {
if (list.contains(list.get(counter))) {
if (list.lastIndexOf(list.get(counter)) != counter) {
list.remove(list.lastIndexOf(list.get(counter)));
counter--;
}
}
removeDuplicates(list, ++counter);
}
return list;
}
}
Output
3 [1, 4, 3]
Online demo
I don't think recursion is necessary in this case, so I will explain the way I would go about it. I will refer to arr as array A. First, you create a hash set of numbers that you have seen already, which we will call hash set B. Then, you can loop through array A, processing each element. Check if hash set B contains that element. If it does, continue, if not, add that value to hash set B. After the loop, return the length of hash set B, or the entire set if you want to see what the unique values are.
For example:
import java.util.HashSet;
public class Class {
public static void main(String[] args){
int[][] A = {{1, 1, 1, 1}, {4, 4, 4, 4}, {3, 3, 1, 1}};
System.out.println("Number of different values: " + countUniqueVals(A));
}
public static int countUniqueVals(int[][] A){
HashSet<Integer> B = new HashSet<Integer>();
for (int row = 0; row < A.length; row++)
for (int col = 0; col < A[row].length; col++)
B.add(A[row][col]);
return B.size();
}
}

Finding Duplicates in Array and printing them only Once

I am trying to loop through my array and find all the numbers that are repeating more than once:
E.G: if there is 1 1 2 3 4
It should print saying "1 repeats more than once"
Here is my code and so far what I have tried, however it prints all duplicates and keep going, if there is 4 4 4 4 3 6 5 6 9, it will print all the 4's but i dont want that:
class average {
public static void main(String[] args) throws IOException {
int numOfLines = 0;
int sum = 0, mean = 0, median = 0, lq = 0, uq = 0;
int[] buffer;
File myFile = new File("num.txt");
Scanner Scan = new Scanner(myFile);
while(Scan.hasNextLine()) {
Scan.nextLine();
numOfLines++;
}
Scan.close();
Scan = new Scanner(myFile);
System.out.println("Number Of Lines: " + numOfLines);
buffer = new int[numOfLines];
for(int i=0; i<numOfLines; i++) {
buffer[i] = Scan.nextInt();
}
Scan.close();
Scan = new Scanner(myFile);
for(int i=0; i<buffer.length; i++) {
sum = sum+i;
mean = sum/numOfLines;
}
System.out.println("Sum: " + sum);
System.out.println("Mean: " + mean);
for(int i=0; i<buffer.length; i++) {
for(int k=i+1; k<buffer.length; k++) {
if(buffer[k] == buffer[i]) {
System.out.println(buffer[k]);
}
}
}
Just add the number you will find duplicated to some structure like HashSet or HashMap so you can find it later when you will detect another duplication.
Set<Integer> printed = new HashSet<Integer>();
for(int i=0; i<buffer.length; i++) {
for(int k=i+1; k<buffer.length; k++) {
if(buffer[k] == buffer[i]) {
Integer intObj = new Integer(buffer[k]);
if (!printed.contains(intObj)) {
System.out.println(buffer[k]);
printed.add(intObj);
}
break;
}
}
}
Better O(n) alghorithm:
Set<Integer> printed = new HashSet<Integer>();
for(int i=0; i<buffer.length; i++) {
if (!printed.add(new Integer(buffer[i])) {
System.out.println(buffer[i]);
}
}
You perform the check for every single item of the array, including the first 4, the second 4 and so on. That's why it just doesn't stop and it prints the message multiple times per duplicated element.
You're saying you cannot use a Set and that you don't want to sort your data. My suggestion is that you loop over the array and add each duplicated item to a list. Make sure you check whether the item has already been added. (or use a Set :) )
Then loop over the list and print those items.
I would use a HashMap to store the value I encounter in the array, with the count as a value. So if you encounter a 4, you would look it up in the HashMap, if it doesn't exist, you would add it with a value of 1, otherwise increment the value returned.
You can the loop over the HashMap and get all the values and print the number of duplicates encountered in the array.
Integer[] ints = {1, 1, 2, 3, 4};
System.out.println(new HashSet<Integer>(Arrays.asList(ints)));
Output: [1, 2, 3, 4]
This problem is much simpler and likely faster to solve using a collection. However, as requested here's an answer that uses "just simple array[s]" and no sorting. I've tried not to change your code too much but I refuse to leak resources in the case of an exception.
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
class Average {
public static void main(String[] args) throws IOException {
int numOfLines = 0;
int sum = 0, mean = 0, median = 0, lq = 0, uq = 0;
int[] buffer;
int flag = -1;
File myFile = new File("num.txt");
try (Scanner Scan = new Scanner(myFile)) {
while(Scan.hasNextLine()) {
Scan.nextLine();
numOfLines++;
}
}
try (Scanner Scan = new Scanner(myFile)) {
System.out.println("Number Of Lines: " + numOfLines);
buffer = new int[numOfLines];
for(int i=0; i<numOfLines; i++) {
buffer[i] = Scan.nextInt();
}
}
for(int i=0; i<buffer.length; i++) {
sum = sum+i;
mean = sum/numOfLines;
}
System.out.println("Sum: " + sum);
System.out.println("Mean: " + mean);
//copy every duplicate
int[] dupesOnly = new int[numOfLines];
int dupesOnlyIndex = 0;
for(int i=0; i<buffer.length; i++) {
for(int k=i+1; k<buffer.length; k++) {
if(buffer[k] == buffer[i]) {
dupesOnly[dupesOnlyIndex++] = buffer[i];
//System.out.println(buffer[k]);
}
}
}
//mark all but first occurrence of dupe
boolean[] skip = new boolean[dupesOnlyIndex]; //Inits to false
for (int i = 0; i < dupesOnlyIndex; i++) {
for(int k=i+1; k<buffer.length; k++) {
if(dupesOnly[k] == dupesOnly[i]) {
skip[k] = true;
}
}
}
//skip elements marked as extra dupes
int[] dupesUnique = new int[dupesOnlyIndex];
int dupesUniqueIndex = 0;
for (int i = 0; i < dupesOnlyIndex; i++) {
if (skip[i] == false) {
dupesUnique[dupesUniqueIndex++] = dupesOnly[i];
}
}
//trim to size
int[] dupesReport = new int[dupesUniqueIndex];
for (int i = 0; i < dupesReport.length; i++) {
dupesReport[i] = dupesUnique[i];
}
System.out.println("Dupes: " + Arrays.toString(dupesReport));
}
}
Input file "num.txt" (numbers separated by newlines not commas):
1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3
Output:
Number Of Lines: 14
Sum: 91
Mean: 6
Dupes: [1, 2, 3, 7]
Using the apache commons CollectionUtils.getCardinalityMap(collection):
final Integer[] buffer = {1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3};
final List<Integer> list = Arrays.asList(buffer);
final Map<Integer, Integer> cardinalityMap = CollectionUtils.getCardinalityMap(list);
for (final Map.Entry<Integer, Integer> entry: cardinalityMap.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey());
}
}
toString() of cardinalityMap looks like this after the init:
{1=4, 2=2, 3=2, 4=1, 5=1, 6=1, 7=2, 9=1}
Using standard java:
final Integer[] buffer = {1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3};
final List<Integer> list = Arrays.asList(buffer);
final Set<Integer> set = new LinkedHashSet<Integer>(list);
for (final Integer element: set) {
if (Collections.frequency(list, element) > 1) {
System.out.println(element);
}
}

Count the no. of occurrence and display the most repeated first no. followed by others. for Eg. input: 223331544 output: 32415 [duplicate]

This question already has answers here:
Printing distinct integers in an array
(8 answers)
Closed 8 years ago.
A program in Java that should count the no. of occurrence and display the most repeated first no. followed by others. for eg. input: 223331544 output: 32415
class Example {
public static void main(String a[]) {
int[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
for (int i = 0; i < arr.length; i++) {
boolean isDistinct = false;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
isDistinct = true;
break;
}
}
if (!isDistinct) {
System.out.print(arr[i] + " ");
}
}
}
}
The following code will print out distinct numbers:
import java.util.*;
public class Example {
public static void main(String[] args) {
Integer[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));
System.out.println(s);
}
}
But this is not the answer. The requirement is to remove all the numbers that appear more than once. To do that, make a Map that containts the number as key and occurrence as value. While put the numbers into the Map, if the number is already exists, +1 the occurrence. So the code is like the following:
import java.util.*;
public class Test {
public static void main(String[] args) {
int[] arr = { 5, 2, 7, 2, 4, 7, 8, 2, 3 };
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
for (int i : arr) {
if (m.get(i) == null)
m.put(i, 1);
else
m.put(i, m.get(i) + 1);
}
for (Map.Entry<Integer, Integer> e : m.entrySet()) {
if (e.getValue() == 1)
System.out.print(e.getKey() + " ");
}
}
}
Try this solution for your problem.
import java.util.*;
class Hello
{
public static void main(String[] args)
{
int[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < arr.length; i++){
set.add(arr[i]);
}
//now if you will iterate through this set, it will contain only unique values.
Iterator it = set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
I thinkd Set already can help u do this, advanced Link.http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
You can try in this way
public static void main(String a[]) {
int[] arr = {1,2,2,3,4,5,5};
for (int i = 0; i < arr.length; i++) {
boolean isDistinct = false;
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j] && i!=j) {
isDistinct = true;
break;
}
}
if (!isDistinct) {
System.out.print(arr[i] + " ");
}
}
}
Out put:
1 3 4
Use set
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class NonDuplicateElement{
public static void main(String []args){
int[] arr = {5,2,7,2,4,7,8,2,3};
Set<Integer>set = new HashSet<Integer>();
Set<Integer>remset = new HashSet<Integer>();
for(int i=0;i<arr.length;i++)
{
if(set.contains(arr[i]))
{
remset.add(arr[i]);
}
else
{
set.add(arr[i]);
}
}
Iterator<Integer> iter = remset.iterator();
while(iter.hasNext())
{
Integer element = iter.next();
if(set.contains(element))
{
set.remove(element);
}
}
iter = set.iterator();
while(iter.hasNext())
{
System.out.println(iter.next()+ "\t");
}
}
}
Output : 3 4 5 8

How to find every occurrence of a target value in array and return a new array containing the indexes for these values? Java

I am working on a problem and am having a hard time getting it to output the right information.
What I am trying to do is find every occurrence of a target value and put it into a new array and output the indexes of the target values. If no target value is found it returns an empty array. outputs {}
Right now I am getting an error.
findAll():
[I#349b688e
[I#46ed5d9d
java.lang.ArrayIndexOutOfBoundsException
The outputs should be:
outputs {0, 5}
outputs {}
public class FindIndex(){
public FindIndex() {
int a[] = {7, 8, 9, 9, 8, 7};
System.out.println("findAll(): ");
System.out.println(findAll(a, 7));
System.out.print(findAll(a, 2));
}
public int[] findAll(int a[], int num) {
int indexNum = 0;
int arrSize = 0;
// find all occurrence of the target number
for(int i = 0; i < a.length; i++) {
if(a[i] == num) {
arrSize++;
}
}
// create new array
int newArray[] = new int[arrSize];
for(int i = 0; i < a.length; i++) {
if(a[i] == num) {
newArray[indexNum] = i;
}
}
return newArray;
}
public void print(int a[]) {
System.out.print("{");
int i;
for(i = 0; i < a.length - 1; i++) {
System.out.print(a[i] + ", ");
}
if(a.length > 0) {
System.out.print(a[i]);
}
System.out.print("}\n");
}
}
You are never incrementing indexNum, it always remains at 0 and the array keeps on writing the values at this same index.
I think you should have this expression there:
newArray[indexNum++] = i;
For your printing problem, what you're actually printing out ther are the addresses of the arrays returned, not the contents.
What you can do is the following:
System.out.println(Arrays.toString(findAll(a, 7)));
System.out.print(Arrays.toString(findAll(a, 2)));
This will give you the following output:
[5, 0]
[]
Calling findAll(a, 2) gets zero size newArray that's why you get ArrayIndexOutOfBoundsException.
You should check if (arrSize > 0) before doing array with indexes and access it.
I was working with the code and got it to work but it is giving me added zeros in the new array. The output of the top sould be 0, 5 How do I get ride of these added zeros?
int a[] = {7, 8, 9, 9, 8, 7};
int array2[];
// print the occurrence of a target index value
System.out.println("findAll(): ");
array2 = copy(findAll(a, 7));
array2 = copy(findAll(a, 2));
public int[] findAll(int a[], int target) {
int index;
int found = 0;
// find all occurrence of the target number
for(int i = 0; i < a.length; i++) {
if(a[i] == target) {
found = target;
i++;
}
}
// create new array
int newArray[] = new int[found];
for(int i = 0; i < newArray.length; i++) {
if(a[i] == target) {
newArray[i] = i;
i++;
}
}
return newArray;
}
public int[] copy(int newArray[]) {
System.out.print("{");
int i;
for(i = 0; i < newArray.length - 1; i++) {
if (newArray.length == 0) {
System.out.print( " " );
} else {
System.out.print(newArray[i] + ", ");
}
}
System.out.print("}\n");
return newArray;
}
output:
findAll():
{0, 0, 0, 0, 0, 5, }
{}

How to remove duplicates from a list using an auxiliary array in Java?

I am trying to remove duplicates from a list by creating a temporary array that stores the indices of where the duplicates are, and then copies off the original array into another temporary array while comparing the indices to the indices I have stored in my first temporary array.
public void removeDuplicates()
{
double tempa [] = new double [items.length];
int counter = 0;
for ( int i = 0; i< numItems ; i++)
{
for(int j = i + 1; j < numItems; j++)
{
if(items[i] ==items[j])
{
tempa[counter] = j;
counter++;
}
}
}
double tempb [] = new double [ items.length];
int counter2 = 0;
int j =0;
for(int i = 0; i < numItems; i++)
{
if(i != tempa[j])
{
tempb[counter2] = items[i];
counter2++;
}
else
{
j++;
}
}
items = tempb;
numItems = counter2;
}
and while the logic seems right, my compiler is giving me an arrayindexoutofbounds error at
tempa[counter] = j;
I don't understand how counter could grow to above the value of items.length, where is the logic flaw?
You are making things quite difficult for yourself. Let Java do the heavy lifting for you. For example LinkedHashSet gives you uniqueness and retains insertion order. It will also be more efficient than comparing every value with every other value.
double [] input = {1,2,3,3,4,4};
Set<Double> tmp = new LinkedHashSet<Double>();
for (Double each : input) {
tmp.add(each);
}
double [] output = new double[tmp.size()];
int i = 0;
for (Double each : tmp) {
output[i++] = each;
}
System.out.println(Arrays.toString(output));
Done for int arrays, but easily coud be converted to double.
1) If you do not care about initial array elements order:
private static int[] withoutDuplicates(int[] a) {
Arrays.sort(a);
int hi = a.length - 1;
int[] result = new int[a.length];
int j = 0;
for (int i = 0; i < hi; i++) {
if (a[i] == a[i+1]) {
continue;
}
result[j] = a[i];
j++;
}
result[j++] = a[hi];
return Arrays.copyOf(result, j);
}
2) if you care about initial array elements order:
private static int[] withoutDuplicates2(int[] a) {
HashSet<Integer> keys = new HashSet<Integer>();
int[] result = new int[a.length];
int j = 0;
for (int i = 0 ; i < a.length; i++) {
if (keys.add(a[i])) {
result[j] = a[i];
j++;
}
}
return Arrays.copyOf(result, j);
}
3) If you do not care about initial array elements order:
private static Object[] withoutDuplicates3(int[] a) {
HashSet<Integer> keys = new HashSet<Integer>();
for (int value : a) {
keys.add(value);
}
return keys.toArray();
}
Imagine this was your input data:
Index: 0, 1, 2, 3, 4, 5, 6, 7, 8
Value: 1, 2, 3, 3, 3, 3, 3, 3, 3
Then according to your algorithm, tempa would need to be:
Index: 0, 1, 2, 3, 4, 5, 6, 7, 8, ....Exception!!!
Value: 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 5, 6, 7, 8, 6, 7, 8, 7, 8, 8
Why do you have this problem? Because the first set of nested for loops does nothing to prevent you from trying to insert duplicates of the duplicate array indices!
What is the best solution?
Use a Set!
Sets guarantee that there are no duplicate entries in them. If you create a new Set and then add all of your array items to it, the Set will prune the duplicates. Then it is just a matter of going back from the Set to an array.
Alternatively, here is a very C-way of doing the same thing:
//duplicates will be a truth table indicating which indices are duplicates.
//initially all values are set to false
boolean duplicates[] = new boolean[items.length];
for ( int i = 0; i< numItems ; i++) {
if (!duplicates[i]) { //if i is not a known duplicate
for(int j = i + 1; j < numItems; j++) {
if(items[i] ==items[j]) {
duplicates[j] = true; //mark j as a known duplicate
}
}
}
}
I leave it to you to figure out how to finish.
import java.util.HashSet;
import sun.security.util.Length;
public class arrayduplication {
public static void main(String[] args) {
int arr[]={1,5,1,2,5,2,10};
TreeSet< Integer>set=new TreeSet<Integer>();
for(int i=0;i<arr.length;i++){
set.add(Integer.valueOf(arr[i]));
}
System.out.println(set);
}
}
You have already used num_items to bound your loop. Use that variable to set your array size for tempa also.
double tempa [] = new double [num_items];
Instead of doing it in array, you can simply use java.util.Set.
Here an example:
public static void main(String[] args)
{
Double[] values = new Double[]{ 1.0, 2.0, 2.0, 2.0, 3.0, 10.0, 10.0 };
Set<Double> singleValues = new HashSet<Double>();
for (Double value : values)
{
singleValues.add(value);
}
System.out.println("singleValues: "+singleValues);
// now convert it into double array
Double[] dValues = singleValues.toArray(new Double[]{});
}
Here's another alternative without the use of sets, only primitive types:
public static double [] removeDuplicates(double arr[]) {
double [] tempa = new double[arr.length];
int uniqueCount = 0;
for (int i=0;i<arr.length;i++) {
boolean unique = true;
for (int j=0;j<uniqueCount && unique;j++) {
if (arr[i] == tempa[j]) {
unique = false;
}
}
if (unique) {
tempa[uniqueCount++] = arr[i];
}
}
return Arrays.copyOf(tempa, uniqueCount);
}
It does require a temporary array of double objects on the way towards getting your actual result.
You can use a set for removing multiples.

Categories

Resources