算法的复杂度就降低为 O(n) ,速度大大提高。
需求:前后数据x条不动,中间随机删除N条记录
实现:
DictionarydictA = GetArrayListFromTxt(this.txtFileNameA.Text);Dictionary dictB = GetArrayListFromTxt(this.txtFileNameB.Text);Dictionary dictC= new Dictionary ();StringBuilder sb=new StringBuilder();foreach (var item in dictB){if (dictA.ContainsKey(item.Key)){dictA.Remove(item.Key);dictC.Add(item.Key, item.Value);sb.AppendLine(item.Key);}}textBox1.Text = sb.ToString();txtRepeatNum.Text = Convert.ToString(dictC.Count );foreach (object key in RandomValues(dictA,x).Take(n)){dictA.Remove(key.ToString());}
算法:
public static IEnumerableRandomValues (IDictionary dict,int num){List list = Enumerable.ToList( dict.Select(k=>k.Key).Skip(Convert.ToInt32(num)).Take(dict.Count - num * 2));Random rand = new Random();while (list.Count > 0){var point = rand.Next(0, list.Count);var rv = list[point];list[point] = list[list.Count - 1];list.RemoveAt(list.Count - 1);yield return rv;}}