Sigma9
Sigma9

Reputation: 29

Recursively removing all elements from an array whose index is a multiple of i >= 2 (Java)

I'm dealing with this recursion problem and I do need some assistance. I'm given a number n and a length n, sorted array r which contains only positive integers. I need to remove every second element from the array, then third,...,nth element and so on until my array size is smaller then the nth number. then i need to determine if the given number n is a "special number", meaning it is in the final list after all required elements had been removed. Not allowed to use any loops nor to create any other arrays but the given one.

for example: r = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20} after removing every second element: r = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19} after removing every third element: r = {1, 3, 7, 9, 13, 15, 19}.

after removing every 5th element: r = {1,3,7,13}

1,3,7,13 are special numbers.

Below is what I've done so far. for the above mentioned array r the program prints false. What am I missing?

public static boolean isSpecial (int n ){
    int [] r = new int []{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
    int end = r.length -1  ;
    return isSpecialHelper(r, -1, end ,2  , n );
    
}
public static boolean isSpecialHelper ( int []r ,int start,int end, int i, int n){
    
    if ( i > r.length ){
        return isSpecialHelper1( r, i -1, n);
        
    }
    else if (i <= r.length && (start + i) % i != 0 && (start + i) < end){
        
            // r[(start+i)] = r[(start+i)+1];
            r[start+i] = r[(start+i)+1];
            return isSpecialHelper(r, start + i, i, end, n); 
    }
    else if((start + i)  == end){
        
            // r[(start+i)] = r[(start+i)+1];
            return isSpecialHelper(r, -1, i++ , end, n); 
        
    }
    return false;
}   
public static boolean isSpecialHelper1( int [] r,int j,int n){
    if (r[j] == n){
        return true;   
    }
    else if (r[j]!= n ){ return isSpecialHelper1(r, j--, n);}
    return false;
}
public static void main (String [] args){
   System.out.print(  isSpecial(7)));
    
}
    
}

Upvotes: 1

Views: 304

Answers (1)

Avarage cat enjoyer
Avarage cat enjoyer

Reputation: 133

isSpecial() doesn't have a System.out.println(); statement. return on its own doesn't print. You should do System.out.println(isSpecial(7)); in your main method or add System.out.println(); to your method. In this case you don't have to add return there and you can change method type to void.

Upvotes: 1

Related Questions