Lecture 28 - Money Counting and Bin Packing Problem
Lecture 28 - Money Counting and Bin Packing Problem
Lecture # 28
Counting Money Problem
2
Counting Money Problem
Suppose you want to count out a certain amount of money,
using the fewest possible bills and coins
7
Approximate Bin Packing
Problem
We are given n items of sizes 𝑆1, 𝑆2, … , 𝑆𝑛. All sizes satisfy
0 < 𝑆𝑖 ≤ 1.
Suppose we have item list with sizes 0.2, 0.5, 0.4, 0.7, 0.1,
0.3, 0.8. Optimal packing of these sizes is
0.3 0.5
0.8
0.1
0.7
0.4 8
0.2
B1 B2 B3
Approximate Bin Packing
Problem
Algorithm 1: Next Fit
When processing any item, we check to see whether
it fits in the same bin as the last item; if it does it is
placed there; otherwise a new bin is created.
void NextFit ( )
{ read item1;
while ( read item2 ) {
if ( item2 can be packed in the same bin as item1 )
place item2 in the bin;
else
create a new bin for item2;
item1 = item2;
} /* end-while */
}
9
Approximate Bin Packing
Problem
Next Fit for 0.2, 0.5, 0.4, 0.7, 0.1, 0.3, 0.8 is
0.1
0.5 0.8
0.7
0.4 0.3
0.2
B1 B2 B3 B4 B5
10
Approximate Bin Packing
Problem
Algorithm 2: First Fit
⚫ We scan the bins in order and place the new item in the
first bin that is large enough to hold it. A new bin is created
only when the result of previous placements have left no
other alternative.
void FirstFit ( )
{ while ( read item ) {
scan for the first bin that is large enough for item;
if ( found )
place item in that bin;
else
create a new bin for item;
} /* end-while */
}
11
Approximate Bin Packing
Problem
First Fit for 0.2, 0.5, 0.4, 0.7, 0.1, 0.3,
0.8 is
0.1
0.3
0.5 0.8
0.7
0.4
0.2
B1 B2 B3 B4
12
Approximate Bin Packing
Problem
Algorithm 3: Best Fit
⚫ Instead of placing a new item in the first spot that is found.
It is placed in the tightest spot among all bins
Best Fit for 0.2, 0.5, 0.4, 0.7, 0.1, 0.3, 0.8 is
0.3
0.1
0.5 0.8
0.7
0.4
0.2
B1 B2 B3 B4 13
T = O( N log N )
Approximate Bin Packing
Problem
Offline Algorithms
⚫ The major problem with all the on-line
algorithms is that it is hard to pack the
large items, especially when they occur
late in the input.
⚫ The natural way around this is to sort the
items, placing the largest items first.
0.2 0.1
0.3
0.4
0.8 0.7 0.5
15
B1 B2 B3