4

我找到了一个代码片段,它在自动锦标赛括号生成器中给出了我想要的东西:一个数组。

有一个问题。我不会读也不会写python,但我精通(足够)Java。我不知道这是否是不好的堆栈溢出礼仪,但我要求有人协助将此代码转换为 Java 方法。

def CBseed( n ):
    #returns list of n in standard tournament seed order
    #Note that n need not be a power of 2 - 'byes' are returned as zero
    ol = [1]
    for i in range( int(ceil( log(n) / log(2) ) )):
        l = 2*len(ol) + 1
        ol = [e if e <= n else 0 for s in [[el, l-el] for el in ol] for e in s]
    return ol

哪个返回一个不错的

2 [1, 2] #seed 1 plays seed 2
3 [1, 0, 2, 3] #seed 1 gets a 'by' game and seed 2 plays seed 3
4 [1, 4, 2, 3] #ETC.
5 [1, 0, 4, 5, 2, 0, 3, 0]
6 [1, 0, 4, 5, 2, 0, 3, 6]
7 [1, 0, 4, 5, 2, 7, 3, 6]
8 [1, 8, 4, 5, 2, 7, 3, 6]
#and so on and so forth till this
31 [1, 0, 16, 17, 8, 25, 9, 24, 4, 29, 13, 20, 5, 28, 12, 21, 2, 31, 15, 18, 7, 26, 10, 23, 3, 30, 14, 19, 6, 27, 11, 22]
32 [1, 32, 16, 17, 8, 25, 9, 24, 4, 29, 13, 20, 5, 28, 12, 21, 2, 31, 15, 18, 7, 26, 10, 23, 3, 30, 14, 19, 6, 27, 11, 22]

因此,数组以两个为单位递增,每两个为一个游戏。

4

1 回答 1

5

直接翻译是这样的:

public static List<Integer> cbSeed(int n) {
    List<Integer> ol = new ArrayList<Integer>();
    ol.add(1);

    int max = (int) Math.ceil(Math.log(n) / Math.log(2));

    for (int i = 0; i < max; i++) {
        int l = 2 * ol.size() + 1;

        List<Integer> newOl = new ArrayList<Integer>(ol.size() * 2);
        for (int el : ol) {
            int e = el;
            newOl.add(e <= n ? e : 0);

            e = l - el;
            newOl.add(e <= n ? e : 0);
        }

        ol = newOl;
    }

    return ol;
}

如您所见,Java 更加冗长:)


您可以看到这产生了与 Python 函数相同的结果:

for (int i = 2; i < 9; i++)
    System.out.println(i + "\t" + cbSeed(i));
2 [1, 2]
3 [1, 0, 2, 3]
4 [1, 4, 2, 3]
5 [1, 0, 4, 5, 2, 0, 3, 0]
6 [1, 0, 4, 5, 2, 0, 3, 6]
7 [1, 0, 4, 5, 2, 7, 3, 6]
8 [1, 8, 4, 5, 2, 7, 3, 6]
于 2013-08-12T21:27:32.087 回答