将用Python编写的方法转换为Java

时间:2016-01-14 17:46:03

标签: java python sequence

我一直在学习Python和Java课程。我试图将我为Python课程编写的函数转换为Java。我的主要问题是创建一个操作列表,就像在Python函数中一样。

这是Python中的函数:

def merge(line):
    """
    Function that merges a single row or column in 2048.
    """

    line_copy = line[:]
    line_len = len(line)

    # removes all zeros from the list copy
    for num in list(line_copy):
        if num == 0:
            line_copy.remove(num)

    # "merges" like tiles and removes the "merged" tile from the list
    for idx in range(len(list(line_copy))):
        if idx + 1 < len(line_copy):
            if line_copy[idx] == line_copy[idx+1]:
                line_copy[idx] *= 2
                line_copy.pop(idx+1)

    # appends the appropriate number of zeros to the back of the list if any
    while len(line_copy) < line_len:
        line_copy.append(0)


    return line_copy

这是我在Java中停止的地方。该程序不完整,因为我想使用main方法开始使用测试器类测试代码。

public class Merge {
    public static List<Integer> merge2048(ArrayList<Integer> line) {
        List<Integer> lineCopy = new ArrayList<Integer>(line);
        List<Integer> zero = Arrays.asList(0);
        lineCopy.removeAll(zero);
        return lineCopy;
    }
}

这是测试人员类。这是一个乱七八糟的混乱。我很难掌握Java中序列类型的概念。

public class mergeTest {
    public static void main(String[] args) {
        int[] line1;
        line1 = new int[]{1, 0, 2, 0, 4};
        ArrayList<Integer> test = new ArrayList<Integer>(line1);
        Merge mergeTest = new Merge();
        mergeTest.merge2048(line1);

    }
}

这让我想到了我的问题。我是在正确的轨道上吗?在阅读Java文档的过程中,我对Java中序列类型的创建,读取和操作感到困惑。

1 个答案:

答案 0 :(得分:1)

首先,您应该简化您的python函数:

def merge(line):
    """
    Function that merges a single row or column in 2048.
    """
    result = []
    for num in line:
        if num:
            if result and result[-1] == num:
                result[-1] *= 2
            else:
                result.append(num)
    while len(result) < len(line):
        result.append(0)
    return result

然后重写更简单:

public static ArrayList<Integer> merge2048(ArrayList<Integer> line) {
   ArrayList<Integer> result = new ArrayList<Integer>();
   for (Intger num : line) {
      if (num != 0) {
         if(result.size()>0 && result.get(result.size()-1) == num) {
            result.set(result.size()-1, result.get(result.size()-1) * 2);
         } else {
            result.add(num);
         }
      }
   }
   while(result.size()<line.size()) {
       result.add(0);
   }
   return result;
}