码迷,mamicode.com
首页 > 其他好文 > 详细

Display an integer array

时间:2017-12-10 11:21:04      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:sha   har   equal   generated   pre   system   static   length   bsp   

Display an integer array of [1, 2, 3, 4, 5, 6, 7] in the following format 

1 4 6 
2 5 7 
3 

The method signature takes in an array of integers and the number of columns. In the above example, noOfCols = 3.
The columns should contain equal number of elements as much as possible.

 

public static void main(String[] args) { 
// TODO Auto-generated method stub 

int[] nums = { 1, 2, 3, 4, 5, 6, 7}; 
Problem.printArr(nums, 5); 
} 

private static void printArr(int[] nums, int numCols) { 

int numRows = nums.length / numCols; 
int numLastRow = nums.length % numCols; 
if (numLastRow > 0) { 
numRows++; 
} 

int[][] matrix = new int[numRows][numCols]; 
int arrIndex = 0; 

for (int i = 0; i < numCols; i++) { 
for (int j = 0; j < numRows; j++) { 
// If we‘re on the bottom row and over the number 
// of items to be put on it just skip this iteration 
if ((j == numRows - 1) && i >= numLastRow) { 
continue; 
} 
matrix[j][i] = nums[arrIndex]; 
arrIndex++; 
if (arrIndex >= nums.length) 
break; 
} 
if (arrIndex >= nums.length) 
break; 
} 

arrIndex = 0; 
for (int i = 0; i < numRows; i++) { 
for (int j = 0; j < numCols; j++) { 
if (matrix[i][j] > 0) 
System.out.print(String.format("%3d", matrix[i][j])); 
if (arrIndex >= nums.length) 
break; 
} 
System.out.println(); 
if (arrIndex >= nums.length) 
break; 
} 
} 

} 

  

Display an integer array

标签:sha   har   equal   generated   pre   system   static   length   bsp   

原文地址:http://www.cnblogs.com/apanda009/p/8016116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!