日期:2014-05-18 浏览次数:20740 次
private void btn_start_Click(object sender, EventArgs e) { //开始抽奖 if (btn_start.Text == "停止") { timer1.Stop(); btn_start.Text = "开始"; //保存获奖信息 SaveResult(); } else { cjnum++; timer1.Start(); } } private void SaveResult() { TGH.Lib.Log.WriteFile(Application.StartupPath + "\\choujiang.txt", "第" + cjnum.ToString() + "次抽奖数为:" + lbl_num.Text); lbl_result.Text += "第" + cjnum.ToString() + "次抽奖号码为:" + lbl_num.Text;// +"\r\n"; } public int[] getRandomNum(int num, int minValue, int maxValue) { Random ra = new Random(unchecked((int)DateTime.Now.Ticks)); arrNum = new int[num]; int tmp = 0; for (int i = 0; i <= num - 1; i++) { tmp = ra.Next(minValue, maxValue); //随机取数 arrNum[i] = ChouJiang(arrNum, tmp, minValue, maxValue, ra); //取出值赋到数组中 } return arrNum; } private int ChouJiang(int[] cjresults, int tmp, int minnum, int maxnum, Random ra) { int i = 0; xunhuannum++; while (i <= cjresults.Length - 1) { if (cjresults[i] == tmp) { //重新随即获取 tmp = ra.Next(minnum, maxnum); //递归:如果取出来的数字和已取得的数字有重复就重新随机获取 ChouJiang(cjresults, tmp, minnum, maxnum, ra); } i++; } return tmp; } private void timer1_Tick(object sender, EventArgs e) { //从fw1至fw2中取出6个互不相同的随机数 int[] arr = getRandomNum(cjtype, fw1, fw2); int i = 0; string temp = ""; while (i <= arr.Length - 1) { temp += arr[i].ToString() + "\n"; i++; } btn_start.Text = "停止"; lbl_num.Text = temp; }
/// <summary> /// 生成最大值范围内无重复值的长度为最大值的随机序列,例:6,则返回0,1,2,3,4,5 的List /// </summary> /// <param name="maxValue"></param> /// <returns></returns> public static List<int> GetRandomList(this int maxValue) { if (maxValue == 0) { return null; } //逻辑描述:生成从0开始到maxValue的tempList //然后random一次就maxValue--,并将random出来的整数用做索引,加入到returnList并从tempList中移除 maxValue = Math.Abs(maxValue);//防止负数 List<int> tempList = new List<int>(); for (int i = 0; i < maxValue; i++) { tempList.Add(i); } Random rd = new Random(); List<int> returnList = new List<int>(); while (maxValue > 0) { int tempInt = 0; if (maxValue > 1)//当maxValue为1时,不再进行随机,因为还剩一个数字,无需随机 { tempInt = rd.Next(maxValue); } returnList.Add(tempList[tempInt]); tempList.RemoveAt(tempInt); maxValue--; } return returnList; }
------解决方案--------------------