Bin Packing Problem ( Minimize number of used Bins ) | Returns number of bins required using first 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 first 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
def firstFit ( weight , n , c ) : NEW_LINE INDENT res = 0 ; NEW_LINE bin_rem = [ 0 ] * n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = 0 ; NEW_LINE min = c + 1 ; NEW_LINE bi = 0 ; NEW_LINE for j in range ( res ) : NEW_LINE INDENT if ( bin_rem [ j ] >= weight [ i ] and bin_rem [ j ] - weight [ i ] < min ) : NEW_LINE INDENT bi = j ; NEW_LINE min = bin_rem [ j ] - weight [ i ] ; NEW_LINE DEDENT DEDENT if ( min == c + 1 ) : NEW_LINE INDENT bin_rem [ res ] = c - weight [ i ] ; NEW_LINE res += 1 ; NEW_LINE bin_rem [ bi ] -= weight [ i ] ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT weight = [ 2 , 5 , 4 , 7 , 1 , 3 , 8 ] ; NEW_LINE c = 10 ; NEW_LINE n = len ( weight ) ; NEW_LINE print ( " Number ▁ of ▁ bins ▁ required ▁ in ▁ First ▁ Fit ▁ : ▁ " , firstFit ( weight , n , c ) ) ; NEW_LINE DEDENT