将Python分区生成器转换为Java

时间:2014-02-26 17:22:08

标签: java python combinatorics code-conversion

我正在尝试将以下分区生成器从Python转换为Java而没有得到预期的结果:

的Python:

def accelAsc(n):
    a = [0 for i in range(n + 1)]
    k = 1
    a[0] = 0
    y = n - 1
    while k != 0:
        x = a[k - 1] + 1
        k -= 1
        while 2*x <= y:
            a[k] = x
            y -= x
            k += 1
        l = k + 1
        while x <= y:
            a[k] = x
            a[l] = y
            yield a[:k + 2]
            x += 1
            y -= 1
        a[k] = x + y
        y = x + y - 1
        yield a[:k + 1]

我的Java:

public static void partition( int n ){
    int[] a = new int[ n + 1 ];
    int k = 1;
    int y = n - 1;
    while( k != 0 ){
        int x = a[k - 1] + 1;
        k -= 1;
        while( 2*x <= y ){
            a[k] = x;
            y -= x;
            k += 1;
        }
        int l = k + 1;
        while( x <= y ){
            a[k] = x;
            a[l] = y;
            for( int xValue = 0; xValue <= k; xValue++ ) System.out.print( a[xValue + 2] );
            System.out.println();
            x += 1;
            y -= 1;
        }
        a[k] = x + y;
        y = x + y - 1;
        for( int xValue = 0; xValue <= k; xValue++ ) System.out.print( a[xValue + 1] );
        System.out.println();
    }
}

使用参数5调用此结果会导致以下打印输出:

1110
1121
132
22
42
2
3

这是不正确的。

1 个答案:

答案 0 :(得分:0)

凯文的评论引出了答案:

替换

for( int xValue = 0; xValue <= k; xValue++ ) System.out.print( a[xValue + 2] );

for( int xValue = 0; xValue < k + 2; xValue++ ) System.out.print( a[xValue] );

替换

for( int xValue = 0; xValue <= k; xValue++ ) System.out.print( a[xValue + 1] );

for( int xValue = 0; xValue < k + 1; xValue++ ) System.out.print( a[xValue] );