Bin Packing Problem ( Minimize number of used Bins ) | Returns number of bins required using best fit online algorithm ; Initialize result ( Count of bins ) ; Create an array to store remaining space in bins there can be at most n bins ; Place items one by one ; Find the best bin that can accommodate weight [ i ] ; Initialize minimum space left and index of best bin ; If no bin could accommodate weight [ i ] , create a new bin ; } else Assign the item to best bin ; Driver code
function bestFit ( weight , n , c ) { var res = 0 ; var bin_rem = Array ( n ) . fill ( 0 ) ; for ( i = 0 ; i < n ; i ++ ) { var j ; var min = c + 1 , bi = 0 ; for ( j = 0 ; j < res ; j ++ ) { if ( bin_rem [ j ] >= weight [ i ] && bin_rem [ j ] - weight [ i ] < min ) { bi = j ; min = bin_rem [ j ] - weight [ i ] ; } } if ( min == c + 1 ) { bin_rem [ res ] = c - weight [ i ] ; res ++ ; bin_rem [ bi ] -= weight [ i ] ; } return res ; } var weight = [ 2 , 5 , 4 , 7 , 1 , 3 , 8 ] ; var c = 10 ; var n = weight . length ; document . write ( " " + bestFit ( weight , n , c ) ) ;