Exemplo n.º 1
0
 private SetHashList(SetHashList <T> setHashList)
 {
     this._equate = setHashList._equate;
     this._hash   = setHashList._hash;
     this._table  = setHashList._table.Clone() as Node[];
     this._count  = setHashList._count;
 }
Exemplo n.º 2
0
 public void Clear()
 {
     this._nodes = new SetHashList <T>(this._nodes.Equate, this._nodes.Hash);
     this._edges = new OmnitreeLinked <Edge, T>(
         new T[] { this._edges.Min(0), this._edges.Min(1) },
         new T[] { this._edges.Max(0), this._edges.Max(1) },
         this._edges.Locate, this._edges.Compare, this._edges.Average);
 }
Exemplo n.º 3
0
 public GraphSetOmnitree(Equate <T> equate, Compare <T> compare, Hash <T> hash, T min, T max, Omnitree.Average <T> average)
 {
     this._nodes = new SetHashList <T>(equate, hash);
     Omnitree.Locate <Edge, T> locationFunction = (Edge a) => { return(Accessor.Get(new T[] { a.Start, a.End })); };
     this._edges = new OmnitreeLinked <Edge, T>(
         new T[] { min, min },
         new T[] { max, max },
         locationFunction, compare, average);
 }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            Random random = new Random();
            int    test   = 10;

            Console.WriteLine("You are runnning the Data Structures example.");
            Console.WriteLine("======================================================");
            Console.WriteLine();

            #region Link

            Console.WriteLine("  Testing Link-------------------------------");
            Console.WriteLine("   Size: 6");
            Link link = new Link <int, int, int, int, int, int>(0, 1, 2, 3, 4, 5);
            Console.Write("    Traversal: ");
            link.Stepper((dynamic current) => { Console.Write(current); });
            Console.WriteLine();
            // Saving to a file
            //string linklink_file = "link." + ToExtension(link.GetType());
            //Console.WriteLine("    File: \"" + linklink_file + "\"");
            //Console.WriteLine("    Serialized: " + Serialize(linklink_file, link));
            //Link<int, int, int, int, int, int> deserialized_linklink;
            //Console.WriteLine("    Deserialized: " + Deserialize(linklink_file, out deserialized_linklink));
            Console.WriteLine();

            #endregion

            #region Array

            Console.WriteLine("  Testing Array_Array<int>-------------------");
            Indexed <int> array = new IndexedArray <int>(test);
            for (int i = 0; i < test; i++)
            {
                array[i] = i;
            }
            Console.Write("    Traversal: ");
            array.Stepper((int current) => { Console.Write(current); });
            Console.WriteLine();
            // Saving to a file
            //string arrayarray_file = "array." + ToExtension(array.GetType());
            //Console.WriteLine("    File: \"" + arrayarray_file + "\"");
            //Console.WriteLine("    Serialized: " + Serialize(arrayarray_file, array));
            //ArrayArray<int> deserialized_arrayarray;
            //Console.WriteLine("    Deserialized: " + Deserialize(arrayarray_file, out deserialized_arrayarray));
            Console.WriteLine();

            #endregion

            #region List

            Console.WriteLine("  Testing List_Array<int>--------------------");
            Addable <int> list_array = new AddableArray <int>(test);
            for (int i = 0; i < test; i++)
            {
                list_array.Add(i);
            }
            Console.Write("    Traversal: ");
            list_array.Stepper((int current) => { Console.Write(current); });
            Console.WriteLine();
            //string list_array_serialization = (list_array as ListArray<int>).Serialize(x => x.ToString());
            //using (StreamWriter writer = new StreamWriter("ListArray.ListArray"))
            //{
            //    writer.WriteLine(list_array_serialization);
            //}
            //using (StreamReader reader = new StreamReader("ListArray.ListArray"))
            //{
            //    list_array = ListArray<int>.Deserialize(reader.ReadToEnd(), x => Int16.Parse(x.Trim()));
            //}
            //Console.Write("    Serialization/Deserialization is possible.");
            list_array.Add(11);
            list_array.Remove(7);
            Console.WriteLine();
            Console.WriteLine();


            //ListArray<ListArray<int>> list_array2 = new ListArray<ListArray<int>>(test);
            //for (int i = 0; i < test; i++)
            //{
            //    ListArray<int> nested_list = new ListArray<int>();
            //    for (int j = 0; j < test; j++)
            //    {
            //        nested_list.Add(j);
            //    }
            //    list_array2.Add(nested_list);
            //}
            //string list_array2_serialization = list_array2.Serialize(x => x.Serialize(y => y.ToString()));
            //using (StreamWriter writer = new StreamWriter("ListArray2.ListArray"))
            //{
            //    writer.WriteLine(list_array2_serialization);
            //}
            //using (StreamReader reader = new StreamReader("ListArray2.ListArray"))
            //{
            //    list_array2 = ListArray<ListArray<int>>.Deserialize(reader.ReadToEnd(), x => ListArray<int>.Deserialize(x, y => Int16.Parse(y.Trim())));
            //}

            Console.WriteLine("  Testing List_Linked<int>-------------------");
            Addable <int> list_linked = new AddableLinked <int>();
            for (int i = 0; i < test; i++)
            {
                list_linked.Add(i);
            }
            Console.Write("    Traversal: ");
            list_linked.Stepper((int current) => { Console.Write(current); });
            Console.WriteLine();



            // Saving to a file
            //string listlinked_file = "list_linked." + ToExtension(list_linked.GetType());
            //Console.WriteLine("    File: \"" + listlinked_file + "\"");
            //Console.WriteLine("    Serialized: " + Serialize(listlinked_file, list_linked));
            //ListLinked<int> deserialized_listlinked;
            //Console.WriteLine("    Deserialized: " + Deserialize(listlinked_file, out deserialized_listlinked));
            Console.WriteLine();

            #endregion

            #region Stack

            Console.WriteLine("  Testing Stack_Linked<int>------------------");
            FirstInLastOut <int> stack_linked = new FirstInLastOutLinked <int>();
            for (int i = 0; i < test; i++)
            {
                stack_linked.Push(i);
            }
            Console.Write("    Traversal: ");
            stack_linked.Stepper((int current) => { Console.Write(current); });
            Console.WriteLine();
            // Saving to a file
            //string stacklinked_file = "stack_linked." + ToExtension(stack_linked.GetType());
            //Console.WriteLine("    File: \"" + stacklinked_file + "\"");
            //Console.WriteLine("    Serialized: " + Serialize(stacklinked_file, stack_linked));
            //StackLinked<int> deserialized_stacklinked;
            //Console.WriteLine("    Deserialized: " + Deserialize(stacklinked_file, out deserialized_stacklinked));
            Console.WriteLine();

            #endregion

            #region Queue

            Console.WriteLine("  Testing Queue_Linked<int>------------------");
            FirstInFirstOut <int> queue_linked = new FirstInFirstOutLinked <int>();
            for (int i = 0; i < test; i++)
            {
                queue_linked.Enqueue(i);
            }
            Console.Write("    Traversal: ");
            queue_linked.Stepper((int current) => { Console.Write(current); });
            Console.WriteLine();
            // Saving to a file
            //string queuelinked_file = "queue_linked." + ToExtension(queue_linked.GetType());
            //Console.WriteLine("    File: \"" + queuelinked_file + "\"");
            //Console.WriteLine("    Serialized: " + Serialize(queuelinked_file, queue_linked));
            //QueueLinked<int> deserialized_queuelinked;
            //Console.WriteLine("    Deserialized: " + Deserialize(queuelinked_file, out deserialized_queuelinked));
            Console.WriteLine();

            #endregion

            #region Heap

            Console.WriteLine("  Testing Heap_Array<int>--------------------");
            Heap <int> heap_array = new HeapArray <int>(Compute.Compare);
            for (int i = 0; i < test; i++)
            {
                heap_array.Enqueue(i);
            }
            Console.Write("    Delegate: ");
            heap_array.Stepper((int current) => { Console.Write(current); });
            Console.WriteLine();
            // Saving to a file
            //string heaplinked_file = "heap_array." + ToExtension(heap_array.GetType());
            //Console.WriteLine("    File: \"" + heaplinked_file + "\"");
            //Console.WriteLine("    Serialized: " + Serialize(heaplinked_file, heap_array));
            //HeapArray<int> deserialized_heaplinked;
            //Console.WriteLine("    Deserialized: " + Deserialize(heaplinked_file, out deserialized_heaplinked));
            Console.WriteLine();

            #endregion

            #region Tree

            Console.WriteLine("  Testing Tree_Map<int>----------------------");
            Tree <int> tree_Map = new TreeMap <int>(0, Compute.Equal, Hash.Default);
            for (int i = 1; i < test; i++)
            {
                tree_Map.Add(i, i / (int)System.Math.Sqrt(test));
            }
            Console.Write("    Children of 0 (root): ");
            tree_Map.Children(0, (int i) => { Console.Write(i + " "); });
            Console.WriteLine();
            Console.Write("    Children of " + ((int)System.Math.Sqrt(test) - 1) + " (root): ");
            tree_Map.Children(((int)System.Math.Sqrt(test) - 1), (int i) => { Console.Write(i + " "); });
            Console.WriteLine();
            Console.Write("    Traversal: ");
            tree_Map.Stepper((int i) => { Console.Write(i + " "); });
            Console.WriteLine();
            // Saving to a file
            //string treelinked_file = "tree_Map." + ToExtension(tree_Map.GetType());
            //Console.WriteLine("    File: \"" + treelinked_file + "\"");
            //Console.WriteLine("    Serialized: " + Serialize(treelinked_file, tree_Map));
            //TreeMap<int> deserialized_treelinked;
            //Console.WriteLine("    Deserialized: " + Deserialize(treelinked_file, out deserialized_treelinked));
            Console.WriteLine();

            #endregion

            #region AVL Tree

            //Console.WriteLine("  Testing AvlTree_Linked<int>----------------");
            //// Construction
            //AvlTree<int> avlTree_linked = new AvlTree_Linked<int>(Logic.compare);
            //// Adding Items
            //Console.Write("    Adding (0-" + test + ")...");
            //for (int i = 0; i < test; i++)
            //	avlTree_linked.Add(i);
            //Console.WriteLine();
            //// Iteration
            //Console.Write("    Traversal: ");
            //avlTree_linked.Stepper((int current) => { Console.Write(current); });
            //Console.WriteLine();
            //// Removal
            //int avl_tree_linked_removal = random.Next(0, test);
            //avlTree_linked.Remove(avl_tree_linked_removal);
            //Console.Write("    Remove(" + avl_tree_linked_removal + "): ");
            //avlTree_linked.Stepper((int current) => { Console.Write(current); });
            //Console.WriteLine();
            //// Look Up Items
            //int avl_tree_linked_lookup = random.Next(0, test);
            //while (avl_tree_linked_lookup == avl_tree_linked_removal)
            //	avl_tree_linked_lookup = random.Next(0, test);
            //Console.WriteLine("    Look Up (" + avl_tree_linked_lookup + "): " + avlTree_linked.TryGet(avl_tree_linked_lookup, Logic.compare, out temp));
            //Console.WriteLine("    Look Up (" + avl_tree_linked_removal + "): " + avlTree_linked.TryGet(avl_tree_linked_removal, Logic.compare, out temp));
            //avlTree_linked.Get(avl_tree_linked_lookup, Logic.compare);
            //// Current Min-Max Values
            //Console.WriteLine("    Least: " + avlTree_linked.CurrentLeast + " Greatest: " + avlTree_linked.CurrentGreatest);
            //// Saving to a file
            //string avltreelinked_file = "avlTree_linked." + ToExtension(avlTree_linked.GetType());
            //Console.WriteLine("    File: \"" + avltreelinked_file + "\"");
            //Console.WriteLine("    Serialized: " + Serialize(avltreelinked_file, avlTree_linked));
            //AvlTree_Linked<int> deserialized_avltreelinked;
            //Console.WriteLine("    Deserialized: " + Deserialize(avltreelinked_file, out deserialized_avltreelinked));
            //Console.WriteLine();

            #endregion

            #region Red-Black Tree

            Console.WriteLine("  Testing RedBlack_Linked<int>---------------");
            RedBlackTree <int> redBlackTree_linked = new RedBlackTreeLinked <int>(Compute.Compare);
            for (int i = 0; i < test; i++)
            {
                redBlackTree_linked.Add(i);
            }
            Console.Write("    Traversal: ");
            redBlackTree_linked.Stepper((int current) => { Console.Write(current); });
            Console.WriteLine();
            // Saving to a file
            //string redblacktreelinked_file = "redBlackTree_linked." + ToExtension(redBlackTree_linked.GetType());
            //Console.WriteLine("    File: \"" + redblacktreelinked_file + "\"");
            //Console.WriteLine("    Serialized: " + Serialize(redblacktreelinked_file, redBlackTree_linked));
            //RedBlackTreeLinked<int> deserialized_redblacktreelinked;
            //Console.WriteLine("    Deserialized: " + Deserialize(redblacktreelinked_file, out deserialized_redblacktreelinked));
            Console.WriteLine();

            #endregion

            #region BTree

            //Console.WriteLine("  Testing BTree_LinkedArray<int>-------------");
            //BTree<int> btree_linked = new BTree_LinkedArray<int>(Logic.compare, 3);
            //for (int i = 0; i < test; i++)
            //	btree_linked.Add(i);
            //Console.Write("    Delegate: ");
            //btree_linked.Stepper((int current) => { Console.Write(current); });
            //Console.WriteLine();
            //Console.Write("    IEnumerator: ");
            //foreach (int current in btree_linked)
            //	Console.Write(current);
            //Console.WriteLine();
            //Console.WriteLine("  Press Enter to continue...");
            //string maplinked_file = "maplinked.quad";
            //Console.WriteLine("    File: \"" + maplinked_file + "\"");
            //Console.WriteLine("    Serialized: " + Serialize(maplinked_file, hashTable_linked));
            //Omnitree_LinkedLinkedLists<int, double> deserialized_maplinked;
            //Console.WriteLine("    Deserialized: " + Deserialize(maplinked_file, out deserialized_maplinked));
            //Console.ReadLine();
            //Console.WriteLine();

            #endregion

            #region Set

            Console.WriteLine("  Testing Set_Hash<int>----------------------");
            Set <int> set_linked = new SetHashList <int>(Compute.Equal, Hash.Default);
            for (int i = 0; i < test; i++)
            {
                set_linked.Add(i);
            }
            // Traversal
            Console.Write("    Traversal: ");
            set_linked.Stepper((int current) => { Console.Write(current); });
            Console.WriteLine();
            Console.Write("    Table Size: " + (set_linked as SetHashList <int>).TableSize);
            Console.WriteLine();
            Console.WriteLine();

            #endregion

            #region Map

            Console.WriteLine("  Testing MapHashList<int, int>--------------");
            Map <int, int> map_sethash = new MapHashLinked <int, int>(Compute.Equal, Hash.Default);
            for (int i = 0; i < test; i++)
            {
                map_sethash.Add(i, i);
            }
            Console.Write("    Look Ups: ");
            for (int i = 0; i < test; i++)
            {
                Console.Write(map_sethash[i]);
            }
            Console.WriteLine();
            // Traversal
            Console.Write("    Traversal: ");
            map_sethash.Stepper((int current) => { Console.Write(current); });
            Console.WriteLine();
            Console.Write("    Table Size: " + (map_sethash as MapHashLinked <int, int>).TableSize);
            Console.WriteLine();
            Console.WriteLine();

            #endregion

            #region OmnitreePoints
            {
                Console.WriteLine("  Testing OmnitreeLinkedLinked<int, double>-------");
                // Construction
                OmnitreePoints <int, double, double, double> omnitree_linked = new OmnitreePointsLinked <int, double, double, double>(
                    (int index, out double a, out double b, out double c) => { a = index; b = index; c = index; }); // axis average function
                                                                                                                    // Properties
                Console.WriteLine("      Dimensions: " + omnitree_linked.Dimensions);
                Console.WriteLine("      Count: " + omnitree_linked.Count);
                // Addition
                Console.Write("    Adding 0-" + test + ": ");
                for (int i = 0; i < test; i++)
                {
                    omnitree_linked.Add(i);
                }
                omnitree_linked.Stepper((int current) => { Console.Write(current); });
                Console.WriteLine();
                Console.WriteLine("      Count: " + omnitree_linked.Count);
                // Traversal
                Console.Write("    Traversal [ALL]: ");
                omnitree_linked.Stepper((int current) => { Console.Write(current); });
                Console.WriteLine();
                // Look Up 1
                Console.Write("    Traversal [(" + (test / 2) + ", " + (test / 2) + ", " + (test / 2) + ")->(" + test + ", " + test + ", " + test + ")]: ");
                omnitree_linked.Stepper((int current) => { Console.Write(current); },
                                        test / 2, test,
                                        test / 2, test,
                                        test / 2, test);
                Console.WriteLine();
                // Look Up 2
                Console.Write("    Look Up [" + (test / 3) + ", " + (test / 3) + ", " + (test / 3) + "]: ");
                omnitree_linked[(test / 3), (test / 3), (test / 3)]((int current) => { Console.Write(current); });
                Console.WriteLine();
                // Removal
                Console.Write("    Remove 0-" + test / 3 + ": ");
                omnitree_linked.Remove(
                    0, test / 3,
                    0, test / 3,
                    0, test / 3);
                omnitree_linked.Stepper((int current) => { Console.Write(current); });
                Console.WriteLine();
                Console.WriteLine("      Count: " + omnitree_linked.Count);
                // Clear
                Console.Write("    Clear: ");
                omnitree_linked.Clear();
                omnitree_linked.Stepper((int current) => { Console.Write(current); });
                Console.WriteLine();
                Console.WriteLine("      Count: " + omnitree_linked.Count);
                // Saving to a file
                //string omnitreelinked_file = "omnitree_linkedlinkedlists." + ToExtension(omnitree_linked.GetType());
                //Console.WriteLine("    File: \"" + omnitreelinked_file + "\"");
                //Console.WriteLine("    Serialized: " + Serialize(omnitreelinked_file, omnitree_linked));
                //OmnitreeLinkedLinkedLists<int, double> deserialized_omnitreeLinked;
                //Console.WriteLine("    Deserialized: " + Deserialize(omnitreelinked_file, out deserialized_omnitreeLinked));
                Console.WriteLine();

                //Console.WriteLine("  Testing Omnitree_LinkedArrayLists<int, double>--------");
                //// Construction
                //Omnitree<int, double> omnitree_array = new OmnitreeLinkedArray<int, double>(
                //	new double[] { -test - 1, -test - 1, -test - 1 }, // minimum dimensions of the omnitree
                //	new double[] { test + 1, test + 1, test + 1 }, // maximum dimensions of the omnitree
                //	(int index) => { return Accessor.Get(new double[] { index, index, index }); }, // "N-D" location function
                //	Compute<double>.Compare, // comparison function
                //	(double a, double b) => { return (a + b) / 2; }); // average function
                //// Properties
                //Console.WriteLine("      Origin: [" + omnitree_array.Origin(0) + ", " + omnitree_array.Origin(1) + ", " + omnitree_array.Origin(2) + "]");
                //Console.WriteLine("      Minimum: [" + omnitree_array.Min(0) + ", " + omnitree_array.Min(1) + ", " + omnitree_array.Min(2) + "]");
                //Console.WriteLine("      Maximum: [" + omnitree_array.Max(0) + ", " + omnitree_array.Max(1) + ", " + omnitree_array.Max(2) + "]");
                //Console.WriteLine("      Dimensions: " + omnitree_array.Dimensions);
                //Console.WriteLine("      Count: " + omnitree_array.Count);
                //// Addition
                //Console.Write("    Adding 0-" + test + ": ");
                //for (int i = 0; i < test; i++)
                //	omnitree_array.Add(i);
                //omnitree_array.Stepper((int current) => { Console.Write(current); });
                //Console.WriteLine();
                //Console.WriteLine("      Count: " + omnitree_array.Count);
                //// Traversal
                //Console.Write("    Traversal [ALL]: ");
                //			omnitree_array.Stepper((int current) => { Console.Write(current); });
                //Console.WriteLine();
                //// Look Up
                //Console.Write("    Traversal [" + (test / 2) + "-" + test + "]: ");
                //			omnitree_array.Stepper((int current) => { Console.Write(current); },
                //	new double[] { test / 2, test / 2, test / 2 },
                //	new double[] { test, test, test });
                //Console.WriteLine();
                //// Removal
                //Console.Write("    Remove 0-" + test / 3 + ": ");
                //omnitree_array.Remove(
                //	new double[] { 0, 0, 0 },
                //	new double[] { test / 3, test / 3, test / 3 });
                //omnitree_array.Stepper((int current) => { Console.Write(current); });
                //Console.WriteLine();
                //Console.WriteLine("      Count: " + omnitree_array.Count);
                //// Clear
                //Console.Write("    Clear: ");
                //omnitree_array.Clear();
                //			omnitree_array.Stepper((int current) => { Console.Write(current); });
                //Console.WriteLine();
                //Console.WriteLine("      Count: " + omnitree_array.Count);
                //// Saving to a file
                ////string omnitreearray_file = "omnitree_linkedarraylists." + ToExtension(omnitree_array.GetType());
                ////Console.WriteLine("    File: \"" + omnitreearray_file + "\"");
                ////Console.WriteLine("    Serialized: " + Serialize(omnitreearray_file, omnitree_array));
                ////OmnitreeLinkedLinkedLists<int, double> deserialized_omnitreearray;
                ////Console.WriteLine("    Deserialized: " + Deserialize(omnitreearray_file, out deserialized_omnitreearray));
                //Console.WriteLine();
            }
            #endregion

            #region OmnitreeBounds
            {
                Console.WriteLine("  Testing OmnitreeBoundsLinked<int, double>-------");
                // Construction
                OmnitreeBounds <int, double, double, double> omnitreeBounds_linked = new OmnitreeBoundsLinked <int, double, double, double>(
                    (int index,
                     out double min1, out double max1,
                     out double min2, out double max2,
                     out double min3, out double max3) =>
                {
                    min1 = index; max1 = index;
                    min2 = index; max2 = index;
                    min3 = index; max3 = index;
                });

                // Properties
                Console.WriteLine("      Dimensions: " + omnitreeBounds_linked.Dimensions);
                Console.WriteLine("      Count: " + omnitreeBounds_linked.Count);

                // Addition
                Console.Write("    Adding 0-" + test + ": ");
                for (int i = 0; i < test; i++)
                {
                    omnitreeBounds_linked.Add(i);
                }
                omnitreeBounds_linked.Stepper((int current) => { Console.Write(current); });
                Console.WriteLine();
                Console.WriteLine("      Count: " + omnitreeBounds_linked.Count);
                // Traversal
                Console.Write("    Traversal [ALL]: ");
                omnitreeBounds_linked.Stepper((int current) => { Console.Write(current); });
                Console.WriteLine();
                // Look Up 1
                //Console.Write("    Traversal [(" + (test / 2) + ", " + (test / 2) + ", " + (test / 2) + ")->(" + test + ", " + test + ", " + test + ")]: ");
                //omnitreeBounds_linked.Stepper((int current) => { Console.Write(current); },
                //    test / 2, test,
                //    test / 2, test,
                //    test / 2, test);
                //Console.WriteLine();
                // Removal
                Console.Write("    Remove 0-" + test / 3 + ": ");
                omnitreeBounds_linked.RemoveOverlapped(
                    0, test / 3,
                    0, test / 3,
                    0, test / 3);
                omnitreeBounds_linked.Stepper((int current) => { Console.Write(current); });
                Console.WriteLine();
                Console.WriteLine("      Count: " + omnitreeBounds_linked.Count);
                // Clear
                Console.Write("    Clear: ");
                omnitreeBounds_linked.Clear();
                omnitreeBounds_linked.Stepper((int current) => { Console.Write(current); });
                Console.WriteLine();
                Console.WriteLine("      Count: " + omnitreeBounds_linked.Count);
                Console.WriteLine();
            }
            #endregion

            #region KD Tree

            ////List<KdTreeNode<float, string>> testNodes = new List_Linked<KdTreeNode<float, string>>();
            //KdTree_Linked<string, float> tree = new KdTree_Linked<string, float>(
            //	2,
            //	Logic.compare,
            //	float.MinValue,
            //	float.MaxValue,
            //	0,
            //	Arithmetic.Add,
            //	Arithmetic.Subtract,
            //	Arithmetic.Multiply);

            //List<KdTree_Linked<string, float>.Node> testNodes =
            //	new List_Linked<KdTree_Linked<string, float>.Node>
            //{
            //	new KdTree_Linked<string, float>.Node(new float[] { 5, 5 }, "Root"),
            //	new KdTree_Linked<string, float>.Node(new float[] { 2.5f, 2.5f }, "Root-Left"),
            //	new KdTree_Linked<string, float>.Node(new float[] { 7.5f, 7.5f }, "Root-Right"),
            //	new KdTree_Linked<string, float>.Node(new float[] { 1, 10 }, "Root-Left-Left"),
            //	new KdTree_Linked<string, float>.Node(new float[] { 10, 10 }, "Root-Right-Right")
            //};

            //foreach (var node in testNodes)
            //	if (!tree.Add(node.Point, node.Value))
            //		throw new Exception("Failed to add node to tree");

            //var nodesToRemove = new KdTreeNode<float, string>[] {
            //	testNodes[1], // Root-Left
            //	testNodes[0] // Root
            //};

            //foreach (var nodeToRemove in nodesToRemove)
            //{
            //	tree.RemoveAt(nodeToRemove.Point);
            //	testNodes.Remove(nodeToRemove);

            //	Assert.IsNull(tree.FindValue(nodeToRemove.Value));
            //	Assert.IsNull(tree.FindValueAt(nodeToRemove.Point));

            //	foreach (var testNode in testNodes)
            //	{
            //		Assert.AreEqual(testNode.Value, tree.FindValueAt(testNode.Point));
            //		Assert.AreEqual(testNode.Point, tree.FindValue(testNode.Value));
            //	}

            //	Assert.AreEqual(testNodes.Count, tree.Count);
            //}

            #endregion

            #region Graph

            Console.WriteLine("  Testing Graph_SetOmnitree<int>-------------");
            Graph <int> graph = new GraphSetOmnitree <int>(Compute.Equal, Compute.Compare, Hash.Default);
            // add nodes
            for (int i = 0; i < test; i++)
            {
                graph.Add(i);
            }
            // add edges
            for (int i = 0; i < test - 1; i++)
            {
                graph.Add(i, i + 1);
            }
            Console.Write("    Traversal: ");
            graph.Stepper((int current) => { Console.Write(current); });
            Console.WriteLine();
            Console.WriteLine("    Edges: ");
            //((Graph_SetQuadtree<int>)graph)._edges.Foreach((Graph_SetQuadtree<int>.Edge e) => { Console.WriteLine("     " + e.Start + " " + e.End); });
            graph.Stepper(
                (int current) =>
            {
                Console.Write("     " + current + ": ");
                graph.Neighbors(current,
                                (int a) =>
                {
                    Console.Write(a);
                });
                Console.WriteLine();
            });
            Console.WriteLine();

            #endregion

            Console.WriteLine("============================================");
            Console.WriteLine("Examples Complete...");
            Console.ReadLine();
        }
