Algorithm to calculate number of intersecting discs

前端 未结 30 1557
鱼传尺愫
鱼传尺愫 2020-12-12 10:57

Given an array A of N integers we draw N discs in a 2D plane, such that i-th disc has center in (0,i) and a radius

30条回答
  •  旧时难觅i
    2020-12-12 11:37

    I know that this is an old questions but it is still active on codility.

        private int solution(int[] A)
        {
            int openedCircles = 0;
            int intersectCount = 0;
    

    We need circles with their start and end values. For that purpose I have used Tuple. True/False indicates if we are adding Circle Starting or Circle Ending value.

            List> circles = new List>();
            for(int i = 0; i < A.Length; i ++)
            {
                // Circle start value
                circles.Add(new Tuple((decimal)i - (decimal)A[i], true));
    
                // Circle end value
                circles.Add(new Tuple((decimal)i + (decimal)A[i], false));
            }
    

    Order "circles" by their values. If one circle is ending at same value where other circle is starting, it should be counted as intersect (because of that "opening" should be in front of "closing" if in same point)

            circles = circles.OrderBy(x => x.Item1).ThenByDescending(x => x.Item2).ToList();
    

    Counting and returning counter

            foreach (var circle in circles)
            {
                // We are opening new circle (within existing circles)
                if(circle.Item2 == true)
                {
                    intersectCount += openedCircles;
    
                    if (intersectCount > 10000000)
                    { 
                        return -1;
                    }
    
                    openedCircles++;
                }
                else
                {
                    // We are closing circle
                    openedCircles--;
                }
            }
    
            return intersectCount;
        }
    

提交回复
热议问题