做了一个彩票程序,为了复式投注颇费了点脑筋,网上找了半天,才知道这个公式,比如36选7,如果买10个号,公式就是:
10!/ (10-7)!/ 7!
顺手做了一个测试程序:
- using System;
- public class Test{
- public static void Main(string[] args){
- int a = 5; // 选择了几
- int b = 2;
- try{
- if(args.Length == 1){
- b = int.Parse(args[0]);
- } else if(args.Length >= 2){
- a = int.Parse(args[0]);
- b = int.Parse(args[1]);
- }
- }catch{
- Console.WriteLine("请正确输入");
- return;
- }
- int d = GetCount(a, b);
- Console.WriteLine("{0},{1},{2}", a,b,d);
- }
- //buyNum : 购买的数字个数
- //perNum : 每注要求的数字个数
- // 返回值为 : buyNum!/(buyNum-perNum)!/perNum!
- public static int GetCount(int buyNum, int perNum){
- if(perNum == buyNum)
- return 1;
- if(perNum > buyNum){
- throw new Exception("后者必须比前者小!");
- }else if(perNum <= 0){
- throw new Exception("后者不能小于0!");
- }
- // 这3行能提高一点效率,并降低一部分溢出的可能
- int diff = buyNum - perNum;
- if (diff > perNum)
- perNum = diff;
- int result = 1;
- for(int i=perNum + 1;i<=buyNum;i++){
- result *= i;
- }
- for(int i=1;i<=buyNum - perNum;i++){
- result /= i;
- }
- return result;
- /*
- 8个号码选7= 8注
- 9个号码选7= 36注
- 10个号码选7= 120注
- 11个号码选7= 330注
- 12个号码选7= 792注
- */
- }
- }
下面是生成复式投注时,列出组合号码的列表的代码:
- /// <summary>
- /// 从数组中查找s个数字的组合,并返回全部组合(根据复式彩票投注的号码,返回对应的全部号码组列表)
- /// </summary>
- /// <param name="arr">数组(购买的数字列表)</param>
- /// <param name="s">大于0的整数(每注要求的数字个数)</param>
- /// <returns></returns>
- List<List<int>> GetCountList(int[] arr, int s)
- {
- if (s < 1)
- throw new Exception("选择个数不能小于1!");
- if (arr == null || arr.Length == 0 || arr.Length < s)
- throw new Exception("数组不能为空 或 小于必选个数!");
- if (arr.Length == s)
- {
- #region 数组长度等于s时,直接返回1个组合
- List<List<int>> l_ret = new List<List<int>>();
- List<int> l_item = new List<int>();
- foreach (int item in arr)
- {
- l_item.Add(item);
- }
- l_ret.Add(l_item);
- #endregion
- return l_ret;
- }
- if (s == 1)
- {
- #region 从数组中查找1个数字的组合,直接把数组各元素返回
- List<List<int>> l_ret = new List<List<int>>();
- foreach (int item in arr)
- {
- List<int> l_item = new List<int>();
- l_item.Add(item);
- l_ret.Add(l_item);
- }
- #endregion
- return l_ret;
- }
- List<List<int>> l_arrTmp = new List<List<int>>();
- for (int i = 0; i < arr.Length - s; i++)
- {
- // 后面的数任意取s-1个
- int[] tmp = GetArray(arr, i);
- List<List<int>> l_arrTmp1 = GetCountList(tmp, s - 1);
- foreach (List<int> item in l_arrTmp1)
- {
- item.Insert(0, arr[i]);
- l_arrTmp.Add(item);
- }
- }
- List<int> l_lastItem = new List<int>();
- for (int i = arr.Length - s; i < arr.Length; i++)
- {
- l_lastItem.Add(arr[i]);
- }
- l_arrTmp.Add(l_lastItem);
- return l_arrTmp;
- }
- /// <summary>
- /// 把arr数组中,位置为beg之后的元素全部放入一个新数组返回(不包含beg元素)
- /// </summary>
- /// <param name="arr"></param>
- /// <param name="beg"></param>
- /// <returns></returns>
- private static int[] GetArray(int[] arr, int beg)
- {
- int[] tmp = new int[arr.Length - (beg + 1)];
- for (int i = beg + 1; i < arr.Length; i++)
- tmp[i - (beg + 1)] = arr[i];
- return tmp;
- }