5.6k views
4 votes
Given an integer n and an array a of length n, your task is to apply the following mutation to an: Array a mutates into a new array b of length n.

For each i from 0 to n - 1, b[i] = a[i - 1] + a[i] + a[i + 1].
If some element in the sum a[i - 1] + a[i] + a[i + 1] does not exist, it should be set to 0. For example, b[0] should be equal to 0 + a[0] + a[1].

1 Answer

6 votes

Answer: provided in the explanation section

Step-by-step explanation:

import java.util.*;

class Mutation {

public static int[] mutateTheArray(int n , int[] a)

{

int []b = new int[n];

for(int i=0;i<n;i++)

{

b[i]=0;

if(((i-1)>=0)&&((i-1)<n))

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

if(((i)>=0)&&((i)<n))

b[i]+=a[i];

if(((i+1)>=0)&&((i+1)<n))

b[i]+=a[i+1];

}

return b;

}

public static void main (String[] args) {

Scanner sc = new Scanner(System.in);

int n= sc.nextInt();

int []a = new int [n];

for(int i=0;i<n;i++)

a[i]=sc.nextInt();

int []b = mutateTheArray(n,a);

for(int i=0;i<n;i++)

System.out.print(b[i]+" ");

}

}

cheers i hope this helped !!

User Andre Kraemer
by
4.3k points