-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinpack.ts
More file actions
80 lines (70 loc) · 1.67 KB
/
binpack.ts
File metadata and controls
80 lines (70 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
export class Size {
private readonly dims: number[];
constructor(dims: number[]) {
this.dims = [...dims];
}
get(dim: number): number {
return this.dims[dim] ?? 0;
}
add(that: Size): Size {
const newSize = new Size(this.dims);
for (let i = 0; i < this.dims.length; i++) {
newSize.dims[i] += that.get(i);
}
return newSize;
}
compare(that: Size): number {
for (let i = 0; i < this.dims.length; i++) {
const t1 = this.get(i);
const t2 = that.get(i);
if (t1 < t2) {
return -1;
}
if (t1 > t2) {
return 1;
}
}
return 0;
}
canContain(that: Size): boolean {
for (let i = 0; i < this.dims.length; i++) {
const t1 = this.get(i);
const t2 = that.get(i);
if (t2 > t1) {
return false;
}
}
return true;
}
}
export type Item<T> = {
obj: T;
size: Size;
};
export function firstFitDecreasing<T>(capacity: Size, items: Item<T>[]) {
// sort in decreasing order of required capacity
const sorted = [...items].sort((a, b) => -a.size.compare(b.size));
const bins: { items: Item<T>[]; used: Size }[] = [];
for (const item of sorted) {
let fit = false;
for (const bin of bins) {
// search for first bin which can fit
if (capacity.canContain(bin.used.add(item.size))) {
// assign to bin
bin.items.push(item);
bin.used = bin.used.add(item.size);
fit = true;
break;
}
}
// if no existing bins can fit the item
// create a new bin
if (!fit && capacity.canContain(item.size)) {
bins.push({
items: [item],
used: item.size,
});
}
}
return bins;
}