Night JonSnow King
Night JonSnow King

Reputation: 43

Array of n size in Java

This was asked in my interview:

To print duplicate values from an array.

I am storing all duplicate values in array b. Finally storing them in hash set and printing the hash set. Only reason I am storing them in hash set is because I only want unique value from the duplicates. Like if I have {1,2,2,1} in my array then it should only print {1,2}.

Below program works fine but I have allocated a fixed size for array b (size = 100 in below program) and I want that on run time its value should be updated with the number of duplicates found. For example: if I have 10 duplicate values in my array a then b then b should become 10.

I checked a lot before posting this question, also I think this could be done with ArrayList but I am not sure how to write for array b.

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

public class duplicate_values_hash {

    public static void main(String aa[])
    {   
        Integer a[] = {1, 2, 3, 1, 2, 4, 5, 1, 3, 8, 10, 11, 90, 8,12, 5, 4, 5, 8};
        Arrays.sort(a);

        Integer b[] = new Integer[100]; // How to update on runtime

        int len,i,j = 0;
        len = a.length;

        for(i = 1; i < len; i++)
        {
            if(a[i-1] == a[i])
            {   
                j = j + 1;  
                b[j] = a[i];
            }
        }

        List<Integer> list = Arrays.asList(b);
        HashSet hs = new HashSet();
        hs.addAll(list);
        System.out.println(hs);

    }
}

Upvotes: 0

Views: 987

Answers (4)

antak
antak

Reputation: 20859

for(i = 1; i < len; i++)
{
    if(a[i-1] == a[i])
    {   
        j = j + 1;  
        b[j] = a[i];
    }
}

You could do something like this, and it'll probably work given proper logic, but this would be minus points if I were looking for a suitable Java programmer (and not a graduate programmer), because this fails to understand Java.

To find duplicate entries, I'd expect something more like this:

int nums[] = {1, 2, 3, 1, 2, 4, 5, 1, 3, 8, 10, 11, 90, 8,12, 5, 4, 5, 8};

Set<Integer> uniqueNums = new HashSet<>();
for (int num : nums) {
    if (!uniqueNums.add(num)) {
        System.out.println(num);
    }
}

How this works

Set<E> is a data structure that only stores unique elements. As such, if you try adding a value that's already in the set, Set.add(E) will return false.

The above loop goes through the numbers and tries to add each to the set. Any number which uniqueNums.add(num) returns false are those that were already in the set, hence duplicates.

Resulting output

The above code prints this.

1
2
1
3
8
5
4
5
8

1, 5, 8 are printed twice because they were duplicated twice. (i.e. Each had three in total.)

Now, what to do if you don't want to see duplicates of your duplicates? Answer: Use another Set<E>!

Upvotes: 0

chengpohi
chengpohi

Reputation: 14227

Dynamically allocate by the array a size:

public static void main(String aa[]) {
    Integer a[] = {
        1, 2, 3, 1, 2, 4, 5, 1, 3, 8, 10, 11, 90, 8, 12, 5, 4, 5, 8
    };
    Arrays.sort(a);

    Integer b[] = new Integer[a.length]; // How to update on runtime

    int len, i, j = 0;
    len = a.length;

    for (i = 1; i < len; i++) {
        if (a[i - 1] == a[i]) {
            b[j++] = a[i];
        }
    }

    List<Integer> list = new ArrayList<Integer>(Arrays.asList(b));
    list.removeAll(Collections.singleton(null));
    HashSet hs = new HashSet();
    hs.addAll(list);
    System.out.println(hs);

}

Upvotes: 1

Ashley Frieze
Ashley Frieze

Reputation: 5458

What's this question really about? Dynamically sizing an array? Don't. Or use ArrayList, as it will resize.

Is it about finding how many duplicates in an array?

Set<Integer> set = new HashSet<>();
for(int nextInt:myArrayOfPossibleDuplicates) {
    set.add(nextInt);
}
for(int nextInt:set) {
    System.out.println(nextInt);
}
System.out.println("There were " + myArrayOfPossibleDuplicates.length - set.size() + " additional items through duplication");

Or are you trying to work how many duplicates for each item? Do this with a map.

Map<Integer, Integer> howManyOfEach = new HashMap<>();
for(int nextInt:myArrayOfPossibleDuplicates) {
    if (!howManyOfEach.containsKey(nextInt)) {
       howManyOfEach.put(nextInt, 1);
    } else {
       howManyOfEach.put(nextInt, howManyOfEach.get(nextInt) + 1);
    }
}
for(Entry<Integer,Integer> item:howManyOfEach.entrySet()) { 
    System.out.println("Number " + item.key() + " -> " + item.value() + " time(s)");
}

Seems a bit pointless now your interview is over.

Upvotes: 0

Saeid
Saeid

Reputation: 4265

I think this code does the samething

public static void main(String aa[])
{   
    Integer a[] = {1, 2, 3, 1, 2, 4, 5, 1, 3, 8, 10, 11, 90, 8,12, 5, 4, 5, 8};

    int len = a.length;
    HashSet hs = new HashSet();
    for(int i = 0; i < len; i++)
    {
        hs.add(a[i]);
    }

    System.out.println(hs);

}

Upvotes: 0

Related Questions