找不到如何编程这个数字模式 [英] can't find how to program this number pattern
本文介绍了找不到如何编程这个数字模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被要求输入一个数字rc,并根据rc构造这个模式。我可以初始化表但没有突出显示的数字:
I am asked to enter a number rc, and based on rc construct this pattern. I am able to initialize the table but without the highlighted numbers:
int [][] num2 = new int [rc][rc];
counter = 1;
for(int i = 0; i < rc; i++){
if(i!=0)
counter--;
for(int j =0; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
}
任何提示或想法?
推荐答案
我的解决方案背后的逻辑是:
The logic behind my solution is:
- 首先填写来自
1 - N
的数组,其中N
是用户输入(或
rc
在这种情况下): - 然后,我们检查它是不是第一行,如果是,我们只需打印
中的数字订单。 -
现在,我们必须知道哪个数字先行:
- First fill an array from
1 - N
, whereN
is the user input (orrc
in this case): - Then, we check if it's not the first line, if it is, we simply print the numbers in order.
Now, we have to know which numbers go first:
- In第1行(记住它从0开始),它必须打印[1] [0]中[1] [4]的数字,所以我们的循环减去
rc - i + j
,这给出:5 - 1 + 0,实际上是索引[4]。 -
我们知道在我们先打印了最后一个数字后,我们必须继续序列,所以我们打印索引:[1] [0]在[1] [1](为什么1,2?因为否则我们会得到类似下面的例子,这就是为什么我们需要减去1到它
- In the line 1 (remember it starts from 0), it must print the number at [1][4] in [1][0], so our loop substracts
rc - i + j
, this gives: 5 - 1 + 0, which in fact is index [4]. We know that after we've printed the last numbers first, we must continue the sequence, so we print index: [1][0] at [1][1] (Why 1, 2? Because otherwise we would get something like the example below, that's why we need to substract 1 to it
1 2 3 4 5
10 7 8 9 10
就是这样:
public class StrangePattern {
public static void main(String[] args) {
int rc = 5;
int number = 1;
int spaces = 0;
int[][] numbers = new int[rc][rc];
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
numbers[i][j] = number;
number++;
}
}
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
if (i != 0) {
if (j < i) {
System.out.print(numbers[i][rc - i + j] + "\t");
} else {
System.out.print(numbers[i][j - spaces] + "\t");
}
} else {
System.out.print(numbers[i][j] + "\t");
}
}
spaces++;
System.out.println();
}
}
}
提供此输出:
1 2 3 4 5
10 6 7 8 9
14 15 11 12 13
18 19 20 16 17
22 23 24 25 21
这个为 rc = 3
:
1 2 3
6 4 5
8 9 7
这篇关于找不到如何编程这个数字模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文