private void initialize(IEnumerable <Line> lineSegments)
        {
            SweepLine = new Line(new Point(0, 0), new Point(0, int.MaxValue), Tolerance);

            currentlyTrackedLines = new RedBlackTree <Event>(true, pointComparer);
            intersectionEvents    = new Dictionary <Point, HashSet <Tuple <Event, Event> > >(pointComparer);

            verticalHorizontalLines = new HashSet <Event>();
            normalLines             = new HashSet <Event>();

            rightLeftEventLookUp = lineSegments
                                   .Select(x =>
            {
                if (x.Left.X < 0 || x.Left.Y < 0 || x.Right.X < 0 || x.Right.Y < 0)
                {
                    throw new Exception("Negative coordinates are not supported.");
                }

                return(new KeyValuePair <Event, Event>(
                           new Event(x.Left, pointComparer, EventType.Start, x, this),
                           new Event(x.Right, pointComparer, EventType.End, x, this)
                           ));
            }).ToDictionary(x => x.Value, x => x.Key);

            eventQueueLookUp = new HashSet <Event>(rightLeftEventLookUp.SelectMany(x => new[] {
                x.Key,
                x.Value
            }), new PointComparer());

            eventQueue = new BMinHeap <Event>(eventQueueLookUp, new EventQueueComparer());
        }
        /// <summary>
        /// Returns a dictionary of chosen encoding bytes for each distinct T
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Dictionary <T, byte[]> Compress(T[] input)
        {
            var frequencies = computeFrequency(input);

            var minHeap = new BMinHeap <FrequencyWrap>();

            foreach (var frequency in frequencies)
            {
                minHeap.Insert(new FrequencyWrap(
                                   frequency.Key, frequency.Value));
            }

            while (minHeap.Count > 1)
            {
                var a = minHeap.ExtractMin();
                var b = minHeap.ExtractMin();

                var newNode = new FrequencyWrap(
                    default(T), a.Frequency + b.Frequency);

                newNode.Left  = a;
                newNode.Right = b;

                minHeap.Insert(newNode);
            }

            var root = minHeap.ExtractMin();

            var result = new Dictionary <T, byte[]>();

            DFS(root, new List <byte>(), result);

            return(result);
        }
Beispiel #3
0
        /// <summary>
        /// Sort the given input
        /// where elements are misplaced almost by a distance k
        /// </summary>
        /// <param name="input"></param>
        /// <param name="k"></param>
        /// <returns></returns>
        public static int[] Sort(int[] input, int k)
        {
            if (k > input.Length)
            {
                throw new Exception("K cannot exceed array length.");
            }

            var firstKElements = new int[k];

            Array.Copy(input, firstKElements, k);

            var minHeap = new BMinHeap <int>(firstKElements);

            var result = new List <int>();

            for (int i = k; i < input.Length; i++)
            {
                result.Add(minHeap.ExtractMin());
                minHeap.Insert(input[i]);
            }

            while (minHeap.Count > 0)
            {
                result.Add(minHeap.ExtractMin());
            }

            return(result.ToArray());
        }
Beispiel #4
0
        public void BMinHeap_Test()
        {
            var rnd     = new Random();
            var initial = Enumerable.Range(0, 51).OrderBy(x => rnd.Next()).ToList();

            //insert test
            var tree = new BMinHeap <int>(initial);

            for (int i = 51; i <= 99; i++)
            {
                tree.Insert(i);
            }

            for (int i = 0; i <= 99; i++)
            {
                var min = tree.ExtractMin();
                Assert.AreEqual(min, i);
            }


            var testSeries = Enumerable.Range(1, 49).OrderBy(x => rnd.Next()).ToList();

            foreach (var item in testSeries)
            {
                tree.Insert(item);
            }

            for (int i = 1; i <= 49; i++)
            {
                var min = tree.ExtractMin();
                Assert.AreEqual(min, i);
            }
        }
Beispiel #5
0
        private void initialize(IEnumerable <Line> lineSegments)
        {
            SweepLine = new Line(new Point(0, 0), new Point(0, int.MaxValue), Tolerance);

            var pointComparer = new PointComparer(Tolerance);

            currentlyTracked   = new RedBlackTree <Event>(true, pointComparer);
            intersectionEvents = new Dictionary <Point, HashSet <Tuple <Event, Event> > >(pointComparer);

            specialLines = new HashSet <Event>();
            normalLines  = new HashSet <Event>();

            rightLeftEventLookUp = lineSegments
                                   .Select(x =>
            {
                return(new KeyValuePair <Event, Event>(
                           new Event(x.Left, EventType.Start, x, this),
                           new Event(x.Right, EventType.End, x, this)
                           ));
            }).ToDictionary(x => x.Value, x => x.Key);

            eventQueueLookUp = new HashSet <Event>(rightLeftEventLookUp.SelectMany(x => new[] {
                x.Key,
                x.Value
            }), new PointComparer(Tolerance));

            eventQueue = new BMinHeap <Event>(eventQueueLookUp, new EventQueueComparer(Tolerance));
        }
