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”不同,我将建议以下代码片段。请注意,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);