public void CountExample() { var tree = new RedBlackTree <string, int>(); // Tree count is 0. Assert.AreEqual(0, tree.Count); // Add a cat. tree.Add(new KeyValuePair <string, int>("cat", 1)); // Tree count is 1. Assert.AreEqual(1, tree.Count); // Add a dog tree.Add(new KeyValuePair <string, int>("dog", 2)); // Tree count is 2. Assert.AreEqual(2, tree.Count); // Clear the tree - thereby removing all items contained. tree.Clear(); // Tree is empty again with 0 count. Assert.AreEqual(0, tree.Count); }
private void buttonRestoreTrees_Click(object sender, EventArgs e) { try { workingTree.Clear(); workingTree = (RedBlackTree <int>)InputOutput.LoadFromFile(GetWorkingTreeName() + ".dat"); UpdateLabelCountOfTrees(); toolStripStatusLabel1.Text = "Рабочее дерево было восстановлено"; } catch (Exception ee) { MessageBox.Show(ee.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); toolStripStatusLabel1.Text = ee.Message; UpdateLabelCountOfTrees(); } }
public void Reset() { xObjects.Clear(); EventList.Clear(); Time = 0; stop = false; }
/// <summary> ///A test for Clear ///</summary> public void ClearTestHelper <T>() { RedBlackTree <double> target = new RedBlackTree <double>(); target.Add(1); target.Add(2); target.Add(3); target.Clear(); Assert.IsNull(target.Root); }
public void TestClear() { RedBlackTree <int, string> tree = GetTestTree(); tree.Clear(); Assert.AreEqual(tree.Count, 0); Assert.AreEqual(tree.ContainsKey(40), false); Assert.AreEqual(tree.ContainsKey(41), false); }
public void ClearTest() { var target = new RedBlackTree <int, GenericParameterHelper>(); Assert.IsTrue(target.IsEmpty()); target.Add(5, new GenericParameterHelper(5)); Assert.AreEqual(1, target.Count); target.Clear(); Assert.IsTrue(target.IsEmpty()); }
public void Simple() { var redBlackTree = new RedBlackTree<int, string>(); Assert.IsTrue(redBlackTree.IsEmpty); redBlackTree = GetTestTree(); Assert.IsFalse(redBlackTree.IsEmpty); redBlackTree.Clear(); Assert.IsTrue(redBlackTree.IsEmpty); }
public void Clear() { var array = new[] { 13, 8, 17, 1, 11, 9, 15, 25, 6, 22, 27 }; var tree = new RedBlackTree <int>(); tree.AddRange(array); tree.Clear(); Assert.Equal(0, tree.Count); Assert.Null(tree.RootNode); }
/// <summary> ///A test for Clear ///</summary> ///<param name="key"> </param> ///<param name="testItem"> </param> public void ClearTestHelper <TKey, T>(TKey key, T testItem) where T : class where TKey : IComparable, IComparable <TKey>, IEquatable <TKey> { RedBlackTree <TKey, T> target = new RedBlackTree <TKey, T>(); Assert.IsTrue(target.IsEmpty()); target.Add(key, testItem); Assert.AreEqual(1, target.Count); target.Clear(); Assert.IsTrue(target.IsEmpty()); }
public void TestIsFixedSize() { RedBlackTree <int, string> tree = new RedBlackTree <int, string>(); Assert.AreEqual(tree.IsFixedSize, false); tree = GetTestTree(); Assert.AreEqual(tree.IsFixedSize, false); tree.Clear(); Assert.AreEqual(tree.IsFixedSize, false); }
public void TestIsEmpty() { RedBlackTree <int, string> tree = new RedBlackTree <int, string>(); Assert.AreEqual(tree.IsEmpty, true); tree = GetTestTree(); Assert.AreEqual(tree.IsEmpty, false); tree.Clear(); Assert.AreEqual(tree.IsEmpty, true); }
public void Simple() { var redBlackTree = new RedBlackTree <int, string>(); Assert.IsTrue(redBlackTree.IsEmpty); redBlackTree = GetTestTree(); Assert.IsFalse(redBlackTree.IsEmpty); redBlackTree.Clear(); Assert.IsTrue(redBlackTree.IsEmpty); }
public void CheckCleansingTree() { RedBlackTree <int> tree = new RedBlackTree <int>(); for (int i = 0; i < 5; i++) { tree.Insert(i); } Assert.AreEqual(false, tree.IsEmpty()); tree.Clear(); Assert.AreEqual(true, tree.IsEmpty()); }
public void CheckClear() { RedBlackTree <int, int> Tree = new RedBlackTree <int, int>(); for (int i = 0; i < 100; i++) { Tree.Add(new Node <int, int>(i, i)); Assert.IsTrue(Tree.HasItem(new Node <int, int>(i, i))); } Tree.Clear(); Assert.AreEqual(0, Tree.Count); Assert.AreEqual(null, Tree.Root); }
public void CheckIfNodeIsInvalidatedAfterClearingAndAfterRemoval() { var tree = new RedBlackTree <int>(); tree.Add(2); tree.Add(1); tree.Add(3); // Tree looks like this: // 2 // / \ // 1 3 var node1 = tree.Root.Left; var node2 = tree.Root; var node3 = tree.Root.Right; tree.Remove(2); if (node2.Left != null || node2.Right != null) { Assert.Fail("2"); } tree.Remove(3); if (node3.Left != null || node3.Right != null) { Assert.Fail("3"); } tree.Remove(1); if (node1.Left != null || node1.Right != null) { Assert.Fail("1"); } tree.Add(2); tree.Add(1); tree.Add(3); node1 = tree.Root.Left; node2 = tree.Root; node3 = tree.Root.Right; tree.Clear(); Assert.IsTrue(node1.Left == null && node1.Right == null && node2.Left == null && node2.Right == null && node3.Left == null && node3.Right == null && tree.Root == null && tree.Count == 0); }
public void IsEmptyExample() { var tree = new RedBlackTree <string, int>(); // Tree is empty. Assert.IsTrue(tree.IsEmpty); // Add a cat. tree.Add(new KeyValuePair <string, int>("cat", 1)); // Tree is not empty. Assert.IsFalse(tree.IsEmpty); // Clear the tree - thereby removing all items contained. tree.Clear(); // Tree is empty again with count = 0. Assert.IsTrue(tree.IsEmpty); }
public void RedBlackTreeRemoveTest() { // inserting and then removing elements RedBlackTree <Int32, String> tree = new RedBlackTree <Int32, String>(); String value; foreach (KeyValuePair <Int32, String> keyValuePair in this.values) { tree.Insert(keyValuePair.Key, keyValuePair.Value); tree.Height.ShouldBeLessThanOrEqualTo(20); } for (Int32 number = -1000; number < 1000; number++) { tree.Remove(number).ShouldBe(this.values.Select(keyValuePair => keyValuePair.Key).Contains(number)); tree.Height.ShouldBeLessThanOrEqualTo(20); } tree.Height.ShouldBe(-1); tree.Count.ShouldBe(0); foreach (KeyValuePair <Int32, String> keyValuePair in this.values) { tree.Insert(keyValuePair.Key, keyValuePair.Value); tree.Height.ShouldBeLessThanOrEqualTo(20); } tree.Clear(); tree.Height.ShouldBe(-1); tree.Count.ShouldBe(0); foreach (KeyValuePair <Int32, String> keyValuePair in this.values) { tree.Contains(keyValuePair.Key).ShouldBeFalse(); tree.TrySearch(keyValuePair.Key, out value).ShouldBeFalse(); } // exceptions RedBlackTree <Object, String> objectTree = new RedBlackTree <Object, String>(); Should.Throw <ArgumentNullException>(() => objectTree.Remove(null)); }
public void ClearExample() { // Create a simple tree var tree = new RedBlackTree <string, int> { new KeyValuePair <string, int>("cat", 1), new KeyValuePair <string, int>("dog", 2), new KeyValuePair <string, int>("canary", 3) }; // There should be 3 items in the tree. Assert.AreEqual(3, tree.Count); // Clear the tree tree.Clear(); // The tree should be empty. Assert.AreEqual(0, tree.Count); // No cat here.. Assert.IsFalse(tree.ContainsKey("cat")); }
public void AddingAfterClearingTree() { var tree = new RedBlackTree <int>(); int elementsCount = 100000; //Adding every seventh number, then every fifth number, //every third and at last all numbers for (int i = 7; i > 0; i -= 2) { int el = 0; while (el < elementsCount) { if (!tree.Contains(el)) { tree.Add(el); } el += i; } } if (tree.Count != elementsCount) { Assert.Fail(); } tree.Clear(); if (tree.Count != 0) { Assert.Fail(); } //Adding every seventh number, then every fifth number, //every third and at last all numbers for (int i = 7; i > 0; i -= 2) { int el = 0; while (el < elementsCount) { if (!tree.Contains(el)) { tree.Add(el); } el += i; } } int last = -1; int count = 0; bool elementsAreSorted = true; foreach (var item in tree) { if (last > item) { elementsAreSorted = false; } last = item; count++; } Assert.IsTrue(tree.Count == elementsCount && elementsAreSorted && count == elementsCount); }
/// <summary> /// Clear the dictionary. /// Time complexity: O(log(n)). /// </summary> internal void Clear() { binarySearchTree.Clear(); }
private void button3_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); Stopwatch sw = new Stopwatch(); TimeSpan slTime = TimeSpan.MinValue; TimeSpan treeTime = TimeSpan.MaxValue; //int[] testValue = new int[500000]; Random rng = new Random(); //for (int i = 0; i < testValue.Length; i++) //{ // testValue[i] = rng.Next(); //} SortedDictionary<int, int> sl = new SortedDictionary<int, int>(); RedBlackTree<int, int> tree = new RedBlackTree<int, int>(); sb.Append("1 tick = "); sb.Append((int)(1000000000d / ((double)Stopwatch.Frequency))); sb.AppendLine(" nano seconds"); sb.AppendLine(" Entries | SL in ms | RBT adj || SL ticks | RBT adj | % Time Spent"); const int MaxInsert = 100001; for (int k = 1; k < MaxInsert; k *= 10) for (int j = k; j < k * 10 && j < MaxInsert; j += k) { sl.Clear(); tree.Clear(); int rngValue = rng.Next(); sw.Start(); for (int i = 0; i < j; i++) sl[rngValue] = rngValue; sw.Stop(); slTime = sw.Elapsed; sw.Reset(); sw.Start(); for (int i = 0; i < j; i++) tree.Insert(rngValue, rngValue, true); sw.Stop(); treeTime = sw.Elapsed; sw.Reset(); sb.Append(j.ToString().PadLeft(8)); sb.Append(" |"); sb.Append(slTime.Milliseconds.ToString().PadLeft(9)); sb.Append(" |"); sb.Append((treeTime.Milliseconds - slTime.Milliseconds).ToString().PadLeft(8)); sb.Append(" ||"); sb.Append(slTime.Ticks.ToString().PadLeft(9)); sb.Append(" |"); sb.Append((treeTime.Ticks - slTime.Ticks).ToString().PadLeft(8)); sb.Append(" |"); sb.Append(((double)treeTime.Ticks / (double)slTime.Ticks * 100d).ToString("F2").PadLeft(13)); sb.AppendLine(); } tbOut.Text = sb.ToString(); }
public void ClearExample() { // Create a simple tree var tree = new RedBlackTree<string, int> { new KeyValuePair<string, int>("cat", 1), new KeyValuePair<string, int>("dog", 2), new KeyValuePair<string, int>("canary", 3) }; // There should be 3 items in the tree. Assert.AreEqual(3, tree.Count); // Clear the tree tree.Clear(); // The tree should be empty. Assert.AreEqual(0, tree.Count); // No cat here.. Assert.IsFalse(tree.ContainsKey("cat")); }
public void IsEmptyExample() { var tree = new RedBlackTree<string, int>(); // Tree is empty. Assert.IsTrue(tree.IsEmpty); // Add a cat. tree.Add(new KeyValuePair<string, int>("cat", 1)); // Tree is not empty. Assert.IsFalse(tree.IsEmpty); // Clear the tree - thereby removing all items contained. tree.Clear(); // Tree is empty again with count = 0. Assert.IsTrue(tree.IsEmpty); }
public void CountExample() { var tree = new RedBlackTree<string, int>(); // Tree count is 0. Assert.AreEqual(0, tree.Count); // Add a cat. tree.Add(new KeyValuePair<string, int>("cat", 1)); // Tree count is 1. Assert.AreEqual(1, tree.Count); // Add a dog tree.Add(new KeyValuePair<string, int>("dog", 2)); // Tree count is 2. Assert.AreEqual(2, tree.Count); // Clear the tree - thereby removing all items contained. tree.Clear(); // Tree is empty again with 0 count. Assert.AreEqual(0, tree.Count); }
private void button4_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); Stopwatch sw = new Stopwatch(); TimeSpan slTime = TimeSpan.MinValue; TimeSpan treeTime = TimeSpan.MaxValue; Random rng = new Random(); SortedDictionary<int, int> sl = new SortedDictionary<int, int>(); RedBlackTree<int, int> tree = new RedBlackTree<int, int>(); sb.Append("1 tick = "); sb.Append((int)(1000000000d / ((double)Stopwatch.Frequency))); sb.AppendLine(" nano seconds"); sb.AppendLine(" Entries | SL in ms | RBT adj || SL ticks | RBT adj | % Time Spent"); const long MaxRotations = 1000; const long MinInsert = 99999; const long MaxInsert = 100000; long[,] slData = new long[MaxInsert - MinInsert + 1, MaxRotations]; long[,] treeData = new long[MaxInsert - MinInsert + 1, MaxRotations]; double[] slData2 = new double[MaxInsert - MinInsert + 1]; double[] treeData2 = new double[MaxInsert - MinInsert + 1]; for (long j = MinInsert; j <= MaxInsert; j++) for (long k = 0L; k < MaxRotations; k++) { sl.Clear(); tree.Clear(); int rngValue = rng.Next(); sw.Start(); for (int i = 0; i < j; i++) sl[rngValue] = rngValue; sw.Stop(); slTime = sw.Elapsed; sw.Reset(); sw.Start(); for (int i = 0; i < j; i++) tree.Insert(rngValue, rngValue, true); sw.Stop(); treeTime = sw.Elapsed; sw.Reset(); slData[j - MinInsert, k] = slTime.Ticks; treeData[j - MinInsert, k] = treeTime.Ticks; } for (long j = MinInsert; j <= MaxInsert; j++) { long slSum = 0, treeSum = 0; for (int k = 0; k < MaxRotations; k++) { slSum += slData[j - MinInsert, k]; treeSum += treeData[j - MinInsert, k]; } slData2[j - MinInsert] = (double)slSum / (double)MaxRotations; treeData2[j - MinInsert] = (double)treeSum / (double)MaxRotations; } for (long j = MinInsert; j <= MaxInsert; j++) { sb.Append(j.ToString().PadLeft(8)); sb.Append(" |"); sb.Append(string.Empty.PadLeft(9)); sb.Append(" |"); sb.Append(string.Empty.PadLeft(8)); sb.Append(" ||"); sb.Append(slData2[j - MinInsert].ToString("F2").PadLeft(9)); sb.Append(" |"); sb.Append((treeData2[j - MinInsert] - slData2[j - MinInsert]).ToString("F2").PadLeft(8)); sb.Append(" |"); sb.Append((treeData2[j - MinInsert] / slData2[j - MinInsert] * 100d).ToString("F2").PadLeft(13)); sb.AppendLine(); } tbOut.Text = sb.ToString(); }
/************************************************************************ * Main() method *************************************************************************/ public static void Main(string[] args) { bool debugOn = false; if (args.Length > 0) { try { debugOn = Convert.ToBoolean(args[0]); } catch (Exception) { debugOn = false; } } RedBlackTree<PersonKey, Person> tree = new RedBlackTree<PersonKey, Person>(debugOn); tree.CollectionChanged += MainApp.CollectionChangedEventHandler; Person p1 = new Person("Deekster", "Willis", "Jaybones", Person.Sex.MALE, new DateTime(1966, 02, 19)); Person p2 = new Person("Knut", "J", "Hampson", Person.Sex.MALE, new DateTime(1972, 04, 23)); Person p3 = new Person("Katrina", "Kataline", "Kobashar", Person.Sex.FEMALE, new DateTime(1982, 09, 3)); Person p4 = new Person("Dreya", "Babe", "Weber", Person.Sex.FEMALE, new DateTime(1978, 11, 25)); Person p5 = new Person("Sam", "\"The Guitar Man\"", "Miller", Person.Sex.MALE, new DateTime(1988, 04, 16)); tree.Add(p1.Key, p1); tree.Add(p2.Key, p2); tree.Add(p3.Key, p3); tree.Add(p4.Key, p4); tree.Add(p5.Key, p5); tree.PrintTreeStats(); Console.WriteLine("Original insertion order:"); Console.WriteLine(p1); Console.WriteLine(p2); Console.WriteLine(p3); Console.WriteLine(p4); Console.WriteLine(p5); Console.WriteLine("-------------------------------------------------"); Console.WriteLine("Sorted Order:"); tree.PrintTreeToConsole(); /*********************************************** Serialize Tree with XML Serializer ***********************************************/ TextWriter writer = null; FileStream fs = null; try{ XmlSerializer serializer = new XmlSerializer(typeof(RedBlackTree<PersonKey, Person>)); writer = new StreamWriter("datafile.xml"); serializer.Serialize(writer, tree); writer.Close(); }catch(Exception e){ Console.WriteLine(e); }finally{ if(writer != null){ writer.Close(); } } Console.WriteLine("----------- Deserializing Tree -----------"); try{ XmlSerializer serializer = new XmlSerializer(typeof(RedBlackTree<PersonKey, Person>)); fs = new FileStream("datafile.xml", FileMode.Open); tree = null; tree = (RedBlackTree<PersonKey, Person>)serializer.Deserialize(fs); fs.Close(); }catch(Exception e){ Console.WriteLine(e); }finally{ if(fs != null){ fs.Close(); } } Console.WriteLine("-----------Tree after XML deserialization -----------"); tree.PrintTreeToConsole(); // Reassign the event handler because we creamated the tree during XmlSerialization above... tree.CollectionChanged += MainApp.CollectionChangedEventHandler; Person p6 = new Person("Kyle", "Victor", "Miller", Person.Sex.MALE, new DateTime(1986, 02, 19)); tree[p6.Key] = p6; tree.Remove(p4.Key); Console.WriteLine("-----------Tree after modifications -----------"); tree.PrintTreeToConsole(); tree.Clear(); } // end Main() method
private NelderMeadStatus minimize() { /* * Internal version of nldrmd_minimize, intended to be used as * a subroutine for the subplex method. Three differences compared * to nldrmd_minimize: * * minf should contain the value of f(x) (so that we don't have to * re-evaluate f at the starting x). * * if psi > 0, then it *replaces* xtol and ftol in stop with the condition * that the simplex diameter |xl - xh| must be reduced by a factor of psi * ... this is for when nldrmd is used within the subplex method; for * ordinary termination tests, set psi = 0. * * scratch should contain an array of length >= (n+1)*(n+1) + 2*n, * used as scratch workspace. * * On output, *fdiff will contain the difference between the high * and low function values of the last simplex. */ double[] x = Solution; int n = NumberOfVariables; double ninv = 1.0 / n; var ret = NelderMeadStatus.Success; double init_diam = 0; var t = new RedBlackTree <double, double[]>(allowDuplicates: true); fdiff = Double.MaxValue; // initialize the simplex based on the starting xstep Array.Copy(x, pts[0], n); val[0] = Value; if (Value < minf_max) { return(NelderMeadStatus.MinimumAllowedValueReached); } for (int i = 0; i < n; i++) { double[] pt = pts[i + 1]; Array.Copy(x, pt, x.Length); pt[i] += xstep[i]; if (pt[i] > ub[i]) { if (ub[i] - x[i] > Math.Abs(xstep[i]) * 0.1) { pt[i] = ub[i]; } else { // ub is too close to pt, go in other direction pt[i] = x[i] - Math.Abs(xstep[i]); } } if (pt[i] < lb[i]) { if (x[i] - lb[i] > Math.Abs(xstep[i]) * 0.1) { pt[i] = lb[i]; } else { // lb is too close to pt, go in other direction pt[i] = x[i] + Math.Abs(xstep[i]); if (pt[i] > ub[i]) { // go towards further of lb, ub pt[i] = 0.5 * ((ub[i] - x[i] > x[i] - lb[i] ? ub[i] : lb[i]) + x[i]); } } } if (close(pt[i], x[i])) { return(NelderMeadStatus.Failure); } val[i + 1] = Function(pt); ret = checkeval(pt, val[i + 1]); if (ret != NelderMeadStatus.Success) { return(ret); } } restart: for (int i = 0; i < n + 1; i++) { t.Add(new KeyValuePair <double, double[]>(val[i], pts[i])); } while (true) { var low = t.Min(); var high = t.Max(); double fl = low.Value.Key; double[] xl = low.Value.Value; double fh = high.Value.Key; double[] xh = high.Value.Value; double fr; fdiff = fh - fl; if (init_diam == 0) { // initialize diam for psi convergence test for (int i = 0; i < n; i++) { init_diam += Math.Abs(xl[i] - xh[i]); } } if (psi <= 0 && nlopt_stop_ftol(stop, fl, fh)) { return(NelderMeadStatus.FunctionToleranceReached); } // compute centroid ... if we cared about the performance of this, // we could do it iteratively by updating the centroid on // each step, but then we would have to be more careful about // accumulation of rounding errors... anyway n is unlikely to // be very large for Nelder-Mead in practical cases Array.Clear(c, 0, n); for (int i = 0; i < n + 1; i++) { double[] xi = pts[i]; if (xi != xh) { for (int j = 0; j < n; ++j) { c[j] += xi[j]; } } } for (int i = 0; i < n; i++) { c[i] *= ninv; } // x convergence check: find xcur = max radius from centroid Array.Clear(xcur, 0, n); for (int i = 0; i < n + 1; i++) { double[] xi = pts[i]; for (int j = 0; j < n; j++) { double dx = Math.Abs(xi[j] - c[j]); if (dx > xcur[j]) { xcur[j] = dx; } } } for (int i = 0; i < n; i++) { xcur[i] += c[i]; } if (psi > 0) { double diam = 0; for (int i = 0; i < n; i++) { diam += Math.Abs(xl[i] - xh[i]); } if (diam < psi * init_diam) { return(NelderMeadStatus.SolutionToleranceReached); } } else if (nlopt_stop_xtol(stop, c, xcur, n)) { return(NelderMeadStatus.SolutionToleranceReached); } // reflection if (!reflectpt(n, xcur, c, alpha, xh, lb, ub)) { return(NelderMeadStatus.SolutionToleranceReached); } fr = Function(xcur); ret = checkeval(xcur, fr); if (ret != NelderMeadStatus.Success) { return(ret); } if (fr < fl) { // new best point, expand simplex if (!reflectpt(n, xh, c, gamm, xh, lb, ub)) { return(NelderMeadStatus.SolutionToleranceReached); } fh = Function(xh); ret = checkeval(xh, fh); if (ret != NelderMeadStatus.Success) { return(ret); } if (fh >= fr) { // expanding didn't improve fh = fr; Array.Copy(xcur, xh, n); } } else if (fr < t.GetPreviousNode(high).Value.Key) { // accept new point Array.Copy(xcur, xh, n); fh = fr; } else { // new worst point, contract double fc; if (!reflectpt(n, xcur, c, fh <= fr ? -beta : beta, xh, lb, ub)) { return(NelderMeadStatus.SolutionToleranceReached); } fc = Function(xcur); ret = checkeval(xcur, fc); if (ret != NelderMeadStatus.Success) { return(ret); } if (fc < fr && fc < fh) { // successful contraction Array.Copy(xcur, xh, n); fh = fc; } else { // failed contraction, shrink simplex t.Clear(); for (int i = 0; i < n + 1; i++) { double[] pt = pts[i]; if (pt != xl) { if (!reflectpt(n, pt, xl, -delta, pt, lb, ub)) { return(NelderMeadStatus.SolutionToleranceReached); } val[i] = Function(pt); ret = checkeval(pt, val[i]); if (ret != NelderMeadStatus.Success) { return(ret); } } } goto restart; } } high.Value = new KeyValuePair <double, double[]>(fh, high.Value.Value); t.Resort(high); } }
public void Clear() { m_PossibleEncounters.Clear(); }
static public void Main() { // create MyObjs containing key and string data MyObj obj1 = new MyObj("MyObj 1"); MyObj obj2 = new MyObj("MyObj 2"); MyObj obj3 = new MyObj("MyObj 3"); MyObj obj4 = new MyObj("MyObj 4"); MyObj obj5 = new MyObj("MyObj 5"); MyObj obj6 = new MyObj("MyObj 6"); MyObj obj7 = new MyObj("MyObj 7"); MyObj obj8 = new MyObj("MyObj 8"); MyObj obj9 = new MyObj("MyObj 9"); MyObj obj10 = new MyObj("MyObj 10"); MyObj obj11 = new MyObj("MyObj 11"); MyObj obj12 = new MyObj("MyObj 12"); MyObj obj13 = new MyObj("MyObj 13"); try { // format: Add(key, value) RedBlackTree.Add(obj1.Data, obj1); RedBlackTree.Add(obj2.Data, obj2); RedBlackTree.Add(obj3.Data, obj3); RedBlackTree.Add(obj4.Data, obj4); RedBlackTree.Add(obj5.Data, obj5); RedBlackTree.Add(obj6.Data, obj6); RedBlackTree.Add(obj7.Data, obj7); RedBlackTree.Add(obj8.Data, obj8); RedBlackTree.Add(obj9.Data, obj9); RedBlackTree.Add(obj10.Data, obj10); RedBlackTree.Add(obj11.Data, obj11); RedBlackTree.Add(obj12.Data, obj12); RedBlackTree.Add(obj13.Data, obj13); Console.WriteLine(Environment.NewLine); IEnumerator <MyObj> items = RedBlackTree.GetEnumerator(); Enumerate(items); Console.WriteLine(Environment.NewLine); DumpMinMaxValue(); Console.WriteLine(Environment.NewLine); string tObjKey = RedBlackTree.GetMinKey(); MyObj tObj = RedBlackTree.GetData(tObjKey); Console.WriteLine(@"Remove Min Key: " + tObj.Data); Console.WriteLine(Environment.NewLine); RedBlackTree.Remove(tObjKey); Console.WriteLine(Environment.NewLine); Console.WriteLine(@"Remove Max Value:" + RedBlackTree.GetMaxValue()); RedBlackTree.RemoveMax(); Console.WriteLine(@"Remove Min Value:" + RedBlackTree.GetMinValue()); RedBlackTree.RemoveMin(); Console.WriteLine(Environment.NewLine); Console.WriteLine(Environment.NewLine); Console.WriteLine(@"Remove Min Key:" + RedBlackTree.GetMinKey()); RedBlackTree.RemoveMin(); Console.WriteLine(@"Remove Max Key:" + RedBlackTree.GetMaxKey()); RedBlackTree.RemoveMax(); Console.WriteLine(Environment.NewLine); Console.WriteLine(@"** Clearing Tree **"); RedBlackTree.Clear(); Console.WriteLine(Environment.NewLine); Console.WriteLine(@"Press enter to terminate"); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(@"Press enter to terminate"); Console.ReadLine(); } }
public void BuildSercherIndexToSQLDB(Action <double, string> IndexesProgress = null) { //hashLoadBalance.RemoveAllDBData(); //hashLoadBalance = new ConsistentHashLoadBalance(); SetServerDBCount(); RedBlackTree <string, string> documentIndices_cachList = new RedBlackTree <string, string>(); var DocumentToatalList = documentDB.GetNotIndexDocument(); int remainder = DocumentToatalList.Count; var remotewords = SercherIndexesDB.GetWords(hashLoadBalance.GetServerNodes()); var localwords = new HashSet <string>(); Dictionary <string, TextComponent> textComponent = new Dictionary <string, TextComponent>();//使用到的时候进行缓存 int curWordCachNum = 0; for (int i = 0, j = 0; i < DocumentToatalList.Count; i++) { var doc = DocumentToatalList[i]; documentDB.UpdateDocumentStateIndexStatus(doc._id, "pro_" + Config.CurrentConfig.IndexesServiceName); IEnumerable <SegmenterToken> textSplit = Pretreatment(doc); Dictionary <string, DocumentIndex> documentIndices = new Dictionary <string, DocumentIndex>(); int wordTotal = textSplit.Count(); foreach (var token in textSplit) { string word = token.Word.Trim().ToLower(); if (!remotewords.Contains(word)) { if (!localwords.Contains(word)) { localwords.Add(word); remotewords.Add(word); } } //记录一个文档的所有相同词汇 if (documentIndices.TryGetValue(word, out DocumentIndex documentIndex)) { documentIndex.WordFrequency++; if (documentIndex.WordFrequency <= Config.CurrentConfig.MaxIndexWordStartLocation) { documentIndex.BeginIndex += ',' + token.StartIndex.ToString(); } documentIndex.DocumentWordTotal = wordTotal; } else { documentIndices[word] = new DocumentIndex { IndexTime = DateTime.Now.Ticks, DocId = doc._id, WordFrequency = 1, BeginIndex = token.StartIndex.ToString(), DocumentWordTotal = wordTotal, Permission = doc.Permission == 0 ? Config.CurrentConfig.DefaultPermission : doc.Permission } }; } //转换为脚本并加入全局缓存等待上传 documentIndices.AsParallel().ForAll(kvp => { //UpdateIndex(kvp.Key, kvp.Value); if (documentIndices_cachList.ContainsKey(kvp.Key.ToString())) { string sql = InsetValueIntoMemory(kvp.Key, new DocumentIndex[1] { kvp.Value }, false); lock (lockobj1)//因为此循环内Key唯一,所以只锁了添加代码 { documentIndices_cachList[kvp.Key] += "," + sql; } } else { string sql = InsetValueIntoMemory(kvp.Key, new DocumentIndex[1] { kvp.Value }, true); lock (lockobj1) { documentIndices_cachList.Add(kvp.Key, sql); } } }); remainder--; IndexesProgress?.Invoke(i / (double)DocumentToatalList.Count, "文档:" + doc.Name + " 缓存完成"); curWordCachNum += documentIndices.Count; documentIndices.Clear(); if (Config.CurrentConfig.MaxIndexCachWordNum < curWordCachNum || i == DocumentToatalList.Count - 1) { IndexesProgress?.Invoke(i / (double)DocumentToatalList.Count, "以达缓存上限,开始创建表"); //对每一个同数据库的词汇的脚本进行组合,创建表 var group1 = localwords.GroupBy(w => hashLoadBalance.FindCloseServerDBsByTableName(w).DbName).ToArray(); System.Diagnostics.Stopwatch watch = new Stopwatch(); watch.Start(); Parallel.ForEach(group1, g => { var wordgroup = g.ToArray(); hashLoadBalance.GetServerNodes().First(n => n.DbName == g.Key) //!##GroupKey欠妥,不过数据库比较少的时候影响不大 .CreateIndexTable(wordgroup); IndexesProgress?.Invoke(i / (double)DocumentToatalList.Count, g.Key + ":一组表创建完成"); }); watch.Stop(); IndexesProgress?.Invoke(i / (double)DocumentToatalList.Count, "表创建完成,用时(s):" + watch.ElapsedMilliseconds / 1000); localwords.Clear(); IndexesProgress?.Invoke(i / (double)DocumentToatalList.Count, "开始上传索引"); //对每一个同数据库的词汇的脚本进行组合,上传 var group2 = documentIndices_cachList.AsQueryable().GroupBy(kv => hashLoadBalance.FindCloseServerDBsByTableName(kv.Key).DbName).ToArray(); watch.Restart(); Parallel.ForEach(group2, new ParallelOptions() { MaxDegreeOfParallelism = Config.CurrentConfig.UploadThreadNum }, g => { //上传此db的inser脚本 hashLoadBalance.FindCloseServerDBsByTableName(g.First().Key) .UploadDocumentIndex(g.Select(s => s.Value + ";").ToArray()); IndexesProgress?.Invoke(i / (double)DocumentToatalList.Count, g.Key + ":一组索引创建完成"); }); watch.Stop(); IndexesProgress?.Invoke(i / (double)DocumentToatalList.Count, "上传索引完成,用时(s):" + watch.ElapsedMilliseconds / 1000); documentIndices_cachList.Clear(); while (j <= i) { documentDB.UpdateDocumentStateIndexStatus(DocumentToatalList[j]._id, "yes"); j++; } curWordCachNum = 0; IndexesProgress?.Invoke(i / (double)DocumentToatalList.Count, "一批上传完成,刷新缓存"); } } }