I'm working on a coding problem where we have to mutate an existing array into a new array. The rules are that an element at the arrays index is equal to, a[i - 1] + a[i] + a[i + 1]. The catch is that if the a[i - 1] or a[i + 1] doesn't exist, they should be counted as zero.
My test cases are passing for every value up to the last value, and I can't understand why it isn't being calculated, when every other value is,
int[] mutateTheArray(int n, int[] a)
{
int b[] = new int[a.length + 1];
if(a.length == 1)
{
return a;
}
for(int i = 0; i < a.length - 1; i++)
{
if(i == 0)
{
b[0] = 0 + a[i] + a[i + 1];
}
if(i == a.length)
{
b[a.length] = a[i - 1] + a[i] + 0;
}
else if(i != a.length && i != 0)
{
b[i] = a[i - 1] + a[i] + a[i + 1];
}
}
return b;
}
The output should be for an array a = [4, 0, 1, -2, 3], output should be: [4, 5, -1, 2, 1]. I'm getting the answer except for the last value, which is calculating to 0. I know the issue is in accessing the array index - 1, but I don't know how to get each element without it going out of bounds. Any help is appreciated, thanks :)
if(i == a.length)should beif(i == a.length - 1). The condition of the lastelse ifcan just be dropped.i == a.length, as the condition of your for-loop isi < a.length - 1.