Last Updated: 26 Nov, 2020

Print Like A Wave

Easy
Asked in companies
Lenskart.comAmazonMercer Mettl

Problem statement

For a given two-dimensional integer array/list ‘ARR’ of size (N x M), print the ‘ARR’ in a sine wave order, i.e., print the first column top to bottom, next column bottom to top, and so on.

For eg:-

The sine wave for the matrix:-
1 2
3 4
will be [1, 3, 4, 2].
Input format :
The first line contains an Integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first line of each test case contains two integer values, 'N' and 'M,’ separated by a single space. They represent the 'rows' and 'columns,’ respectively, for the two-dimensional array/list ‘ARR’.

The next ‘N’ line contains an ‘M’ single-separated integer denoting the value of ‘ARR’.
Output format :
For each test case, print the two-dimensional array/list ‘ARR’ elements in the sine wave order in a single line, separated by a single space.

Output for every test case will be printed in a separate line.
Constraints :
1 <= T <= 10
1 <= N <= 100
1 <= M <= 100
0 <= ARR[i][j] <= 100

Time Limit: 1sec

Approaches

01 Approach

The basic idea of this approach is to print the elements row-wise. The elements are printed in two ways; top-down and bottom-up. It has been observed that the odd rows are printed in a bottom-up manner, and even ones are printed in a top-down manner. We will use two loops, the first loop will iterate through the number of columns, and the second loop will print the element row-wise.

 

Here is the algorithm:

 

  1. Run a loop from ‘I’ = 0 to ‘M_COL’ (Number of columns given)
    • If the current row is even, then the elements will be printed from top to bottom.
      • Run an inner loop from ‘J’ = 0 to ‘N_ROW’ (Number of rows given)
        • Print all the elements.
    • Else if the current row is odd, then the elements will be printed from bottom to top.
      • Run another loop from ‘J’ = ‘N_ROWS - 1’ to 0.
        • Print all the elements.