Reverse array in groups

PROBLEM :

Given an array, reverse every sub-array formed by consecutive k elements.

Input:

The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of two lines. The first line of each test case consists of an integer N, where N is the size of array.The second line of each test case contains N space separated integers denoting array elements.The third line of each test case consists of an integer K.

Output:
Corresponding to each test case, in a new line, print the modified array.

Constraints:

1 = T = 100
1 = N = 500
1 = A[i] = 500

Example:

Input
1
5
1 2 3 4 5
3

Output
3 2 1 5 4

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
void Reverse_array_in_groups(int [],int ,int ) ;
void reverse(int arr[],int ,int ) ;
int main()
 {
int t,no,arr[500],i,k ;
cin>>t ;
while(t--)
{
   cin>>no ;
   for(i=0;i<no;i++)
       cin>>arr[i] ;
   cin>>k ;
 
   Reverse_array_in_groups(arr,no,k) ;
 
   for(i=0;i<no;i++)
       cout<<arr[i]<<" " ;
   cout<<endl ;
}
return 0;
}

void Reverse_array_in_groups(int arr[],int no,int k)
{
    int i,start,end ;
    start=0 ;
    end=no-1 ;
   
    if(no<=k)
    {
        reverse(arr,start,end) ;
        return ;
    }
       
    i=0 ;
    k=k-1 ;
    while(i+k<=no-1)
    {
        reverse(arr,i,i+k) ;
        i=i+k+1 ;
    }
   
    if(i!=no-1)
        reverse(arr,i,no-1) ;
}

void reverse(int arr[],int start,int end)
{
    int temp ;
    while(start<end)
    {
        temp=arr[start] ;
        arr[start]=arr[end] ;
        arr[end]=temp ;
       
        start++ ;
        end-- ;
    }
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )