Home > OS >  Count repeated elements in Java without using loops or imports
Count repeated elements in Java without using loops or imports

Time:12-02

For training purposes I tried to code a program which counts how often a given number appears in an given array of integers. Then checks if the number is even or odd. Without using any imports or loops. I tried to solve it recursive. For Example:

(3, new int[]{3,3,4,5,3,3,2,1})

There are 4 threes, so the Program should check if 4 is even or odd.

After days of coding and not working code I decided to ask here: any Solutions?

public static int evenNumberOf(int num, int[] numarr) {

int i = 0 ;
        int counter = 0;
        if(a == null || a.length == 0) {
            return false;
        } else {
            if(a[i] == a.length -1 ) {
                if(counter % 2 == 0) {
                    System.out.println("true");
                    return true;
                    
                } else System.out.println("false");
                    return false;
                
            } else {
            if(a[i] == n) {
                counter  ;
                i  ;
                return evenNumberOf(n,a) ;
            } else {
                i  ;
                return evenNumberOf(n,a) ;

CodePudding user response:

Hint:

If you are trying to do this recursively, you can do this quickly with divide and conquer. Split the array into half, count each subarray and combine the results. Make sure the base case of an empty array/single element array is handled correctly.

CodePudding user response:

Try this:

public static void main(String[] args) throws Exception{
    System.out.println(evenNumberOf(2, 0, new int[]{2,0,3,7,6,11,1,2}, 0));
}

//arr should not be empty, index and count >= 0
public static int evenNumberOf(int num, int index,int[]numarr, int count) {
    if(index >= numarr.length) return count;
    if(numarr[index] == num ) {
        count  ;
    }
    return evenNumberOf(num,   index, numarr, count);
}

You can add an helper method to make calling simpler :

public static int evenNumberOf(int num, int[] numarr) {
    return evenNumberOf(num, 0, numarr,0);
}
  • Related