Algorithm to calculate number of intersecting discs

前端 未结 30 1553
鱼传尺愫
鱼传尺愫 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条回答
  •  醉酒成梦
    2020-12-12 11:43

    This is a ruby solution that scored 100/100 on codility. I'm posting it now because I'm finding it difficult to follow the already posted ruby answer.

    def solution(a)
        end_points = []
        a.each_with_index do |ai, i|
            end_points << [i - ai, i + ai]
        end
        end_points = end_points.sort_by { |points| points[0]}
    
        intersecting_pairs = 0
        end_points.each_with_index do |point, index|
            lep, hep = point
            pairs = bsearch(end_points, index, end_points.size - 1, hep)
            return -1 if 10000000 - pairs + index < intersecting_pairs
            intersecting_pairs += (pairs - index)
        end
        return intersecting_pairs
    end
    
    # This method returns the maximally appropriate position
    # where the higher end-point may have been inserted.
    def bsearch(a, l, u, x)
        if l == u
            if x >= a[u][0]
                return u
            else
                return l - 1 
            end
        end
        mid = (l + u)/2
    
        # Notice that we are searching in higher range
        # even if we have found equality.
        if a[mid][0] <= x
            return bsearch(a, mid+1, u, x)
        else
            return bsearch(a, l, mid, x)
        end
    end
    

提交回复
热议问题