首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 算法實現雙色球號碼與組合序號雙向轉換

     編輯:Java 相關知識

遊戲規則

  • 紅球:1-33 選 6 個(不重複,升序)。
  • 藍球:1-16 選 1 個。
  • 總組合數:C(33,6) × 16 = 1,107,568 × 16 = 17,721,088 種。

核心算法:組合數學映射

利用組合數遞推公式,將紅球組合映射為唯一序號(0-based),再乘 16 加藍球值得到完整索引。

紅球組合 → 序號

public static final int getBallIndex(int a,int b,int c,int d,int e,int f,int g) {
    return (comp(33,6) - comp(34-a,6)
         + comp(33-a,5) - comp(34-b,5)
         + comp(33-b,4) - comp(34-c,4)
         + comp(33-c,3) - comp(34-d,3)
         + comp(33-d,2) - comp(34-e,2)
         + comp(33-e,1) - comp(33-f,1)) * 16 + g;
}

序號 → 紅球組合

public static final String getBall(long ballIndex) {
    if (ballIndex > 17721088) ballIndex %= 17721088;
    int redIndex = (int)(ballIndex / 16);
    int count = 0;
    for (int a=1; a<29; a++)
      for (int b=a+1; b<30; b++)
        for (int c=b+1; c<31; c++)
          for (int d=c+1; d<32; d++)
            for (int e=d+1; e<33; e++)
              for (int f=e+1; f<34; f++) {
                  count++;
                  if (redIndex == count) {
                      int blue = 1 + (int)((ballIndex-1) % 16);
                      return Arrays.toString(new int[]{a,b,c,d,e,f,blue});
                  }
              }
    return null;
}

組合數計算 C(m,n)

public static final int comp(int m, int n) {
    int sum = 1;
    for (int i=m; i>m-n; i--) sum *= i;
    for (int i=n; i>1; i--) sum /= i;
    return sum;
}

驗證示例

// 2023-11-29 開獎:6,20,28,29,30,31 + 12
System.out.println(getBallIndex(6,20,28,29,30,31,12)); // 12964124
System.out.println(getBall(12964124)); // [6, 20, 28, 29, 30, 31, 12]

// 2023-12-01 開獎:3,8,19,25,27,28 + 2
System.out.println(getBallIndex(3,8,19,25,27,28,2)); // 7353378
System.out.println(getBall(7353378)); // [3, 8, 19, 25, 27, 28, 2]

複式投注全組合展開

public static int getDoubleChromosphere(Integer[] redBall, int[] blueBall) {
    List result = new LinkedList<>();
    int count = 0;
    for (int b : blueBall) {
        List reds = new LinkedList<>(Arrays.asList(redBall));
        for (int i=0; i combo = new LinkedList<>(reds);
            combo.remove(i); // 從 n 紅球中選 n-1?實際邏輯需根據玩法調整
            combo.add(b);
            System.out.println("紅球: " + combo.subList(0,6) + " 藍球: " + b);
            count++;
        }
    }
    return count;
}

算法複雜度

  • 序號→組合:六層循環,最多 110 萬次迭代,極快(毫秒級)。
  • 組合→序號:O(1) 純數學運算。

總結

基於組合數學的雙向映射,可用於歷史數據分析、走勢圖繪制、隨機生成注單等彩票輔助工具開發。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved