Example #1
0
        /// <summary>
        /// Joins adjacent intervals.
        /// </summary>
        /// <param name="set">the current <see cref="IDisjointIntervalSet"/> instance</param>
        /// <returns>a new <see cref="IDisjointIntervalSet"/> with the minimum amount of intervals</returns>
        public static IDisjointIntervalSet Consolidate(this IDisjointIntervalSet set)
        {
            var result = new DisjointIntervalSet();

            if (set.Count > 0)
            {
                var orderedList = set.OrderBy(x => x.Start);

                var cachedItem = orderedList.FirstOrDefault();

                foreach (var item in orderedList.Skip(1))
                {
                    if (cachedItem.IsContiguouslyFollowedBy(item))
                    {
                        cachedItem = new Interval(
                            cachedItem.Start,
                            item.End,
                            cachedItem.StartIncluded,
                            item.EndIncluded);
                    }
                    else
                    {
                        result.Add(cachedItem);
                        cachedItem = item;
                    }
                }

                result.Add(cachedItem);
            }

            return(result);
        }
Example #2
0
        /// <summary>
        /// Joins the given <see cref="IInterval"/> with the current set
        /// </summary>
        /// <param name="set">the current <see cref="IDisjointIntervalSet"/> instance</param>
        /// <param name="interval">the <see cref="IInterval"/> to join</param>
        /// <returns>a new <see cref="IDisjointIntervalSet"/> with the joined intervals</returns>
        public static IDisjointIntervalSet Join(this IDisjointIntervalSet set, IInterval interval)
        {
            var groups = set.GroupBy(val => val.Intersects(interval)).ToDictionary(g => g.Key, g => g.ToList());

            var nonOverlaps = groups.ContainsKey(false) ? groups[false] : new List <IInterval>();
            var result      = new DisjointIntervalSet(nonOverlaps);

            var overlaps    = groups.ContainsKey(true) ? groups[true] : new List <IInterval>();
            var newInterval = interval;

            foreach (var overlap in overlaps)
            {
                newInterval = Interval.Join(newInterval, overlap);
            }

            result.Add(newInterval);

            return(result);
        }