K Centers Problem | Set 1 ( Greedy Approximate Algorithm ) | Javascript program for the above approach ; Index of city having the maximum distance to it 's  closest center ; Updating the distance of the cities to their closest centers ; Updating the index of the city with the maximum distance to it 's closest center ; Printing the maximum distance of a city to a center that is our answer ; Printing the cities that were chosen to be made centers ; Driver Code ; Function Call
function maxindex ( dist , n ) { let mi = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( dist [ i ] > dist [ mi ] ) mi = i ; } return mi ; } function selectKcities ( n , weights , k ) { let dist = new Array ( n ) ; let centers = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { dist [ i ] = Number . MAX_VALUE ; } let max = 0 ; for ( let i = 0 ; i < k ; i ++ ) { centers . push ( max ) ; for ( let j = 0 ; j < n ; j ++ ) { dist [ j ] = Math . min ( dist [ j ] , weights [ max ] [ j ] ) ; } max = maxindex ( dist , n ) ; } document . write ( dist [ max ] + " " ) ; for ( let i = 0 ; i < centers . length ; i ++ ) { document . write ( centers [ i ] + " " ) ; } document . write ( " " ) ; } let n = 4 ; let weights = [ [ 0 , 4 , 8 , 5 ] , [ 4 , 0 , 10 , 7 ] , [ 8 , 10 , 0 , 9 ] , [ 5 , 7 , 9 , 0 ] ] let k = 2 selectKcities ( n , weights , k )