开发者

Java array of array [matrix] of an integer partition with fixed term

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;
     }

        part开发者_开发问答ition(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?


What about something like this?

import java.util.*;

public class Main {
    static void partition(int sum, int[] arr, int k) {
        if (k == arr.length - 1) {
            arr[k] = sum;
            System.out.println(Arrays.toString(arr));
            return;
        }
        for (int i = sum; i >= 0; i--) {
            arr[k] = i;
            partition(sum - i, arr, k + 1);
        }
    }

    public static void main(String[] args) {
        partition(10, new int[5], 0);
    }
}

Output:

[10, 0, 0, 0, 0]
[9, 1, 0, 0, 0]
[9, 0, 1, 0, 0]
[9, 0, 0, 1, 0]
[9, 0, 0, 0, 1]
[8, 2, 0, 0, 0]
[8, 1, 1, 0, 0]
:
:
[0, 0, 0, 5, 5]
[0, 0, 0, 4, 6]
[0, 0, 0, 3, 7]
[0, 0, 0, 2, 8]
[0, 0, 0, 1, 9]
[0, 0, 0, 0, 10]

(see full output)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