平均分配的实现
protected void Button2_Click(object sender, EventArgs e) { List<string> persons = new List<string>(); Dictionary<string, List<string>> result = new Dictionary<string, List<string>>(); //初始化数据 string[] itemList = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K" }; int m = 4; //任务数 int n = 3; //分配人数 //随机初始化一下 List<string> itemListTemp = new List<string>(); long tick = DateTime.Now.Ticks; Random r = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));//保证生成随机数重复率很低 while (itemListTemp.Count < m) { int j = r.Next(m); string s = itemList[j]; if (itemListTemp.Count > 0) { while (itemListTemp.Contains(s)) { j = r.Next(m); s = itemList[j]; } } itemListTemp.Add(s); } for (int j = 0; j < n; j++) { string t = (j + 1).ToString().PadLeft(12, '0'); persons.Add(t); result.Add(t, new List<string>()); } //算法 int iAv = m / n == 0 ? 1 : m / n; int iMod = m % n; int i = 0; foreach (string k in result.Keys) { if (itemListTemp.Count == 0) break; result[k].AddRange(itemListTemp.GetRange(0, iAv)); if (i == result.Keys.Count - 1 && itemListTemp.Count / n < 2) { result[k].AddRange(itemListTemp.GetRange(iAv, itemListTemp.Count - iAv)); } itemListTemp.RemoveRange(0, iAv); i++; this.ListBox1.Items.Add(k + ":" + result[k].Count + "-->" + String.Join(",", result[k].ToArray())); //Console.WriteLine("{0}:{1}-->{2}", k, result[k].Count, String.Join(",", result[k].ToArray())); } //// //int iAverage = m / n; //int iMod = m % n; //foreach (string k in result.Keys) //{ // //int m = 4; //任务数 // //int n = 3; //分配人数 // result[k].AddRange(itemListTemp.GetRange(0, 1)); // if ((4 - 1) != 0 && (4 - 1) / n == 0) // { // } // result[k].AddRange(itemListTemp.GetRange(0, iAverage)); // if (itemListTemp.Count - iAverage != 0 && (itemListTemp.Count - iAverage) / n == 0) // { // result[k].AddRange(itemListTemp.GetRange(iAverage, itemListTemp.Count - iAverage)); // } // this.ListBox1.Items.Add(k + ":" + result[k].Count + "-->" + String.Join(",", result[k].ToArray())); // itemListTemp.RemoveRange(0, iAverage); //} }