Write a program to copy/mutate the array in Java

This program basically does this

if you have a[] = [1,0,2,0,4];

then you need to return the array as [1,3,2,6,4]

basically b[i] = b[i-1]+ b[i] + b[i+1];

Find the Java Program for the same, Here if you are not able to find the specific index then you can take the value for that index as “0”

int[] copyArray(int n, int[] a) {
    int[] b = new int[n];
for(int i=0;i<n;i++){
    int temp1 =0;
    int temp2 = 0;
    int temp3 =0;
    if(i-1 < 0){
        temp1 = 0;
    }else{
        temp1 = a[i-1];
    }
        
    if(i+1 < n){         
        temp3 = a[i+1];
    }else{
        temp3 = 0;
    }
    System.out.println("temp1: "+temp1);
    System.out.println("a[i]: "+a[i]);
    System.out.println("temp3: "+temp3);
     b[i] = temp1+a[i]+temp3;
}
    
    return b;
}

Leave a Reply