Beispiel #6
0
        /// <summary>
        /// Do DFS to pick smallest weight neighbour edges
        /// of current spanning tree one by one
        /// </summary>
        /// <param name="graph"></param>
        /// <param name="currentVertex"></param>
        /// <param name="spanTreeVertices"></param>
        /// <param name="spanTreeNeighbours"> Use Fibornacci Min Heap to pick smallest edge neighbour </param>
        /// <param name="spanTreeEdges">result MST edges</param>
        private void DFS(WeightedGraph <T, W> graph,
                         WeightedGraphVertex <T, W> currentVertex,
                         BMinHeap <MSTEdge <T, W> > spanTreeNeighbours,
                         HashSet <T> spanTreeVertices,
                         List <MSTEdge <T, W> > spanTreeEdges)
        {
            //add all edges to Fibornacci Heap
            //So that we can pick the min edge in next step
            foreach (var edge in currentVertex.Edges)
            {
                spanTreeNeighbours.Insert(new MSTEdge <T, W>(
                                              currentVertex.Value,
                                              edge.Key.Value, edge.Value));
            }

            //pick min edge
            var minNeighbourEdge = spanTreeNeighbours.ExtractMin();

            //skip edges already in MST
            while (spanTreeVertices.Contains(minNeighbourEdge.Source) &&
                   spanTreeVertices.Contains(minNeighbourEdge.Destination))
            {
                minNeighbourEdge = spanTreeNeighbours.ExtractMin();

                //if no more neighbours to explore
                //time to end exploring
                if (spanTreeNeighbours.Count == 0)
                {
                    return;
                }
            }

            //keep track of visited vertices
            //do not duplicate vertex
            if (!spanTreeVertices.Contains(minNeighbourEdge.Source))
            {
                spanTreeVertices.Add(minNeighbourEdge.Source);
            }

            //Destination vertex will never be a duplicate
            //since this is an unexplored Vertex
            spanTreeVertices.Add(minNeighbourEdge.Destination);

            //add edge to result
            spanTreeEdges.Add(minNeighbourEdge);

            //now explore the destination vertex
            DFS(graph, graph.Vertices[minNeighbourEdge.Destination],
                spanTreeNeighbours, spanTreeVertices, spanTreeEdges);
        }
Beispiel #7
0
        /// <summary>
        /// Time complexity: O(nlog(n)).
        /// </summary>
        public static T[] Sort(T[] array)
        {
            //heapify
            var heap = new BMinHeap <T>(array);

            //now extract min until empty and return them as sorted array
            var sortedArray = new T[array.Length];
            var j           = 0;

            while (heap.Count > 0)
            {
                sortedArray[j] = heap.ExtractMin();
                j++;
            }

            return(sortedArray);
        }
        /// <summary>
        /// Find smallest by first constructing a BMinHeap in O(n) time
        /// & then extracting out k -1 times
        /// Finally do one more extract to return the kth smallest
        /// Total O(n+k) complexity
        /// Better algorithms do exist with O(n) time
        /// </summary>
        /// <param name="input"></param>
        /// <param name="k"></param>
        /// <returns></returns>
        public T FindKthSmallest(T[] input, int k)
        {
            if (k > input.Length)
            {
                throw new Exception("K exceeds input length.");
            }

            var minHeap = new BMinHeap <T>(input);

            //0,1,2...(k-1) min extraction
            for (int i = 0; i < k - 1; i++)
            {
                minHeap.ExtractMin();
            }

            //kth extraction
            return(minHeap.ExtractMin());
        }
Beispiel #9
0
        //O(nlog(n))
        public static T[] Sort(T[] array)
        {
            //heapify
            var heap = new BMinHeap <T>();

            for (int i = 0; i < array.Length; i++)
            {
                heap.Insert(array[i]);
            }

            //now extract min until empty and return them as sorted array
            var sortedArray = new T[array.Length];
            int j           = 0;

            while (heap.Count > 0)
            {
                sortedArray[j] = heap.ExtractMin();
                j++;
            }

            return(sortedArray);
        }