My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Remove the occurrences of an element from array if it occurs more than n times.

THE GEEQ's photo
THE GEEQ
·Jan 15, 2018

For Example :-

{ 20, 37, 20, 21 } (n->1) -> { 20, 37, 21}
{ 1, 1, 1, 1, 1 }  (n->5) -> { 1, 1, 1, 1, 1 }

I tried this in my first attempt & it work...

But it's long.....

public class arr{
    public static void main(String[] args){
        int a[] = {1,1,3,3,7,2,2,2,2}; //Array of the elements
        int b =3; // maximum occurrences
        int u=1;  // Counter for same number of elements
        int c[] = new int[nterms(a, b)]; //initializing new array
        int k=0; 
        int l=0;
        for(int i =a.length-1; i>=0; i--){
            k=0;
            // Checking the duplicate elements.
            for(int j=i-1; j>=0; j--){
                if(a[i]==a[j]){
                    k++;    
                }
            }
            if(k!=b){ 
                c[c.length-u] = a[i];
                u++;
            }
        }
        for(int i =0; i<c.length; i++)
            System.out.println(c[i]);  
    }

    // Returns no. of unique elements.
    public static int nterms(int[] x, int y){
        int k=0;
        int l=0;
        for(int i =0; i<x.length; i++){
            k=0;
            for(int j=i+1; j<x.length; j++){
                if(x[i]==x[j]){
                    k++;    
                }
            }
            if(k==y){
                l++;
            }
        }
        return (x.length-l);
    }
}

Can anybody recommend more efficient way ????