RemoveInterval.cs

CSharp · Console

/Program.cs

using System;
using System.Linq;
using System.Collections.Generic;
					
public class Program
{
	public static IList<IList<int>> RemoveInterval(int[][] intervals, int[] toBeRemoved) {
        var list = new List<IList<int>>();
        for (int i = 0; i < intervals.Length; i++)
        {
            var cur = intervals[i];

            // текущий интервал полностью входит в toBeRemoved
            // пропускаем его, он будет удален
            if (toBeRemoved[0] <= cur[0] && cur[1] <= toBeRemoved[1])
            {
                continue;
            }
            // текущий интервал не входит в toBeRemoved -> сохраняем его полностью
            else if (cur[0] >= toBeRemoved[1] || cur[1] <= toBeRemoved[0])
            {
                list.Add(cur);
            }
            // в текущий интервал полностью входит toBeRemoved
            // сохраняем остатки интервала с его начала и с конца
            else if (cur[0] < toBeRemoved[0] && toBeRemoved[1] < cur[1])
            {
                list.Add(new int[] { cur[0], toBeRemoved[0] });
                list.Add(new int[] { toBeRemoved[1], cur[1]});
            }
            // начало текущего интервала не входит в toBeRemoved -> сохраняем его
            else if (cur[0] < toBeRemoved[0])
            {
                list.Add(new int[] { cur[0], toBeRemoved[0] });
            }
            // конец текущего интервала не входит в toBeRemoved -> сохраняем его
            else if (cur[0] < toBeRemoved[1])
            {
                list.Add(new int[] { toBeRemoved[1], cur[1] });
            }
        }

        return list; 
    }
	
	public static void ShowListOfList(IList<IList<int>> list)
	{
		Console.WriteLine(string.Join(", ", list.Select(x => "[" + string.Join(", ", x) + "]")));
		Console.WriteLine();

	}
	
	public static void Main()
	{
		Console.WriteLine("UniLecs");
		
		// tests
		var list = new int[][] {
			new int[] { 0, 2 },
			new int[] { 3, 4 },
			new int[] { 5, 7 }	
		};
		ShowListOfList(RemoveInterval(list, new int[] { 1, 6 }));
	}
}
;