【问题标题】:How do I calculate permutation? [closed]如何计算排列? [关闭]
【发布时间】:2017-07-04 21:29:47
【问题描述】:

我有一个关于 Java 排列的问题。

假设我在数组 [a, b, c, d, e] 中有五个不同的元素,我想从中选择三个元素,顺序很重要。我知道在数学中我们可以使用 5P3 来获得答案,但是我们可以使用 Java 来获得 5P3?

【问题讨论】:

标签: java algorithm permutation


【解决方案1】:

由于 "1, 2, 3" 和 "2, 1, 3" 不同,我建议使用以下代码 sn-p。请注意, i 不能与 j 或 k 相同,以避免“1、1、1”或“1、3、3”场景。

   // 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);

【讨论】:

  • 欢迎来到 Stack Overflow!虽然您可能已经解决了这个用户的问题,但纯代码的答案对于将来遇到这个问题的用户来说并不是很有帮助。请编辑您的答案以解释为什么您的代码解决了原始问题。
  • 谢谢@Joe。根据建议进行了修订。
  • 谢谢@RyanL。假设我在数组中有 i 项,例如 [1, 2, 3, 4, 5, 6, ....i-2, i-1, i] 我想从中选择 j 个元素,顺序很重要,怎么能我们使用 Java 来获取 jPi 的值和所有结果?
  • 嗨明华,你是说iPj吗?
  • @RyanL,谢谢。你说的对。我会做更多关于递归的研究。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-01
  • 2020-12-12
  • 1970-01-01
相关资源
最近更新 更多