-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathKnapsack.cs
274 lines (250 loc) · 9.39 KB
/
Knapsack.cs
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using TreesearchLib;
namespace SampleApp
{
/// <summary>
/// Provides an implementation of the {0,1}-Knapsack problem that
/// supports undo, i.e., moves can be applied and reversed. It is
/// less efficient to clone this state, than <seealso cref="KnapsackNoUndo"/>,
/// because the Decision vector is always full length.
/// </summary>
public class Knapsack : IMutableState<Knapsack, (bool, int), Maximize>
{
public IReadOnlyList<int> Profits { get; set; }
public IReadOnlyList<int> Weights { get; set; }
public int Capacity { get; set; }
public Stack<(bool, int)> Decision { get; private set; }
public int TotalWeight { get; set; }
public int TotalProfit { get; set; }
public Knapsack(IReadOnlyList<int> profits, IReadOnlyList<int> weights, int capcity) {
Profits = profits;
Weights = weights;
Capacity = capcity;
Decision = new Stack<(bool, int)>();
}
public Knapsack(Knapsack other)
{
Profits = other.Profits;
Weights = other.Weights;
Capacity = other.Capacity;
Decision = new Stack<(bool, int)>(other.Decision.Reverse());
TotalWeight = other.TotalWeight;
TotalProfit = other.TotalProfit;
IsTerminal = other.IsTerminal;
}
public bool IsTerminal { get; set; }
// Caching the bound improves performance a lot when e.g., using it
// as sorting criteria in beam search
private Maximize? cachedbound;
public Maximize Bound {
get {
if (!cachedbound.HasValue)
{
if (TotalWeight > Capacity)
{
cachedbound = new Maximize(Capacity - TotalWeight);
} else
{
// This simple bound assumes all remaining items that may
// fit (without considering the others) can be added
var profit = TotalProfit;
var item = Decision.Count > 0 ? Decision.Peek().Item2 : -1;
for (var i = item + 1; i < Profits.Count; i++)
{
if (TotalWeight + Weights[i] <= Capacity)
{
profit += Profits[i];
}
}
cachedbound = new Maximize(profit);
}
}
return cachedbound.Value;
}
}
public Maximize? Quality {
get
{
// as the constraint is checked in GetChoices(), the following condition
// should never be true, however if GetChoices() is changed to consider a relaxed
// formulation that seeks to minimize overweight, this function is still correct
if (TotalWeight > Capacity) return new Maximize(Capacity - TotalWeight);
return new Maximize(TotalProfit);
}
}
public void Apply((bool, int) choice)
{
cachedbound = null;
var (take, item) = choice;
if (take)
{
TotalWeight += Weights[item];
TotalProfit += Profits[item];
}
var isTerminal = true;
for (var i = item + 1; i < Profits.Count; i++)
{
if (TotalWeight + Weights[i] <= Capacity)
{
isTerminal = false;
break;
}
}
IsTerminal = isTerminal;
Decision.Push(choice);
}
public void UndoLast()
{
cachedbound = null;
var (take, item) = Decision.Pop();
if (take)
{
TotalWeight -= Weights[item];
TotalProfit -= Profits[item];
}
IsTerminal = false;
}
public object Clone()
{
return new Knapsack(this);
}
public IEnumerable<(bool, int)> GetChoices()
{
if (IsTerminal) yield break;
var item = Decision.Count > 0 ? Decision.Peek().Item2 : -1;
for (var i = item + 1; i < Profits.Count; i++)
{
if (Weights[i] + TotalWeight <= Capacity)
{
yield return (true, i);
yield return (false, i);
yield break;
}
}
}
public override string ToString()
{
return $"Items: {string.Join(", ", Decision.Where(x => x.Item1).Select(x => x.Item2))}";
}
}
/// <summary>
/// Provides an implementatino of the {0,1}-Knapsack problem that
/// doesn't support undo and is optimized for more efficient cloning.
/// </summary>
public class KnapsackNoUndo : IState<KnapsackNoUndo, Maximize>
{
public IReadOnlyList<int> Profits { get; private set; }
public IReadOnlyList<int> Weights { get; private set; }
public int Capacity { get; private set; }
public bool[] Decision { get; private set; }
public int TotalWeight { get; private set; }
public int TotalProfit { get; private set; }
public KnapsackNoUndo(IReadOnlyList<int> profits, IReadOnlyList<int> weights, int capacity)
{
Profits = profits;
Weights = weights;
Capacity = capacity;
Decision = new bool[0];
TotalWeight = 0;
TotalProfit = 0;
}
public KnapsackNoUndo(KnapsackNoUndo other)
{
Profits = other.Profits;
Weights = other.Weights;
Capacity = other.Capacity;
Decision = other.Decision; // is considered immutable
TotalWeight = other.TotalWeight;
TotalProfit = other.TotalProfit;
}
public KnapsackNoUndo(KnapsackNoUndo other, bool choice, int item) : this(other)
{
if (choice)
{
TotalWeight += Weights[item];
TotalProfit += Profits[item];
}
var decision = new bool[item + 1];
Array.Copy(other.Decision, decision, other.Decision.Length);
decision[item] = choice;
Decision = decision;
}
public bool IsTerminal => Decision.Length == Profits.Count;
public Maximize Bound
{
get
{
if (TotalWeight > Capacity)
{
return new Maximize(Capacity - TotalWeight);
} else
{
// This simple bound assumes all remaining items that may
// fit (without considering the others) can be added
var profit = TotalProfit;
for (var i = Decision.Length; i < Profits.Count; i++)
{
if (TotalWeight + Weights[i] <= Capacity)
{
profit += Profits[i];
}
}
return new Maximize(profit);
}
}
}
public Maximize? Quality
{
get
{
// as the constraint is checked in GetBranches(), the following condition
// should never be true, however if GetBranches() is changed to consider a relaxed
// formulation that seeks to minimize overweight, this function is still correct
if (TotalWeight > Capacity) return new Maximize(Capacity - TotalWeight);
return new Maximize(TotalProfit);
}
}
public object Clone()
{
return new KnapsackNoUndo(this);
}
public IEnumerable<KnapsackNoUndo> GetBranches()
{
if (IsTerminal) yield break;
for (var i = Decision.Length; i < Profits.Count; i++)
{
if (Weights[i] + TotalWeight <= Capacity)
{
yield return new KnapsackNoUndo(this, true, i);
yield return new KnapsackNoUndo(this, false, i);
yield break;
}
}
}
public override string ToString()
{
return $"Items: {string.Join(", ", Decision.Select((v, i) => (i, v)).Where(x => x.v).Select(x => x.i))}";
}
public override bool Equals(object obj)
{
if (obj is KnapsackNoUndo other)
{
if (!Profits.SequenceEqual(other.Profits)) return false;
if (!Weights.SequenceEqual(other.Weights)) return false;
if (Capacity != other.Capacity) return false;
if (TotalWeight != other.TotalWeight) return false;
if (TotalProfit != other.TotalProfit) return false;
if (Decision.Length != other.Decision.Length) return false;
for (var i = 0; i < Decision.Length; i++)
{
if (Decision[i] != other.Decision[i]) return false;
}
return true;
}
return false;
}
}
}