Skip to content
Advertisement

frequency of each element in array

I tried to delete the duplicate value and print the count of each element. But I didn’t get the correct answer. How to delete only the duplicate value and print the count? Here is my code

public class RemoveArray {

    public static int[] delete(int[] arr, int x) {
        int[] sarr = new int[arr.length - 1];
        int j = x;

        for (int i = 0, k = 0; i < arr.length; i++) {
            if (i != j) {
                sarr[k] = arr[i];
                k++;

            }
        }

        return sarr;
    }

    public static void main(String... args) {
        int[] arr = { 1, 2, 8, 3, 2, 2, 2, 1 };

        for (int i = 0; i < arr.length; i++) {
            int count = 1;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    int x = j;
                    count++;
                    arr = delete(arr, x);
                }
            }

            System.out.println(count);
        }
    }

}

I need output as

2
4
1
1

Advertisement

Answer

The problem is that you are removing an element and not updating j accoridngly.

To fix your code, try this:

import java.util.Arrays;

public class removearray {

    static int[] delete(int arr[], int x) {
        int sarr[] = new int[arr.length - 1];
        int j = x;
        for (int i = 0, k = 0; i < arr.length; i++) {
            if (i != j) {
                sarr[k] = arr[i];
                k++;

            }
        }
        return sarr;
    }

    public static void main(String[] args) {
        int arr[] = new int[] { 1, 2, 8, 3, 2, 2, 2, 1 };
        for (int i = 0; i < arr.length; i++) {
            int count = 1;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    int x = j;
                    count = count + 1;
                    arr = delete(arr, x);
                    j--;
                }
            }

            System.out.println(count);
        }
    }
}

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement