标签: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;
}
}
}
标签:sha har equal generated pre system static length bsp
原文地址:http://www.cnblogs.com/apanda009/p/8016116.html