給定數組{±1.6, ±1, ±0.6, 0}共7個相異數值,任選4個組成有序四元組(a, b, c, d),請問總共有多少個偶排列?本文提供數學推導與完整Java暴力驗證程式碼。
P(7,4) = 7 × 6 × 5 × 4 = 840。840 / 2 = 420。public class PermutationParity {
// 計算逆序對數
static int inversionCount(double[] arr) {
int cnt = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) cnt++;
}
}
return cnt;
}
public static void main(String[] args) {
double[] pool = {1.6, 1, 0.6, 0, -0.6, -1, -1.6};
int total = 0, even = 0;
// 四層迴窮舉所有有序四元組
for (int i = 0; i < 7; i++)
for (int j = 0; j < 7; j++)
if (j != i)
for (int m = 0; m < 7; m++)
if (m != i && m != j)
for (int n = 0; n < 7; n++)
if (n != i && n != j && n != m) {
total++;
double[] quad = {pool[i], pool[j], pool[m], pool[n]};
if (inversionCount(quad) % 2 == 0) even++;
}
System.out.println("總排列數: " + total + " 偶排列數: " + even);
// 輸出: 總排列數: 840 偶排列數: 420
}
}
總排列數: 840 偶排列數: 420,與理論推導完全一致。
若需列出所有偶排列的具體內容,可在if (inversionCount(quad) % 2 == 0)區塊中加入列印或收集邏輯。此暴力法適用於n ≤ 10的小規模問題;大規模問題建議使用組合數學公式或生成函數直接計算。