java - 如何递归地重复数组中的元素n次?

标签 java arrays recursion

为了更清楚,我正在尝试找到解决此问题的递归函数:

  • 输入 = [8, 4, 3, 4}
  • n = 3
  • 输出 = [8, 8, 8, 4, 4, 4, 3, 3, 3, 4, 4, 4]

我已经使用迭代和循环解决了这个问题,但是由于我刚刚接触了递归方法,所以我仍然在这个问题上特别挣扎。这是我的迭代解决方案。

public class repeatElement {

public static void main(String[] args) {
    int[] a = {1, 2, 3};
    int n, j, i;
    n = Integer.parseInt(JOptionPane.showInputDialog("Enter n"));
    int[] b = new int[a.length * n];

    for (i = 0; i < a.length; i++) {
         for (j = n*i; j < n*(i+1); j++) {
            if (j % n == 0) {
                b[j] = a[i];
            }
            if (j % n != 0) {
                b[j] = a[i];
            }
        }
    }
    JOptionPane.showMessageDialog(null, Arrays.toString(b));
}

最佳答案

您可以通过使用额外的 index 参数来模拟带有递归的 for 循环。在方法结束时,使用 index + 1 再次递归调用该方法。当 index 到达数组末尾时,该方法应该返回,就像 for 循环一样:

private static void repeatEachElement(int times, int[] input, int[] output, int index) {
    // stopping condition
    if (index == output.length) {
        return;
    }

    // this is where it fills the array.
    output[index] = input[index / times];

    // calls itself again with index + 1
    repeatEachElement(times, input, output, index + 1);
}

请注意,我在输出数组上“循环”,这样我就不需要另一个循环来填充每个索引。我可以通过执行 input[index/times] 来获取应该位于该索引处的元素。

要调用此方法,您需要首先创建一个正确长度的输出数组,并且index必须从0开始。您可以将此方法包装为更方便的方法:

private static int[] repeatEachElement(int times, int[] input) {
    int[] output = new int[input.length * times];
    repeatEachElement(times, input, output, 0);
    return output;
}

然后你可以这样做:

int[] input = {8, 4, 3, 4};
System.out.println(Arrays.toString(repeatEachElement(3, input)));
// [8, 8, 8, 4, 4, 4, 3, 3, 3, 4, 4, 4]

归根结底,除了了解递归的工作原理之外,在 Java 中递归地执行此操作没有太多意义。它的可读性比循环差,并且如果数组足够长,就会溢出堆栈。

关于java - 如何递归地重复数组中的元素n次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70232911/

相关文章:

java - ConcurrentHashMap 的迭代一致性保证

java - Minfiying CSS 破坏了嵌入的 EL 表达式

php - 在 Twig 中显示嵌套数组

java - 递归检查数组是否包含 0 (java)

Java类加载器: Why an "NoSuchMethodEx" is thrown here?

java - 计算器 Try and Catch Java 程序

php - 不同数组中键的值

java - 在 for 循环中表示整个数组的正确方法是什么?

algorithm - 递归:打印隐含的括号

function - 如何在 Haskell 中创建 Prouhet-Thue-Morse 序列?