-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2197 lines (1938 loc) · 76.9 KB
/
script.js
File metadata and controls
2197 lines (1938 loc) · 76.9 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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// We're using local implementations of the knapsack algorithms
// instead of importing them as modules to avoid potential issues
class Item {
constructor(value, weight, id) {
this.value = value;
this.weight = weight;
this.id = id;
}
}
// Global variables
let items = [];
let selectedItems = [];
let capacity = 10;
let optimalSolution = null;
let stepsCounter = 0;
// DOM elements
const itemsContainer = document.getElementById('items-container');
const selectedItemsContainer = document.getElementById('selected-items');
const capacityInput = document.getElementById('capacity-input');
const itemCountInput = document.getElementById('item-count');
const generateBtn = document.getElementById('generate-btn');
const solveBtn = document.getElementById('solve-btn');
const resetBtn = document.getElementById('reset-btn');
const showStepsBtn = document.getElementById('show-steps-btn');
const explainAlgorithmBtn = document.getElementById('explain-algorithm-btn');
const currentWeightSpan = document.getElementById('current-weight');
const maxCapacitySpan = document.getElementById('max-capacity');
const capacityFill = document.getElementById('capacity-fill');
const selectionValueSpan = document.getElementById('selection-value');
const selectionWeightSpan = document.getElementById('selection-weight');
const backpack = document.getElementById('backpack');
const resultPanel = document.getElementById('result-panel');
const bestValueSpan = document.getElementById('best-value');
const totalWeightSpan = document.getElementById('total-weight');
const stepsTakenSpan = document.getElementById('steps-taken');
const optimalSolutionDiv = document.getElementById('optimal-solution');
const stepsModal = document.getElementById('steps-modal');
const closeModal = document.getElementById('close-modal');
const visualStepsDiv = document.getElementById('visual-steps');
const combinationsDisplayDiv = document.getElementById('combinations-display');
const explanationModal = document.getElementById('explanation-modal');
const closeExplanationModal = document.getElementById('close-explanation-modal');
const explanationTitle = document.getElementById('explanation-title');
const algorithmExplanation = document.getElementById('algorithm-explanation');
// Initialization
initialize();
function initialize() {
console.log("Initializing application...");
// Initialize capacity
capacity = parseInt(capacityInput.value);
maxCapacitySpan.textContent = capacity;
backpack.querySelector('span').textContent = `Capacidade: ${capacity}`;
console.log("Initial capacity set to:", capacity);
// Add event listeners
generateBtn.addEventListener('click', generateItems);
solveBtn.addEventListener('click', solveKnapsack);
resetBtn.addEventListener('click', resetSelection);
showStepsBtn.addEventListener('click', showAlgorithmSteps);
closeModal.addEventListener('click', () => stepsModal.style.display = 'none');
explainAlgorithmBtn.addEventListener('click', showAlgorithmExplanation);
closeExplanationModal.addEventListener('click', () => explanationModal.style.display = 'none');
capacityInput.addEventListener('change', () => {
capacity = parseInt(capacityInput.value);
maxCapacitySpan.textContent = capacity;
backpack.querySelector('span').textContent = `Capacidade: ${capacity}`;
updateCapacityBar();
console.log("Capacity updated to:", capacity);
});
// Initial generation
console.log("Generating initial items...");
generateItems();
console.log("Initialization complete");
}
function generateRandomItems(count) {
const newItems = [];
const usedValues = new Set();
const usedWeights = new Set();
const minValue = parseInt(document.getElementById('min-value').value);
const maxValue = parseInt(document.getElementById('max-value').value);
const minWeight = parseInt(document.getElementById('min-weight').value);
const maxWeight = parseInt(document.getElementById('max-weight').value);
// Validate ranges
if (minValue > maxValue || minWeight > maxWeight) {
alert('O valor mínimo não pode ser maior que o valor máximo!');
return [];
}
console.log("Generating items with values between", minValue, "and", maxValue, "and weights between", minWeight, "and", maxWeight);
for (let i = 0; i < count; i++) {
let value, weight;
let attempts = 0;
const maxAttempts = 100; // Prevent infinite loops
do {
value = Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue;
weight = Math.floor(Math.random() * (maxWeight - minWeight + 1)) + minWeight;
attempts++;
} while ((usedValues.has(value) && usedWeights.has(weight)) && attempts < maxAttempts);
if (attempts >= maxAttempts) {
// If we can't find a unique combination, just use the last generated values
value = Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue;
weight = Math.floor(Math.random() * (maxWeight - minWeight + 1)) + minWeight;
}
usedValues.add(value);
usedWeights.add(weight);
// Create a new item with a unique id
const item = new Item(value, weight, i + 1);
newItems.push(item);
console.log(`Created item ${i+1}: value=${value}, weight=${weight}`);
}
console.log("Generated", newItems.length, "items");
return newItems;
}
function validateInputs() {
const minValue = parseInt(document.getElementById('min-value').value);
const maxValue = parseInt(document.getElementById('max-value').value);
const minWeight = parseInt(document.getElementById('min-weight').value);
const maxWeight = parseInt(document.getElementById('max-weight').value);
const itemCount = parseInt(document.getElementById('item-count').value);
const capacity = parseInt(document.getElementById('capacity-input').value);
const algorithm = document.getElementById('algorithm-select').value;
// Validate value ranges
document.getElementById('value-warning').style.display =
(minValue > maxValue) ? 'block' : 'none';
document.getElementById('weight-warning').style.display =
(minWeight > maxWeight) ? 'block' : 'none';
// Show warnings for large problems
document.getElementById('items-warning').style.display =
(itemCount > 20) ? 'block' : 'none';
document.getElementById('capacity-warning').style.display =
(capacity > 1000) ? 'block' : 'none';
// Show algorithm-specific warnings
let showAlgorithmWarning = false;
if (algorithm === 'bruteforce' && itemCount > 20) {
showAlgorithmWarning = true;
} else if (algorithm === 'dp' && (itemCount * capacity > 1000000)) {
showAlgorithmWarning = true;
} else if (algorithm === 'bnb' && itemCount > 30) {
showAlgorithmWarning = true;
}
document.getElementById('algorithm-warning').style.display =
showAlgorithmWarning ? 'block' : 'none';
return !(minValue > maxValue || minWeight > maxWeight);
}
// Add event listeners for validation
document.getElementById('min-value').addEventListener('change', validateInputs);
document.getElementById('max-value').addEventListener('change', validateInputs);
document.getElementById('min-weight').addEventListener('change', validateInputs);
document.getElementById('max-weight').addEventListener('change', validateInputs);
document.getElementById('item-count').addEventListener('change', validateInputs);
document.getElementById('capacity-input').addEventListener('change', validateInputs);
document.getElementById('algorithm-select').addEventListener('change', validateInputs);
// Update generateItems to use validation
function generateItems() {
// Validate inputs first
if (!validateInputs()) {
alert('Por favor, corrija os valores inválidos antes de gerar itens.');
return;
}
// Get the number of items to generate
const count = parseInt(itemCountInput.value);
console.log(`Generating ${count} items...`);
// Get the min/max values
const minValue = parseInt(document.getElementById('min-value').value);
const maxValue = parseInt(document.getElementById('max-value').value);
const minWeight = parseInt(document.getElementById('min-weight').value);
const maxWeight = parseInt(document.getElementById('max-weight').value);
try {
// Generate new random items
items = [];
for (let i = 0; i < count; i++) {
// Generate random value and weight within ranges
const value = Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue;
const weight = Math.floor(Math.random() * (maxWeight - minWeight + 1)) + minWeight;
// Create a new item with a unique ID
const item = {
id: i + 1,
value: value,
weight: weight
};
// Add to items array
items.push(item);
}
console.log(`Successfully generated ${items.length} items:`, items);
// Reset selected items and optimal solution
selectedItems = [];
optimalSolution = null;
// Render the items on the page
renderItems();
updateSelection();
resultPanel.style.display = 'none';
} catch (error) {
console.error("Error generating items:", error);
alert("Erro ao gerar itens: " + error.message);
}
}
function renderItems() {
// Clear the container first
itemsContainer.innerHTML = '';
if (!items || items.length === 0) {
itemsContainer.innerHTML = '<p>Nenhum item disponível. Gere itens primeiro.</p>';
return;
}
console.log(`Rendering ${items.length} items:`, items);
// Create a div for each item
items.forEach(item => {
const itemElement = document.createElement('div');
itemElement.classList.add('item');
itemElement.dataset.id = item.id;
// Set the content of the div
itemElement.innerHTML = `
<div class="item-value">$${item.value}</div>
<div class="item-weight">${item.weight} kg</div>
`;
// Add event listener for item selection
itemElement.addEventListener('click', () => {
toggleItemSelection(item);
});
// Append the element to the container
itemsContainer.appendChild(itemElement);
});
}
function toggleItemSelection(item) {
const index = selectedItems.findIndex(i => i.id === item.id);
if (index === -1) {
selectedItems.push(item);
} else {
selectedItems.splice(index, 1);
}
updateSelection();
highlightSelectedItems();
}
function highlightSelectedItems() {
console.log("Highlighting selected items. Selected:", selectedItems, "Optimal:", optimalSolution);
// Clear previous selections
document.querySelectorAll('.item').forEach(el => {
el.classList.remove('selected');
el.classList.remove('in-optimal');
});
// Highlight currently selected items
if (selectedItems && selectedItems.length > 0) {
selectedItems.forEach(item => {
const itemElement = document.querySelector(`.item[data-id="${item.id}"]`);
if (itemElement) {
itemElement.classList.add('selected');
console.log(`Highlighted selected item ${item.id}`);
} else {
console.warn(`Could not find element for selected item ${item.id}`);
}
});
}
// Highlight items that belong to the optimal solution (if available)
if (optimalSolution && Array.isArray(optimalSolution) && optimalSolution.length > 0) {
optimalSolution.forEach(item => {
if (!item || !item.id) {
console.warn("Invalid item in optimal solution:", item);
return;
}
const itemElement = document.querySelector(`.item[data-id="${item.id}"]`);
if (itemElement) {
itemElement.classList.add('in-optimal');
console.log(`Highlighted optimal item ${item.id}`);
} else {
console.warn(`Could not find element for optimal item ${item.id}`);
}
});
}
}
function updateSelection() {
const currentWeight = calculateTotalWeight(selectedItems);
const currentValue = calculateTotalValue(selectedItems);
currentWeightSpan.textContent = currentWeight;
selectionValueSpan.textContent = currentValue;
selectionWeightSpan.textContent = currentWeight;
updateCapacityBar();
renderSelectedItems();
}
function updateCapacityBar() {
const currentWeight = calculateTotalWeight(selectedItems);
const percentage = Math.min((currentWeight / capacity) * 100, 100);
capacityFill.style.width = `${percentage}%`;
capacityFill.style.backgroundColor = (currentWeight > capacity) ? 'var(--danger)' : 'var(--primary)';
}
function renderSelectedItems() {
selectedItemsContainer.innerHTML = '';
if (selectedItems.length === 0) {
const emptyMessage = document.createElement('p');
emptyMessage.textContent = 'Nenhum item selecionado ainda. Clique nos itens para adicioná-los à sua mochila.';
selectedItemsContainer.appendChild(emptyMessage);
return;
}
selectedItems.forEach(item => {
const itemElement = document.createElement('div');
itemElement.classList.add('item', 'selected');
itemElement.innerHTML = `
<div class="item-value">$${item.value}</div>
<div class="item-weight">${item.weight} kg</div>
`;
selectedItemsContainer.appendChild(itemElement);
});
}
function calculateTotalWeight(itemsList) {
return itemsList.reduce((sum, item) => sum + item.weight, 0);
}
function calculateTotalValue(itemsList) {
return itemsList.reduce((sum, item) => sum + item.value, 0);
}
function resetSelection() {
selectedItems = [];
updateSelection();
highlightSelectedItems();
}
// ----- Provided Brute Force Method -----
function bruteForceKnapsack(items, capacity) {
console.log("Running bruteForceKnapsack with items:", items);
let bestValue = 0;
let bestCombination = [];
const n = items.length;
const totalCombinations = 1 << n; // 2^n combinations
let steps = 0;
const allCombinations = [];
for (let i = 0; i < totalCombinations; i++) {
steps++;
let currentValue = 0;
let currentWeight = 0;
let combination = [];
for (let j = 0; j < n; j++) {
steps++;
if (i & (1 << j)) {
// Make sure we include the full item object
const item = items[j];
currentValue += item.value;
currentWeight += item.weight;
combination.push(item);
}
}
allCombinations.push({
combination,
value: currentValue,
weight: currentWeight,
valid: currentWeight <= capacity
});
if (currentWeight <= capacity && currentValue > bestValue) {
bestValue = currentValue;
bestCombination = [...combination]; // Create a copy to avoid reference issues
}
}
console.log("Brute force complete. Best combination:", bestCombination);
return { bestValue, bestCombination, steps, allCombinations };
}
function solveKnapsack() {
const algorithm = document.getElementById('algorithm-select').value;
const startTime = performance.now();
stepsCounter = 0;
// Clear any previous results
optimalSolution = null;
resultPanel.style.display = 'none';
// Ensure all input validations pass
if (!validateInputs()) {
alert('Por favor, corrija os valores inválidos antes de continuar.');
return;
}
// Check if items exist
if (!items || items.length === 0) {
alert('Não há itens para resolver. Por favor, gere itens primeiro.');
return;
}
// Update capacity from input (in case it was changed)
capacity = parseInt(capacityInput.value);
console.log(`Solving with algorithm: ${algorithm}, capacity: ${capacity}, items:`, items);
try {
switch(algorithm) {
case 'bruteforce':
const result = bruteForceKnapsack(items, capacity);
optimalSolution = result.bestCombination;
stepsCounter = result.steps;
break;
case 'dp':
optimalSolution = solveKnapsackDP();
break;
case 'dp_recursive':
optimalSolution = solveKnapsackDPRecursive();
break;
case 'greedy':
optimalSolution = solveKnapsackGreedy();
break;
case 'bnb':
optimalSolution = solveKnapsackBnB();
break;
case 'ga':
optimalSolution = solveKnapsackGA();
break;
case 'sa':
optimalSolution = solveKnapsackSA();
break;
case 'aco':
optimalSolution = solveKnapsackACO();
break;
case 'pso':
optimalSolution = solveKnapsackPSO();
break;
case 'cuckoo':
optimalSolution = solveKnapsackCuckoo();
break;
case 'approx':
optimalSolution = solveKnapsackApprox();
break;
case 'fptas':
optimalSolution = solveKnapsackFPTAS();
break;
default:
alert('Algoritmo não encontrado!');
return;
}
console.log("Optimal solution:", optimalSolution);
// Handle case if optimalSolution is invalid
if (!optimalSolution) {
alert('Erro ao calcular a solução. Verifique o console para mais informações.');
return;
}
const endTime = performance.now();
const executionTime = endTime - startTime;
// Display results
document.getElementById('execution-time').textContent = `${executionTime.toFixed(2)} ms`;
bestValueSpan.textContent = calculateTotalValue(optimalSolution);
totalWeightSpan.textContent = calculateTotalWeight(optimalSolution);
stepsTakenSpan.textContent = stepsCounter;
// Show optimal solution items
optimalSolutionDiv.innerHTML = '';
if (optimalSolution.length === 0) {
optimalSolutionDiv.innerHTML = '<p>Nenhum item pode ser adicionado dentro da capacidade.</p>';
} else {
optimalSolution.forEach(item => {
const itemElement = document.createElement('div');
itemElement.classList.add('item');
itemElement.classList.add('in-optimal');
itemElement.innerHTML = `
<div class="item-value">$${item.value}</div>
<div class="item-weight">${item.weight}kg</div>
`;
optimalSolutionDiv.appendChild(itemElement);
});
}
// Show result panel
resultPanel.style.display = 'block';
// Update items visualization to highlight optimal items
highlightSelectedItems();
} catch (error) {
console.error("Error solving knapsack:", error);
alert(`Erro ao calcular a solução: ${error.message}\n\nVerifique o console para mais detalhes.`);
}
}
// ----- 1. Dynamic Programming -----
function solveKnapsackDP() {
const startTime = performance.now();
const n = items.length;
let steps = 0;
// Create dp table: rows for items and columns for weight capacities
const dp = Array(n + 1).fill(0).map(() => Array(capacity + 1).fill(0));
// Table for item inclusion reconstruction
for (let i = 1; i <= n; i++) {
const item = items[i - 1];
for (let w = 0; w <= capacity; w++) {
steps++;
if (item.weight > w) {
dp[i][w] = dp[i - 1][w];
} else {
dp[i][w] = Math.max(
dp[i - 1][w],
dp[i - 1][w - item.weight] + item.value
);
}
}
}
// Reconstruction to get selected items
let res = dp[n][capacity];
let w = capacity;
const selected = [];
for (let i = n; i > 0 && res > 0; i--) {
steps++;
if (res !== dp[i - 1][w]) {
const item = items[i - 1];
selected.push(item);
res -= item.value;
w -= item.weight;
}
}
const endTime = performance.now();
const executionTime = endTime - startTime;
document.getElementById('execution-time').textContent = `${executionTime.toFixed(2)} ms`;
optimalSolution = { bestValue: dp[n][capacity], bestCombination: selected, steps };
bestValueSpan.textContent = optimalSolution.bestValue;
totalWeightSpan.textContent = calculateTotalWeight(selected);
stepsTakenSpan.textContent = steps;
resultPanel.style.display = 'block';
optimalSolutionDiv.innerHTML = `
<p>Solução DP inclui os seguintes itens:</p>
<ul>
${selected.map(item => `<li>Item ${item.id}: Valor = $${item.value}, Peso = ${item.weight} kg</li>`).join('')}
</ul>
<p>Valor Total: $${optimalSolution.bestValue}</p>
<p>Peso Total: ${calculateTotalWeight(selected)} kg</p>
`;
highlightSelectedItems();
}
// ----- 2. Greedy Approach (by value/weight ratio) -----
function solveKnapsackGreedy() {
const startTime = performance.now();
let steps = 0;
// Sort items by descending value/weight ratio
const sortedItems = [...items].sort((a, b) => {
steps++;
return (b.value / b.weight) - (a.value / a.weight);
});
let currentWeight = 0;
const selected = [];
for (const item of sortedItems) {
steps++;
if (currentWeight + item.weight <= capacity) {
selected.push(item);
currentWeight += item.weight;
}
}
const totalValue = calculateTotalValue(selected);
const endTime = performance.now();
const executionTime = endTime - startTime;
document.getElementById('execution-time').textContent = `${executionTime.toFixed(2)} ms`;
optimalSolution = { bestValue: totalValue, bestCombination: selected, steps };
bestValueSpan.textContent = optimalSolution.bestValue;
totalWeightSpan.textContent = currentWeight;
stepsTakenSpan.textContent = steps;
resultPanel.style.display = 'block';
optimalSolutionDiv.innerHTML = `
<p>Solução Greedy inclui os seguintes itens:</p>
<ul>
${selected.map(item => `<li>Item ${item.id}: Valor = $${item.value}, Peso = ${item.weight} kg</li>`).join('')}
</ul>
<p>Valor Total: $${totalValue}</p>
<p>Peso Total: ${currentWeight} kg</p>
`;
highlightSelectedItems();
}
// ----- 3. Branch and Bound -----
function solveKnapsackBnB() {
const startTime = performance.now();
let steps = 0;
// Sort items by descending ratio (helps bounding)
const sortedItems = [...items].sort((a, b) => {
steps++;
return (b.value / b.weight) - (a.value / a.weight);
});
let bestValue = 0;
let bestCombination = [];
function bound(level, currentValue, currentWeight) {
steps++;
// Upper bound using fractional knapsack
let boundVal = currentValue;
let totalWeight = currentWeight;
for (let i = level; i < sortedItems.length; i++) {
steps++;
if (totalWeight + sortedItems[i].weight <= capacity) {
totalWeight += sortedItems[i].weight;
boundVal += sortedItems[i].value;
} else {
const remain = capacity - totalWeight;
boundVal += sortedItems[i].value * (remain / sortedItems[i].weight);
break;
}
}
return boundVal;
}
function branch(level, currentValue, currentWeight, combination) {
steps++;
if (currentWeight > capacity) return;
if (level === sortedItems.length) {
if (currentValue > bestValue) {
bestValue = currentValue;
bestCombination = combination.slice();
}
return;
}
if (bound(level, currentValue, currentWeight) < bestValue) return; // prune
// Explore including current item
combination.push(sortedItems[level]);
branch(level + 1, currentValue + sortedItems[level].value, currentWeight + sortedItems[level].weight, combination);
combination.pop();
// Explore excluding current item
branch(level + 1, currentValue, currentWeight, combination);
}
branch(0, 0, 0, []);
const endTime = performance.now();
const executionTime = endTime - startTime;
document.getElementById('execution-time').textContent = `${executionTime.toFixed(2)} ms`;
optimalSolution = { bestValue, bestCombination, steps };
bestValueSpan.textContent = bestValue;
totalWeightSpan.textContent = calculateTotalWeight(bestCombination);
stepsTakenSpan.textContent = steps;
resultPanel.style.display = 'block';
optimalSolutionDiv.innerHTML = `
<p>Solução Branch and Bound inclui os seguintes itens:</p>
<ul>
${bestCombination.map(item => `<li>Item ${item.id}: Valor = $${item.value}, Peso = ${item.weight} kg</li>`).join('')}
</ul>
<p>Valor Total: $${bestValue}</p>
<p>Peso Total: ${calculateTotalWeight(bestCombination)} kg</p>
`;
highlightSelectedItems();
}
// ----- 4. Genetic Algorithm -----
function solveKnapsackGA() {
const startTime = performance.now();
let steps = 0;
// Parameters for GA
const populationSize = 50;
const generations = 100;
const mutationRate = 0.05;
const n = items.length;
// Create an initial population (each individual is an array of 0s and 1s)
function createIndividual() {
steps++;
return Array.from({ length: n }, () => Math.random() < 0.5 ? 1 : 0);
}
let population = Array.from({ length: populationSize }, createIndividual);
// Fitness function: if overweight, assign 0 fitness; otherwise, use total value.
function fitness(individual) {
steps++;
let totalWeight = 0;
let totalValue = 0;
for (let i = 0; i < n; i++) {
steps++;
if (individual[i] === 1) {
totalWeight += items[i].weight;
totalValue += items[i].value;
}
}
return totalWeight <= capacity ? totalValue : 0;
}
// Selection: tournament selection
function selectIndividual() {
steps++;
const tournamentSize = 3;
let best = null;
for (let i = 0; i < tournamentSize; i++) {
steps++;
const ind = population[Math.floor(Math.random() * populationSize)];
if (best === null || fitness(ind) > fitness(best)) {
best = ind;
}
}
return best.slice();
}
// Crossover: single-point crossover
function crossover(parent1, parent2) {
steps++;
const crossoverPoint = Math.floor(Math.random() * n);
return parent1.slice(0, crossoverPoint).concat(parent2.slice(crossoverPoint));
}
// Mutation: flip bit with some probability
function mutate(individual) {
steps++;
return individual.map(bit => Math.random() < mutationRate ? 1 - bit : bit);
}
let bestIndividual = null;
let bestIndividualFitness = 0;
// Evolve population
for (let gen = 0; gen < generations; gen++) {
steps++;
const newPopulation = [];
for (let i = 0; i < populationSize; i++) {
steps++;
const parent1 = selectIndividual();
const parent2 = selectIndividual();
let child = crossover(parent1, parent2);
child = mutate(child);
newPopulation.push(child);
const childFitness = fitness(child);
if (childFitness > bestIndividualFitness) {
bestIndividualFitness = childFitness;
bestIndividual = child.slice();
}
}
population = newPopulation;
}
// Convert bestIndividual into a set of items
const selected = [];
for (let i = 0; i < n; i++) {
steps++;
if (bestIndividual[i] === 1) {
selected.push(items[i]);
}
}
const endTime = performance.now();
const executionTime = endTime - startTime;
document.getElementById('execution-time').textContent = `${executionTime.toFixed(2)} ms`;
optimalSolution = { bestValue: bestIndividualFitness, bestCombination: selected, steps };
bestValueSpan.textContent = optimalSolution.bestValue;
totalWeightSpan.textContent = calculateTotalWeight(selected);
stepsTakenSpan.textContent = steps;
resultPanel.style.display = 'block';
optimalSolutionDiv.innerHTML = `
<p>Solução Algoritmo Genético inclui os seguintes itens:</p>
<ul>
${selected.map(item => `<li>Item ${item.id}: Valor = $${item.value}, Peso = ${item.weight} kg</li>`).join('')}
</ul>
<p>Valor Total: $${optimalSolution.bestValue}</p>
<p>Peso Total: ${calculateTotalWeight(selected)} kg</p>
`;
highlightSelectedItems();
}
// ----- 5. Simulated Annealing -----
function solveKnapsackSA() {
const startTime = performance.now();
let steps = 0;
// Parameters for SA
let temperature = 100;
const coolingRate = 0.95;
const iterationsPerTemp = 50;
const n = items.length;
// Generate an initial random solution (binary vector)
function randomSolution() {
steps++;
return Array.from({ length: n }, () => Math.random() < 0.5 ? 1 : 0);
}
// Compute fitness for SA (if overweight, fitness = 0)
function solutionFitness(sol) {
steps++;
let weight = 0, value = 0;
for (let i = 0; i < n; i++) {
steps++;
if (sol[i] === 1) {
weight += items[i].weight;
value += items[i].value;
}
}
return weight <= capacity ? value : 0;
}
// Generate neighbor by flipping one random bit
function getNeighbor(sol) {
steps++;
const neighbor = sol.slice();
const index = Math.floor(Math.random() * n);
neighbor[index] = 1 - neighbor[index];
return neighbor;
}
let currentSolution = randomSolution();
let currentFitness = solutionFitness(currentSolution);
let bestSolution = currentSolution.slice();
let bestFitness = currentFitness;
while (temperature > 1) {
steps++;
for (let i = 0; i < iterationsPerTemp; i++) {
steps++;
const neighbor = getNeighbor(currentSolution);
const neighborFitness = solutionFitness(neighbor);
const delta = neighborFitness - currentFitness;
if (delta > 0 || Math.exp(delta / temperature) > Math.random()) {
currentSolution = neighbor;
currentFitness = neighborFitness;
}
if (currentFitness > bestFitness) {
bestSolution = currentSolution.slice();
bestFitness = currentFitness;
}
}
temperature *= coolingRate;
}
const selected = [];
let totalWeight = 0;
for (let i = 0; i < n; i++) {
steps++;
if (bestSolution[i] === 1) {
selected.push(items[i]);
totalWeight += items[i].weight;
}
}
const endTime = performance.now();
const executionTime = endTime - startTime;
document.getElementById('execution-time').textContent = `${executionTime.toFixed(2)} ms`;
optimalSolution = { bestValue: bestFitness, bestCombination: selected, steps };
bestValueSpan.textContent = bestFitness;
totalWeightSpan.textContent = totalWeight;
stepsTakenSpan.textContent = steps;
resultPanel.style.display = 'block';
optimalSolutionDiv.innerHTML = `
<p>Solução Simulated Annealing inclui os seguintes itens:</p>
<ul>
${selected.map(item => `<li>Item ${item.id}: Valor = $${item.value}, Peso = ${item.weight} kg</li>`).join('')}
</ul>
<p>Valor Total: $${bestFitness}</p>
<p>Peso Total: ${totalWeight} kg</p>
`;
highlightSelectedItems();
}
// ----- 6. Approximation Algorithm (Simple Heuristic) -----
function solveKnapsackApprox() {
const startTime = performance.now();
let steps = 0;
// A simple heuristic: sort by value descending (ignoring weight) and add items
const sortedItems = [...items].sort((a, b) => {
steps++;
return b.value - a.value;
});
let totalWeight = 0;
const selected = [];
for (const item of sortedItems) {
steps++;
if (totalWeight + item.weight <= capacity) {
selected.push(item);
totalWeight += item.weight;
}
}
const totalValue = calculateTotalValue(selected);
const endTime = performance.now();
const executionTime = endTime - startTime;
document.getElementById('execution-time').textContent = `${executionTime.toFixed(2)} ms`;
optimalSolution = { bestValue: totalValue, bestCombination: selected, steps };
bestValueSpan.textContent = totalValue;
totalWeightSpan.textContent = totalWeight;
stepsTakenSpan.textContent = steps;
resultPanel.style.display = 'block';
optimalSolutionDiv.innerHTML = `
<p>Solução Aproximação inclui os seguintes itens:</p>
<ul>
${selected.map(item => `<li>Item ${item.id}: Valor = $${item.value}, Peso = ${item.weight} kg</li>`).join('')}
</ul>
<p>Valor Total: $${totalValue}</p>
<p>Peso Total: ${totalWeight} kg</p>
`;
highlightSelectedItems();
}
// ----- 7. FPTAS (Fully Polynomial Time Approximation Scheme) -----
function solveKnapsackFPTAS() {
const startTime = performance.now();
let steps = 0;
// User defined epsilon for approximation precision. Smaller epsilon -> more accurate and slower.
const epsilon = 0.2; // You can allow user to change this via an input
const n = items.length;
const maxValue = Math.max(...items.map(i => i.value));
// Scaling factor
const K = (epsilon * maxValue) / n;
// Scale item values
const scaledValues = items.map(item => {
steps++;
return Math.floor(item.value / K);
});
// DP based on scaled values
const sumScaled = scaledValues.reduce((acc, cur) => {
steps++;
return acc + cur;
}, 0);
const dp = Array(n + 1).fill(0).map(() => Array(sumScaled + 1).fill(Infinity));
dp[0][0] = 0;
for (let i = 1; i <= n; i++) {
const weight = items[i - 1].weight;
const valueScaled = scaledValues[i - 1];
for (let j = 0; j <= sumScaled; j++) {
steps++;
if (j < valueScaled) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = Math.min(dp[i - 1][j], dp[i - 1][j - valueScaled] + weight);
}
}
}
// Find the maximum scaled value that fits in capacity
let bestScaledValue = 0;
for (let j = 0; j <= sumScaled; j++) {
steps++;
if (dp[n][j] <= capacity) bestScaledValue = j;
}
// Now reconstruct selected items (a simple reconstruction by iterating backwards)
const selected = [];
let j = bestScaledValue;
for (let i = n; i > 0; i--) {
steps++;
if (dp[i][j] !== dp[i - 1][j]) {
selected.push(items[i - 1]);
j -= scaledValues[i - 1];
}
}
const approxValue = calculateTotalValue(selected);
const endTime = performance.now();
const executionTime = endTime - startTime;
document.getElementById('execution-time').textContent = `${executionTime.toFixed(2)} ms`;
optimalSolution = { bestValue: approxValue, bestCombination: selected, steps };
bestValueSpan.textContent = approxValue;
totalWeightSpan.textContent = calculateTotalWeight(selected);
stepsTakenSpan.textContent = steps;
resultPanel.style.display = 'block';
optimalSolutionDiv.innerHTML = `
<p>Solução FPTAS inclui os seguintes itens:</p>
<ul>
${selected.map(item => `<li>Item ${item.id}: Valor = $${item.value}, Peso = ${item.weight} kg</li>`).join('')}
</ul>
<p>Valor Total (Aproximado): $${approxValue}</p>
<p>Peso Total: ${calculateTotalWeight(selected)} kg</p>
`;
highlightSelectedItems();