Home > database >  how to update the elements of an array with the sum of previous two and next two elements?
how to update the elements of an array with the sum of previous two and next two elements?

Time:09-17

how to update the elements of an array with the sum of previous two and next two elements ? given that for the first element the sum would be the sum of next two elements as there is no previous element and same is the case for last element. for example given an array {1,2,3} the array will be updated as {5,4,3} explanation: for 1 there is no previous element so it will be udated as 2 3=5, for 2 there is only 1 previous and only 1 next element so it will be updated as 1 3=4, similarly for 3 it will be 1 2=3.

i tried doing this with if else loops but that seems too confusing and lengthy is there any other way to solve this?

for(int i=0;i<n;i  ){
if(i==0){
sum=arr[1] arr[2];
}
if(i==1){
sum=arr[0] arr[2] arr[3];
}
if(i==n-1){
sum=arr[n-2] arr[n-3];

}
if(i==n-2){
sum=arr[n-1] arr[n-3] arr[n-4];
}

}

the above code does not work for n==3 because element at i==1 will be same as n-2 , also this code is so lengthy. how should i solve this question?

CodePudding user response:

You could use some logic like this if u are looking for minimal code

Psuedo code

for(int i=0;i<sizeof(arr);i  ){
    int sum = 0;
    int startIndex = (i 2) > sizeof(arr) ? sizeof(arr) : (i 2) ;
    while(startIndex > (i - 2) && startIndex > 0)
    {
        if(startIndex == i) continue;
        sum = sum   arr[startIndex];
        startIndex --;
    }
    arr[i] = sum;
}

CodePudding user response:

You need to create a temporary array to store the initial value of arr to prevent calculating the new value of arr[i] using new values (post-update) of arr[i - 1], arr[i - 2], etc.

std::vector<int> initial_value(arr, arr   n);

for (int i = 0; i < n;   i) {
    int updated_value = 0;
    if (i - 2 >= 0) {
        updated_value  = initial_value[i - 2];
    }
    if (i - 1 >= 0) {
        updated_value  = initial_value[i - 1];
    }
    if (i   1 < n) {
        updated_value  = initial_value[i   1];
    }
    if (i   2 < n) {
        updated_value  = initial_value[i   2];
    }
    arr[i] = updated_value;
}
  • Related