Reverse In Groups

 Coding Problem Keys 

 Reverse In Groups 

 Problem Statement 

Given an array of integers of size N and size of group R as input, the program must reverse and print every R elements in the array. Please fill in the lines of code to define the method reverseInGroup so that the program runs successfully.

 Boundary Condition(s) 

1 <= N, R <= 100

 Input Format 

The first line contains the value of N and R separated by space.
The second line contains N elements separated by space(s).

 Output Format 

The first line contains N elements separated by space.

 Example Input/Output 1 

 Input 

10 4
10 20 30 40 50 60 70 80 90 100

 Output 

40 30 20 10 80 70 60 50 90 100

 Explanation 

Reverse the first 4 elements ⟶ 40 30 20 10
Reverse the next 4 elements ⟶ 80 70 60 50
At last only 2 elements left which less than 4 so keep as it is ⟶ 90 100
Hence the output is 40 30 20 10 80 70 60 50 90 100

 Example Input/Output 2 

 Input 

7 8
2 4 6 8 10 12 14

 Output 

2 4 6 8 10 12 14

 Explanation 

The array has only 7 elements which is less than 8 so keep as it is ⟶ 2 4 6 8 10 12 14.
Hence the output is 2 4 6 8 10 12 14.

 Note: Max Execution Time Limit: 5000 millisecs 

 Solution 

 Programming Language: C Language 

#include <stdio.h>
void reverseInGroup(int arr[], int N, int R);
void main(){
    int N, R, index;
    scanf("%d%d", &N, &R);
    int arr[N];
    for(index=0; index<N; index++){
        scanf("%d",&arr[index]);
    }
    reverseInGroup(arr, N, R);
    for(index=0; index<N; index++){
        printf("%d ",arr[index]);
    }
}
 void reverseInGroup(int arr[],int N,int R){
     int w=R;
     int arrp,i=0,j=w-1;
     while(j<N){
         int wp=j,new=i;
         while(new<wp){
             arrp=arr[new];
             arr[new]=arr[wp];
             arr[wp]=arrp;
             new+=1;
             wp-=1;
         }i+=w;j+=w;
     }return arr;
 }
 // Published By PKJCODERS

 Programming Language: C++ Language 

#include<iostream>
using namespace std;
int main(){
    int n,k,q;
    cin>>n;
    q=n;
    int arr[n];
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    cin>>k;
    for(int i=0;i<n;i+=k){
        if(k+i<=n){
            for(int j=0;j<k/2;j++)
                swap(arr[i+j],arr[i+k-1-j]);
        }else{
            for(int j=i;j<n;j++){
                swap(arr[j],arr[n-1]);
                n--;
            }
        }
    }
    for(int i=0;i<q;i++)
        cout<<arr[i]<<" ";
}
// Published By PKJCODERS

 (Note: Incase If the code doesn't Pass the output kindly comment us with your feedback to help us improvise.) 

Comments

Popular Posts

Function decimalToBinary - CTS Pattern

Bank Account Balance

Interface Implementation - Pair

Words Starting with Upper Case

Occurrences of Sub in Parent

Flowchart Logic 047