Exemplo n.º 5
0
 public GraphSetOmnitree(Compare <T> compare, Hash <T> hash)
 {
     this._nodes = new SetHashList <T>((T a, T b) => { return(compare(a, b) == Comparison.Equal); }, hash);
     this._edges = new OmnitreePointsLinked <Edge, T, T>((Edge a, out T start, out T end) => { start = a.Start; end = a.End; });
 }
Exemplo n.º 6
0
 public GraphSetOmnitree(Equate <T> equate, Compare <T> compare, Hash <T> hash)
 {
     this._nodes = new SetHashList <T>(equate, hash);
     this._edges = new OmnitreePointsLinked <Edge, T, T>((Edge a, out T start, out T end) => { start = a.Start; end = a.End; });
 }
Exemplo n.º 7
0
 private GraphSetOmnitree(GraphSetOmnitree <T> graph)
 {
     this._edges = graph._edges.Clone() as OmnitreePointsLinked <Edge, T, T>;
     this._nodes = graph._nodes.Clone() as SetHashList <T>;
 }
Exemplo n.º 8
0
 public NodeData(T parent, SetHashList <T> children)
 {
     this._parent   = parent;
     this._children = children;
 }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            Console.WriteLine("You are runnning the Algorithms tutorial.");
            Console.WriteLine("======================================================");
            Console.WriteLine();

            #region Sorting
            {
                Console.WriteLine(" Sorting Algorithms----------------------");
                Console.WriteLine();
                int[] dataSet = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
                Console.Write("  Data Set:");
                Console.Write(dataSet[0]);
                for (int i = 1; i < dataSet.Length; i++)
                {
                    Console.Write(", " + dataSet[i]);
                }
                Console.WriteLine();

                // if you want to sort non-array types, see the overloads using Get<int> and Assign<int>
                // Delegates
                //Get<int> get = (int index) => { return dataSet[index]; };
                //Assign<int> assign = (int index, int value) => { dataSet[index] = value; };

                // Shuffling (Randomizing)
                Sort <int> .Shuffle(dataSet);

                Console.Write("  Shuffle (Randomizing): ");
                Console.Write(dataSet[0]);
                for (int i = 1; i < dataSet.Length; i++)
                {
                    Console.Write(", " + dataSet[i]);
                }
                Console.WriteLine();

                // Bubble
                Sort <int> .Bubble(dataSet);

                Console.Write("  Bubble: ");
                Console.Write(dataSet[0]);
                for (int i = 1; i < dataSet.Length; i++)
                {
                    Console.Write(", " + dataSet[i]);
                }
                Console.WriteLine();

                Console.WriteLine("  shuffling dataSet...");
                Sort <int> .Shuffle(dataSet);

                // Selection
                Sort <int> .Selection(dataSet);

                Console.Write("  Selection: ");
                Console.Write(dataSet[0]);
                for (int i = 1; i < dataSet.Length; i++)
                {
                    Console.Write(", " + dataSet[i]);
                }
                Console.WriteLine();

                Console.WriteLine("  shuffling dataSet...");
                Sort <int> .Shuffle(dataSet);

                // Insertion
                Sort <int> .Insertion(dataSet);

                Console.Write("  Insertion: ");
                Console.Write(dataSet[0]);
                for (int i = 1; i < dataSet.Length; i++)
                {
                    Console.Write(", " + dataSet[i]);
                }
                Console.WriteLine();

                Console.WriteLine("  shuffling dataSet...");
                Sort <int> .Shuffle(dataSet);

                // Quick
                Sort <int> .Quick(dataSet);

                Console.Write("  Quick: ");
                Console.Write(dataSet[0]);
                for (int i = 1; i < dataSet.Length; i++)
                {
                    Console.Write(", " + dataSet[i]);
                }
                Console.WriteLine();

                Console.WriteLine("  shuffling dataSet...");
                Sort <int> .Shuffle(dataSet);

                // Merge
                Sort <int> .Merge(Compute.Compare, dataSet);

                Console.Write("  Merge: ");
                Console.Write(dataSet[0]);
                for (int i = 1; i < dataSet.Length; i++)
                {
                    Console.Write(", " + dataSet[i]);
                }
                Console.WriteLine();

                Console.WriteLine("  shuffling dataSet...");
                Sort <int> .Shuffle(dataSet);

                // Heap
                Sort <int> .Heap(Compute.Compare, dataSet);

                Console.Write("  Heap: ");
                Console.Write(dataSet[0]);
                for (int i = 1; i < dataSet.Length; i++)
                {
                    Console.Write(", " + dataSet[i]);
                }
                Console.WriteLine();

                Console.WriteLine("  shuffling dataSet...");
                Sort <int> .Shuffle(dataSet);

                // OddEven
                Sort <int> .OddEven(Compute.Compare, dataSet);

                Console.Write("  OddEven: ");
                Console.Write(dataSet[0]);
                for (int i = 1; i < dataSet.Length; i++)
                {
                    Console.Write(", " + dataSet[i]);
                }
                Console.WriteLine();

                //Sort<int>.Shuffle(get, set, 0, dataSet.Length);

                //// Slow
                //Sort<int>.Slow(Logic.compare, get, set, 0, dataSet.Length);
                //Console.Write("Slow: ");
                //Console.Write(dataSet[0]);
                //for (int i = 1; i < dataSet.Length; i++)
                //	Console.Write(", " + dataSet[i]);
                //Console.WriteLine();

                Sort <int> .Shuffle(dataSet);

                // Bogo
                //Sort<int>.Bogo(Logic.compare, get, set, 0, dataSet.Length);
                Console.Write("  Bogo: Disabled (takes forever)");
                //Console.Write(dataSet[0]);
                //for (int i = 1; i < dataSet.Length; i++)
                //	Console.Write(", " + dataSet[i]);
                //Console.WriteLine();

                Console.WriteLine();
                Console.WriteLine();
            }
            #endregion

            #region Graph Search
            {
                Console.WriteLine(" Graph Searching----------------------");
                Console.WriteLine();

                // make a graph
                Graph <int> graph = new GraphSetOmnitree <int>(
                    Compare.Default,
                    Hash.Default);

                // add nodes
                graph.Add(0);
                graph.Add(1);
                graph.Add(2);
                graph.Add(3);

                // add edges
                graph.Add(0, 1);
                graph.Add(0, 2);
                graph.Add(1, 3);
                graph.Add(2, 3);

                //// represent a graph
                //// Note: can be any type  (doesn't have to be int?[,])
                //int?[,] adjacencyMatrix =
                //{
                //	{ null, 1, 2, null },
                //	{ null, null, null, 5 },
                //	{ null, null, null, 1 },
                //	{ null, null, null, null }
                //};

                // make a delegate for finding neighbor nodes
                Action <int, Step <int> > neighbors =
                    (int current, Step <int> step_function) =>
                {
                    //for (int i = 0; i < 4; i++)
                    //	if (adjacencyMatrix[current, i] != null)
                    //		step(i);
                    graph.Neighbors(current, step_function);
                };

                // make a delegate for computing heuristics
                Func <int, int> heuristic =
                    (int node) =>
                {
                    switch (node)
                    {
                    case 0:
                        return(3);

                    case 1:
                        return(6);

                    case 2:
                        return(1);

                    case 3:
                        return(0);

                    default:
                        throw new NotImplementedException();
                    }
                };

                // make a delegate for computing costs
                Func <int, int, int> cost =
                    (int from, int to) =>
                {
                    if (from == 0 && to == 1)
                    {
                        return(1);
                    }
                    if (from == 0 && to == 2)
                    {
                        return(2);
                    }
                    if (from == 1 && to == 3)
                    {
                        return(5);
                    }
                    if (from == 2 && to == 3)
                    {
                        return(1);
                    }
                    if (from == 0 && to == 3)
                    {
                        return(99);
                    }
                    throw new Exception("invalid path cost computation");
                };

                // make a delegate for determining if the goal is reached
                Func <int, bool> goal =
                    (int node) =>
                {
                    if (node == 3)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                };

                // run A* the algorithm
                Stepper <int> aStar_path = Search <int> .Graph <int> .Astar(
                    0,
                    graph,
                    new Search <int> .Graph <int> .Heuristic(heuristic),
                    new Search <int> .Graph <int> .Cost(cost),
                    new Search <int> .Graph <int> .Goal(goal));

                // run the Greedy algorithm
                Stepper <int> greedy_path = Search <int> .Graph <int> .Greedy(
                    0,
                    graph,
                    new Search <int> .Graph <int> .Heuristic(heuristic),
                    new Search <int> .Graph <int> .Goal(goal));

                Console.Write("  A* Path: ");
                if (aStar_path != null)
                {
                    aStar_path((int i) => { System.Console.Write(i + " "); });
                }
                else
                {
                    Console.Write("  none");
                }

                Console.WriteLine();

                Console.Write("  Greedy Path: ");
                if (greedy_path != null)
                {
                    greedy_path((int i) => { System.Console.Write(i + " "); });
                }
                else
                {
                    Console.Write("  none");
                }
                Console.WriteLine();
                Console.WriteLine();
            }
            #endregion

            #region Graph Search (Vector Game-Style Example)

            // Lets say you are coding enemy AI and you want the AI to find a path towards the player
            // in order to attack them. Here are their starting positions:
            Vector <float> enemy_location     = new Vector <float>(-100, 0, -50);
            Vector <float> player_location    = new Vector <float>(200, 0, -50);
            float          enemy_attack_range = 3; // enemy has a melee attack with 3 range

            // Lets say most of the terrain is open, but there is a big rock in between them that they
            // must go around.
            Vector <float> rock_location = new Vector <float>(15, 0, -40);
            float          rock_radius   = 20;

            // So, we just need to validate movement locations (make sure the path finding algorithm
            // ignores locations inside the rock)
            Func <Vector <float>, bool> validateMovementLocation = location =>
            {
                float mag = (location - rock_location).Magnitude;
                if (mag <= rock_radius)
                {
                    return(false); // inside rock (not valid)
                }
                return(true);      // not inside rock (valid)

                // NOTE:
                // This function will normally be handled by your physics engine if you are running one.
            };

            // Make sure we don't re-use locations (must be wiped after running the algorithm)
            Set <Vector <float> > already_used = new SetHashList <Vector <float> >();

            // Now we need the neighbor function (getting the neighbors of the current location).
            Search <Vector <float> > .Graph <float> .Neighbors neighborFunction = (currentLocation, neighbors) =>
            {
                // lets make a simple neighbor function that returns 4 locations (directly north, south, east, and west)
                // and the distance of each node in the graph will be 1
                Vector <float>
                north = new Vector <float>(currentLocation.X + 1, currentLocation.Y, currentLocation.Z),
                                                               east  = new Vector <float>(currentLocation.X, currentLocation.Y, currentLocation.Z + 1),
                                                               south = new Vector <float>(currentLocation.X - 1, currentLocation.Y, currentLocation.Z),
                                                               west  = new Vector <float>(currentLocation.X, currentLocation.Y, currentLocation.Z - 1);

                // validate the locations (not inside the rock) and make sure we have not already traversed the location
                if (validateMovementLocation(north) && !already_used.Contains(north))
                {
                    already_used.Add(north); // mark for usage so we do not use this location again
                    neighbors(north);
                }
                if (validateMovementLocation(east) && !already_used.Contains(east))
                {
                    already_used.Add(east); // mark for usage so we do not use this location again
                    neighbors(east);
                }
                if (validateMovementLocation(south) && !already_used.Contains(south))
                {
                    already_used.Add(south); // mark for usage so we do not use this location again
                    neighbors(south);
                }
                if (validateMovementLocation(west) && !already_used.Contains(west))
                {
                    already_used.Add(west); // mark for usage so we do not use this location again
                    neighbors(west);
                }

                // NOTES:
                // - This neighbor function has a 90 degree per-node resolution (360 / 4 [north/south/east/west] = 90).
                // - This neighbor function has a 1 unit per-node resolution, because we went 1 unit in each direction.

                // RECOMMENDATIONS:
                // - If the path finding is failing, you may need to increase the resolution.
                // - If the algorithm is running too slow, you may need to reduce the resolution.
            };

            // Now we need the heuristic function (how close are we to the goal).
            Search <Vector <float> > .Graph <float> .Heuristic heuristicFunction = currentLocation =>
            {
                // The goal is the player's location, so we just need our distance from the player.
                return((currentLocation - player_location).Magnitude);
            };

            // Lets say there is a lot of mud around the rock, and the mud makes our player move at half their normal speed.
            // Our path finding needs to find the fastest route to the player, whether it be through the mud or not.
            Vector <float> mud_location = new Vector <float>(15, 0, -70);
            float          mud_radius   = 30;

            // Now we need the cost function
            Search <Vector <float> > .Graph <float> .Cost costFunction = (location1, location2) =>
            {
                // If either locations are in the mud, lets increase the cost of moving to that spot.
                float mag1 = (location1 - mud_location).Magnitude;
                if (mag1 <= mud_radius)
                {
                    return(2);
                }
                float mag2 = (location2 - mud_location).Magnitude;
                if (mag2 <= mud_radius)
                {
                    return(2);
                }

                // neither location is in the mud, it is just a standard movement at normal speed.
                return(1);
            };

            // Now we need a goal function
            Search <Vector <float> > .Graph <float> .Goal goalFunction = currentLocation =>
            {
                float mag = (currentLocation - player_location).Magnitude;
                // if the player is within the enemy's attack range WE FOUND A PATH! :)
                if (mag <= enemy_attack_range)
                {
                    return(true);
                }

                // the enemy is not yet within attack range
                return(false);
            };

            // We have all the necessary parameters. Run the pathfinding algorithms!
            Stepper <Vector <float> > aStarPath = Search <Vector <float> > .Graph <float> .Astar(
                enemy_location,
                neighborFunction,
                heuristicFunction,
                costFunction,
                goalFunction);

            // NOTE:
            // if the "Astar" function returns "null" there is no valid path. (in this example there
            // are valid paths, so I didn't add a nul check)

            // Here is the path converted to an array (easier to read while debugging)
            Vector <float>[] aStarPath_array = aStarPath.ToArray();

            // flush the duplicate locations checker before running the Greedy algorithm
            already_used.Clear();

            Stepper <Vector <float> > greedyPath = Search <Vector <float> > .Graph <float> .Greedy(
                enemy_location,
                neighborFunction,
                heuristicFunction,
                goalFunction);

            // Here is the path converted to an array (easier to read while debugging)
            Vector <float>[] greedyPath_array = greedyPath.ToArray();


            // lets calculate the movement cost of each path

            float total_cost_astar = Compute.Add <float>(step =>
            {
                for (int i = 0; i < aStarPath_array.Length - 1; i++)
                {
                    float cost = costFunction(aStarPath_array[i], aStarPath_array[i + 1]);
                    step(cost);
                }
            });

            float total_cost_greedy = Compute.Add <float>(step =>
            {
                for (int i = 0; i < greedyPath_array.Length - 1; i++)
                {
                    float cost = costFunction(greedyPath_array[i], greedyPath_array[i + 1]);
                    step(cost);
                }
            });

            // Notice that that the A* algorithm produces a less costly path than the Greedy,
            // meaning that it is faster. The Greedy path went through the mud, but the A* path
            // took the longer route around the other side of the rock, which ended up being faster
            // than running through the mud.

            #endregion

            #region Random Generation

            Console.WriteLine(" Random Generation---------------------");
            Console.WriteLine();

            int             iterationsperrandom = 3;
            Action <Random> testrandom          = (Random random) =>
            {
                for (int i = 0; i < iterationsperrandom; i++)
                {
                    Console.WriteLine("    " + i + ": " + random.Next());
                }
                Console.WriteLine();
            };
            Arbitrary mcg_2pow59_13pow13 = new Arbitrary.Algorithms.MultiplicativeCongruent_A();
            Console.WriteLine("  mcg_2pow59_13pow13 randoms:");
            testrandom(mcg_2pow59_13pow13);
            Arbitrary mcg_2pow31m1_1132489760 = new Arbitrary.Algorithms.MultiplicativeCongruent_B();
            Console.WriteLine("  mcg_2pow31m1_1132489760 randoms:");
            testrandom(mcg_2pow31m1_1132489760);
            Arbitrary mersenneTwister = new Arbitrary.Algorithms.MersenneTwister();
            Console.WriteLine("  mersenneTwister randoms:");
            testrandom(mersenneTwister);
            Arbitrary cmr32_c2_o3 = new Arbitrary.Algorithms.CombinedMultipleRecursive();
            Console.WriteLine("  mersenneTwister randoms:");
            testrandom(cmr32_c2_o3);
            Arbitrary wh1982cmcg = new Arbitrary.Algorithms.WichmannHills1982();
            Console.WriteLine("  mersenneTwister randoms:");
            testrandom(wh1982cmcg);
            Arbitrary wh2006cmcg = new Arbitrary.Algorithms.WichmannHills2006();
            Console.WriteLine("  mersenneTwister randoms:");
            testrandom(wh2006cmcg);
            Arbitrary mwcxorsg = new Arbitrary.Algorithms.MultiplyWithCarryXorshift();
            Console.WriteLine("  mwcxorsg randoms:");
            testrandom(mwcxorsg);

            #endregion

            Console.WriteLine();
            Console.WriteLine("============================================");
            Console.WriteLine("Example Complete...");
            Console.ReadLine();
        }