我如何计算排列? [英] How do I calculate permutation?

查看:117
本文介绍了我如何计算排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java中的排列有疑问。

I am having a question about permutation in Java.

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

Suppose I have five different elements in an array [a, b, c, d, e] and I want to select three elements out of them, the order does matter. I know in math we can use 5P3 to get the answer, but can we use Java to get the count and the complete list of elements of the permutation set of 5P3?

推荐答案

自1,2,3以来与2,1,3不同,我将建议以下代码片段。请注意,我不能与j或k相同,以避免1,1,1或1,3,3场景。

Since "1, 2, 3" is different from "2, 1, 3", I will suggest the following code snippet. Note that i can't be identical to j or k to avoid "1, 1, 1" or "1, 3, 3" scenarios.

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

这篇关于我如何计算排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