Java 数组的数组[矩阵] 具有固定项的整数分区
出于我的学习目的,我需要构建一个数组的数组,其中填充了具有固定项的整数的分区。给定一个整数,假设为 10,给定固定数量的项,假设为 5 我需要填充一个像这样的数组,这
10 0 0 0 0
9 0 0 0 1
8 0 0 0 2
7 0 0 0 3
............
9 0 0 1 0
8 0 0 1 1
.............
7 0 1 1 0
6 0 1 1 1
............
...........
0 6 1 1 1
.............
0 0 0 0 10
对 Java 来说很陌生,并且对所有 for 循环感到困惑。现在我的代码可以对整数进行分区,但不幸的是它不具有固定期限
public class Partition {
private static int[] riga;
private static void printPartition(int[] p, int n) {
for (int i= 0; i < n; i++)
System.out.print(p[i]+" ");
System.out.println();
}
private static void partition(int[] p, int n, int m, int i) {
if (n == 0)
printPartition(p, i);
else
for (int k= m; k > 0; k--) {
p[i]= k;
partition(p, n-k, n-k, i+1);
}
}
public static void main(String[] args) {
riga = new int[6];
for(int i = 0; i<riga.length; i++){
riga[i] = 0;
}
partition(riga, 6, 1, 0);
}
}
我从中得到的输出是这样的:
1 5
1 4 1
1 3 2
1 3 1 1
1 2 3
1 2 2 1
1 2 1 2
1 2 1 1 1
我实际上试图理解如何继续是让它有一个固定的术语,这将是我的列大批。所以,我一直在努力寻找一种方法来实现它 不太动态。有什么帮助吗?
for my study purpose I need to build an array of array filled with the partitions of an integer with fixed term. That is given an integer, suppose 10 and given the fixed number of terms, suppose 5 I need to populate an array like this
10 0 0 0 0
9 0 0 0 1
8 0 0 0 2
7 0 0 0 3
............
9 0 0 1 0
8 0 0 1 1
.............
7 0 1 1 0
6 0 1 1 1
............
...........
0 6 1 1 1
.............
0 0 0 0 10
am pretty new to Java and am getting confused with all the for loops. Right now my code can do the partition of the integer but unfortunately it is not with fixed term
public class Partition {
private static int[] riga;
private static void printPartition(int[] p, int n) {
for (int i= 0; i < n; i++)
System.out.print(p[i]+" ");
System.out.println();
}
private static void partition(int[] p, int n, int m, int i) {
if (n == 0)
printPartition(p, i);
else
for (int k= m; k > 0; k--) {
p[i]= k;
partition(p, n-k, n-k, i+1);
}
}
public static void main(String[] args) {
riga = new int[6];
for(int i = 0; i<riga.length; i++){
riga[i] = 0;
}
partition(riga, 6, 1, 0);
}
}
the output I get it from is like this:
1 5
1 4 1
1 3 2
1 3 1 1
1 2 3
1 2 2 1
1 2 1 2
1 2 1 1 1
what i'm actually trying to understand how to proceed is to have it with a fixed terms which would be the columns of my array. So, am stuck with trying to get a way to make it
less dynamic. Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样的事怎么办?
输出:(
查看完整输出)
What about something like this?
Output:
(see full output)