Hackerland Radio Transmitters

  • + 0 comments

    Python, typical greedy algorithm

    # two modes: 
    # a) looking for farthest house to provide covarege for current uncovered house (radio search)
    # b) looking for first house out of coverage from current house with radio
    
    def hackerlandRadioTransmitters(locs, coverage):
        locs.sort()
        if len(locs) == 1:
            return 1
    
        radiosearch = True
        curindex = 0
        numradios = 0
        
        while True:
            otherindex = curindex + 1
            while otherindex != len(locs) and locs[otherindex] - locs[curindex] <= coverage:
                otherindex += 1
                
            if radiosearch:
                numradios += 1
                curindex = otherindex - 1 # radio search ends one house too far
            else:
                curindex = otherindex
                
            if otherindex == len(locs):
                return numradios
            
            radiosearch = not radiosearch