小编典典

如何计算排列?

algorithm

我有一个关于Java中置换的问题。

假设我在数组[a,b,c,d,e]中有五个不同的元素,并且我想从其中选择三个元素,顺序确实很重要。我知道在数学中我们可以使用5 P
3来获得答案,但是我们可以使用Java来获取5 P 3排列集的计数和元素的完整列表吗?


阅读 300

收藏
2020-07-28

共1个答案

小编典典

由于“ 1、2、3”与“ 2、1、3”不同,因此我建议使用以下代码段。请注意,为了避免出现“ 1、1、1”或“ 1、3、3”情形,我不能与j或k相同。

   // array with elements
   char[] items = {'a', 'b', 'c', 'd', 'e'};
   int count = 0;

    // first of the "three"
    for (int i = 0; i < upperBound; i++) {
       // second of the "three"
       for (int j = 0; j < upperBound; j++) {
          // can't be identical to i
          if (j == i) 
             continue;

          // third of the "three"
          for (int k = 0; k < upperBound; k++) {
             // can't be identical to i or j
             if (k == i || k ==j) 
                continue;

             // print some display
             System.out.println(items[i] + ", " + items[j] + ", " + items[k]);

             // increment the total count
             count++;
          }
       }
    }



    System.out.println("Total count is " + count);
2020-07-28