In: Computer Science
Write an array method to carry out each of the following tasks for an array of integers. Note: you can think of each as a separate problem independent of the others.
a) Swap the first and last elements in the array.
b) Shi< all elements by one to the right and move the last element into the first
posi>on. For example, 1 4 9 16 25 would be transformed into 25 1 4 9 16.
c) Replace all even elements with 0.
d) Replace each element except the first and last by the larger of its two neigh-
bors.
e) Return true if the array contains duplicate elements (which need not be adja-
cent).
JAVA
Source Code:
class ex
{
static void swap_first_last(int arr[])
{
int temp=arr[0];
arr[0]=arr[arr.length - 1];
arr[arr.length - 1]=temp;
}
static void move_circular_right(int arr[])
{
int last=arr[arr.length - 1];
int i=arr.length -1 ,temp=0;
while(i>0)
{
arr[i]=arr[i-1];
--i;
}
arr[0]=last;
}
static void replace_even_with_zero(int arr[])
{
for(int
i=0;i<arr.length;i++)
{
if(arr[i]%2==0)
arr[i]=0;
}
}
static void replace_with_adj_neighbour(int
arr[])
{
for(int
i=1;i<arr.length-1;i++)
{
if(arr[i-1]>arr[i+1])
arr[i]=arr[i-1];
else
arr[i]=arr[i+1];
}
}
static boolean have_duplicates(int arr[])
{
boolean duplicates=false;
for(int
i=0;i<arr.length-1;i++)
{
for(int
j=i+1;j<arr.length;j++)
{
if(arr[i]==arr[j])
duplicates=true;
}
}
return duplicates;
}
public static void main(String[] args) {
int arr[]=new
int[]{1,4,9,16,25};
swap_first_last(arr);
move_circular_right(arr);
replace_even_with_zero(arr);
replace_with_adj_neighbour(arr);
System.out.println(have_duplicates(arr));
for(int
i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}