【问题标题】:How to print out X number of permutations in java?如何在java中打印出X个排列?
【发布时间】:2018-11-05 05:32:10
【问题描述】:

我编写的代码采用数组元素并遍历数组以给出所有排列。但我需要它只显示一定数量的排列:

最后的代码是只给出 9 个元素的 6 个排列(换句话说,打印总共 362880 个输出的前 60480 个排列)。为简单起见,我使用数组中的 4 个元素,并打印出所有 24 个排列。但我需要代码适用于任意数量的排列。例如,如果我需要它打印出 1-permutation,代码应该打印前 4 个排列 - ABCD、ABDC、ACBD 和 ACDB。我不确定如何解决这个问题。

public static void main(String[] args) {
    // TODO Auto-generated method stub


    String[] myArray = {"A","B","C", "D"};
    int size = myArray.length; 
    permutation(myArray, 0, size-1);

    // Calculate Permutations
    int n=size;
    int r=6; // subject to change
    int p = n - r;
    int total=1;
    int total2=1;
    int total3=0;

    for (int top=n; top>0; top--)
    {
        total *= top;
    }

    if ((n-r<0))
    {
     System.out.println("r value cannot be greater than array size");
     total3=0;
    }
    else 
    {
        for (int bot=1; bot<=p; bot++)
        {
            if (p==0) // should be -- else if (p==0) -- after correction
            {
                total2=1;
            }
            else
            {
                total2 *= bot;
            }
        }
        total3 = total/total2;
    }

    System.out.printf("%d permutations of %d elements = %d\n",r,n,total3);
    // end calculation

}
// end main

// print array
public static void prtArray(String[] myArray, int size)
{
    for(int i=0; i<size; i++)
    {
        System.out.printf("%s", myArray[i]);
    }
    System.out.println();
}

// swap elements    
public static void swap(String[] myArray, int i, int j) {
    String temp;
    temp = myArray[i];
    myArray[i]=myArray[j];
    myArray[j]=temp;
}

// permutation 
private static void permutation(String[] myArray, int b, int e)
{
    if (b == e)
        prtArray(myArray, e+1); // accounts for array of size 1
    else
    {
        for(int i = b; i <= e; i++)
        {

            swap(myArray, i, b);
            permutation(myArray, b+1, e);
            swap(myArray, i, b);

        }
    }
}
}

【问题讨论】:

  • 我真的没有看到问题。代码运行,如果我在数组中添加 9 个元素,我会得到所有的排列。真正的问题是什么?
  • 请提供不起作用的代码,而不是提供模糊描述要更改哪些内容以使其不起作用的代码。还请添加完整的异常消息和堆栈跟踪,以便我们确切知道哪里出了问题。谢谢!
  • 我知道代码运行良好,问题是它打印出所有排列。我正在使用数组中的 4 个元素,所以当我运行代码时,我会打印出 24 种不同的排列。但是,例如,假设我需要打印 2 个排列,那么我应该只打印前 12 个排列。代码需要考虑 r 排列,其中排列的公式是 [(# of elements)! /(元素数 - r)! ]。这就是我卡住的地方。

标签: java arrays recursion permutation swap


【解决方案1】:

我假设您不希望某个元素在排列中重复。 例如。

如果输入数组是 {1, 2, 3, 4},那么对于长度 3:123124 等是有效的排列,但 122111 不是。

为了避免拾取已经被拾取的元素,我们需要在递归中传递一个visited 数组。

public class Main {
    // Maintain a global counter. After finding a permutation, increment this. 
    private static int count = 0;

    // pos is the current index, and K is the length of permutation you want to print, and N is the number of permutation you want to print.
    private static void printPermutations(int[] arr, int[] visited, int pos, int K, int N, String str) {

        // We have already found N number of permutations. We don't need anymore. So just return.
        if (count == N) {
            return;
        }

        if (pos == K) {
            System.out.println(str);
            count++; // we have found a valid permutation, increment counter.
            return;
        }

        for (int i = 0; i < arr.length; i++) {
            // Only recur if the ith element is not visited.
            if (visited[i] == 0) {
                // mark ith element as visited.
                visited[i] = 1;
                printPermutations(arr, visited, pos + 1, K, N, str + arr[i]);
                // unmark ith element as visited.
                visited[i] = 0;
            }
        }

    }


    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};
        int[] visited = {0, 0, 0, 0}; // same as size of input array.
        count = 0; // make sure to reset this counter everytime you call printPermutations.
        // let's print first 4 permutations of length 3.
        printPermutations(arr, visited, 0, 3, 4, "");
    }
}

输出:

对于 N = 4 和 K = 3(即长度为 3 的前 4 个排列):

printPermutations(arr, visited, 0, 3, 4, "");

123
124
132
134

对于 N = 4 和 K = 4(即长度为 4 的前 4 个排列):

printPermutations(arr, visited, 0, 4, 4, "");

1234
1243
1324
1342

【讨论】:

  • 我的代码解释了重复的元素并且运行良好。问题是它打印出所有排列。我正在使用数组中的 4 个元素,所以当我运行代码时,我会打印出 24 种不同的排列。但是,例如,假设我需要打印出这个 4 元素数组的 2 个排列,那么我应该只打印出前 12 个排列。代码需要考虑 r 排列,其中排列的公式是 [(# of elements)! /(元素数 - r)! ]。这就是我卡住的地方。
  • 如果您希望递归在计算出“确定”数量的排列后停止,您可以维护一个全局计数器,以记录到目前为止计算出的排列数量。如果你达到了那个数字(比如N),然后返回递归。请检查编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
  • 2020-07-17
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 2014-07-05
  • 1970-01-01
相关资源
最近更新 更多