简体   繁体   English

Java中的递归数字排列

[英]Recursive number permutation in Java

Recently I got assigned an assignment that says this:最近我接到了一个作业,上面写着:

Write a program named NumberPermutation.java and implement a recursive method specified below:编写一个名为NumberPermutation.java的程序并实现下面指定的递归方法:

 public static void permutation(int num)

This method has a positive integer as its parameter and displays all permutations of the odd digits of that length.此方法将一个正整数作为其参数,并显示该长度的奇数位的所有排列。

Display these values in ascending order.按升序显示这些值。 For example, if the length is 3, your program should display:例如,如果长度为 3,您的程序应该显示:

 111 113 115 117 119 131 133 135 ...

I'm very new to Java (as in all my previous coding assignments for the past year have been in Python and this is the 3rd Java program I've worked on), so I am absolutely lost on where to even get started.我对 Java 非常陌生(因为我过去一年的所有编码作业都是用 Python 编写的,这是我从事的第三个 Java 程序),所以我完全不知道从哪里开始。 If anyone can lend a hand and tell me how to get started I'd appreciate it, thanks.如果有人可以伸出援手并告诉我如何开始,我将不胜感激,谢谢。

Although I don't like questions that smell "help me with my homework" I'll provide an answer this time.虽然我不喜欢有“帮我做作业”味道的问题,但这次我会提供答案。 Here's my suggestion.这是我的建议。 Please don't just copy and paste and hand in. Understand first, and use this example to understand some of the basics of Java.请不要只是复制粘贴和提交。先了解一下,然后通过这个例子了解一些Java的基础知识。

public class RecursionTester {
    public static void main(String[] args) {
        new RecursionTester().permutation(3);
    }

    private void permutation(int num) {
        permutation(num, "");
    }

    private void permutation(int num, String buffer) {
        if (num == 0) {
            System.out.println(buffer);
            return;
        }
        for (int i = 1; i < 10; i += 2) {
            permutation(num - 1, buffer + Integer.toString(i));
        }
    }
}

The fact that the results just go to System.out makes this solution pretty useless, but if the task is to only prove that you understand recursion it should be enough.结果只是转到 System.out 的事实使该解决方案非常无用,但如果任务只是证明您了解递归,它应该足够了。

The map and reduce approach mapreduce方法

You can interpret this task as getting the Cartesian product of the n -th number of 2D arrays of odd digits .你可以解释此任务获得的笛卡尔乘积n的奇数字二维数组的第号。 If n=3 then you get 5 3 =125 combinations.如果n=3那么你会得到5 3 =125组合。

The mapToObj method prepares 2D arrays for summation and points to the format of the result: mapToObj方法为求和准备二维数组并指向结果的格式:

1: {{1}, {3}, {5}, {7}, {9}}
2: {{1}, {3}, {5}, {7}, {9}}
3: {{1}, {3}, {5}, {7}, {9}}

The reduce method sums pairs of 2D arrays into a single 2D array - two steps of reduction if n=3 : reduce方法将成对的 2D 数组相加到一个单一的 2D 数组中 - 如果n=3则为两个减少步骤:

1: {{1}, {3}, {5}, {7}, {9}}
2: {{1}, {3}, {5}, {7}, {9}}
---
sum1: {{1, 1}, {1, 3}, {1, 5}, ...}
3: {{1}, {3}, {5}, {7}, {9}}
---
total: {1, 1, 1}, {1, 1, 3}, ...}

Try it online! 在线试试吧!

public static int[][] cartesianProduct(int n, int[][] arr) {
    return IntStream.range(0, n)
            // stream of n-th number of 2D arrays
            .mapToObj(i -> arr)
            // stream of 2D arrays into a single 2D array
            .reduce((arr1, arr2) -> Arrays.stream(arr1)
                // combinations of rows of two arrays
                .flatMap(row1 -> Arrays.stream(arr2)
                    // concatenate into a single row
                    .map(row2 -> Stream.of(row1, row2)
                        .flatMapToInt(Arrays::stream)
                        // row of a 2D array
                        .toArray()))
                // 2D array of combinations
                .toArray(int[][]::new))
            // otherwise an empty array
            .orElse(new int[0][]);
}
public static void main(String[] args) {
    // exponent
    int n = 3;
    // 2D array of odd digits
    int[][] arr = {{1}, {3}, {5}, {7}, {9}};
    // cartesian product
    int[][] cp = cartesianProduct(n, arr);
    // output
    System.out.println("Number of combinations: " + cp.length);
    // number of rows
    int rows = cp.length / arr.length;
    // column-wise output
    IntStream.range(0, rows)
            .mapToObj(i -> IntStream.range(0, cp.length)
                .filter(j -> j % rows == i)
                .mapToObj(j -> Arrays.toString(cp[j]))
                .collect(Collectors.joining(" ")))
            .forEach(System.out::println);
}

Output:输出:

Number of combinations: 125
[1, 1, 1] [3, 1, 1] [5, 1, 1] [7, 1, 1] [9, 1, 1]
[1, 1, 3] [3, 1, 3] [5, 1, 3] [7, 1, 3] [9, 1, 3]
[1,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 9] [5, 9, 9] [7, 9, 9] [9, 9, 9]

See also: How do I generate a Cartesian product in Java?另请参阅:如何在 Java 中生成笛卡尔积?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM