Created
March 28, 2018 00:07
-
-
Save diogoalexsmachado/79494bc2285e502a4c3a81308eda65de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.teste.app; | |
public class Main { | |
public static void main(String[] args) { | |
int[][] nums = {{ 1, 2, 3, 4}, | |
{ 5, 6, 7, 8}, | |
{ 9, 10, 11, 12}, | |
{13, 14, 15, 16}}; | |
int[][] nums2 = {{ 1, 2, 3}, | |
{ 4, 5, 6}, | |
{ 7, 8, 9}, | |
{ 10, 11, 12}}; | |
int[][] nums3 = {{ 1, 2, 3, 5, 6}, | |
{ 15, 16, 17, 18, 7}, | |
{ 14, 21, 20, 19, 8}, | |
{ 13, 12, 11, 10, 9}}; | |
System.out.println("nums 1 : "); | |
printStuff(nums); | |
System.out.println("\nnums 2 : "); | |
printStuff(nums2); | |
System.out.println("\nnums 3 : "); | |
printStuff(nums3); | |
} | |
public static void printStuff(int[][] nums){ | |
//set matrix lenght (dynamic) | |
int m = nums.length; | |
int n = nums[0].length; | |
int i, row = 0, column = 0; | |
while (row < m && column < n) { | |
// Print the top row | |
for (i = column; i < n; ++i) | |
System.out.print(nums[row][i]+" "); | |
row++; //go right | |
// Print the right column | |
for (i = row; i < m; ++i) | |
System.out.print(nums[i][n-1]+" "); | |
n--; //reduce last column from the "virtual" matrix | |
// Print the bottom row | |
if ( row < m) { | |
for (i = n-1; i >= column; --i) | |
System.out.print(nums[m-1][i]+" "); | |
m--; //reduce last row from the "virtual" matrix | |
} | |
// Print the left column | |
if (column < n) { | |
for (i = m-1; i >= row; --i) | |
System.out.print(nums[i][column]+" "); | |
column++; //go up | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment