Minimum number of towers required such that every house is in the range of at least one tower | Function to count the number of tower ; first we sort the house numbers ; for count number of towers ; for iterate all houses ; count number of towers ; find find the middle location ; traverse till middle location ; this is point to middle house where we insert the tower ; now find the last location ; traverse till last house of the range ; return the number of tower ; given elements ; print number of towers
function number_of_tower ( house , range , n ) { house . sort ( function ( a , b ) { return a - b ; } ) ; let numOfTower = 0 ; let i = 0 ; while ( i < n ) { numOfTower ++ ; let loc = house [ i ] + range ; while ( i < n && house [ i ] <= loc ) i ++ ; -- i ; loc = house [ i ] + range ; while ( i < n && house [ i ] <= loc ) i ++ ; } return numOfTower ; } let house = [ 7 , 2 , 4 , 6 , 5 , 9 , 12 , 11 ] ; let range = 2 ; let n = house . length ; document . write ( number_of_tower ( house , range , n ) ) ;