Print Like a Wave

 

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

Sample Input 1:
3 4 
1  2  3  4 
5  6  7  8 
9 10 11 12
Sample Output 1:
1 5 9 10 6 2 3 7 11 12 8 4
import java.util.Scanner;

public class WaveArray {

	public static void main(String[] args) {
	
		Scanner s = new Scanner(System.in);
		int n = s.nextInt();
		int m = s.nextInt();
		int input[][] = new int[n][m];
		for(int i = 0; i < n; i++)
		{
			for(int j = 0; j < m; j++)
			{
			input[i][j] = s.nextInt();
		}

	}
		wavePrint(input);

}

	public static void wavePrint(int mat[][]){
		
		 if(mat.length==0)
         {
             return;
         }
		
		for(int i=0;i<mat[0].length;i++)
		{
			if(i%2==0)
			{
				for(int j=0;j<mat.length;j++)
				{
					System.out.print(mat[j][i]+ " ");
				}
			}
				else
				{
					for(int j=mat.length-1;j>=0;j--)
					{
						System.out.print(mat[j][i]+ " ");
					}
				}
			}
		}

	}


Comments

Popular posts from this blog

Minimum Length Word

Check Number Sequence

Star Pattern