如何按列而非按行填充指定样式的10×10二维数组?
正确实现方案
首先分析目标数组的数值规律:
- 当列索引
col≤ 行索引row时,数值为0; - 当
col > row时,数值计算公式为:45 - (col * (col - 1)) / 2 - row
公式推导依据:
- 第0行(row=0)的非0数值,是从45开始依次减去1、2、3…直到8,等价于
45 - 1到(col-1)的和,而1到n的和公式为n*(n+1)/2,这里n=col-1,因此第0行col列的数值为45 - (col*(col-1))/2; - 同一列col中,每往下一行(row增加1)数值减少1,最终数值为第0行该列的值减去row。
正确代码实现
public class Main { public static void main(String[] args) { int size = 10; for (int row = 0; row < size; row++) { StringBuilder line = new StringBuilder(); for (int col = 0; col < size; col++) { if (col <= row) { line.append("0"); } else { int value = 45 - (col * (col - 1)) / 2 - row; line.append(value); } // 贴近目标格式添加分隔空格 if (col != size - 1) { if (col == row) { line.append(" "); } else { line.append(" "); } } } System.out.println(line.toString()); } } }
输出验证
运行上述代码后,输出将与目标样式完全一致:
0 45 44 42 39 35 30 24 17 9 0 0 43 41 38 34 29 23 16 8 0 0 0 40 37 33 28 22 15 7 0 0 0 0 36 32 27 21 14 6 0 0 0 0 0 31 26 20 13 5 0 0 0 0 0 0 25 19 12 4 0 0 0 0 0 0 0 18 11 3 0 0 0 0 0 0 0 0 10 2 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
内容的提问来源于stack exchange,提问作者faeton
相关产品推荐
相关产品推荐

