-
Notifications
You must be signed in to change notification settings - Fork 2
/
RandomSearch.java
57 lines (49 loc) · 1.65 KB
/
RandomSearch.java
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
import java.util.*;
/**
* Random Search on a filled knapsack.
* @author Shalin Shah
* Email: [email protected]
*/
public class RandomSearch
{
public static KNode randomSearch(KNode sack)
{
int i = 0;
for(int n = 0; n < Constants.LOOP; n++)
{
BitSet array = sack.getKnapsackContents();
// remove a certain number of knapsack objects
for(int k = 0; k < Constants.LOOP; k++)
{
int rand = Util.generateRandomNumber(0, Constants.NUMBER_OBJECTS-1);
if(array.get(rand) == true)
{
array.set(rand, false);
i++;
}
if(i >= Constants.REMOVED)
{
i = 0;
break;
}
}
for(int m = 0; m < Constants.INNER_LOOP; m++)
{
int rand = Util.generateRandomNumber(0, Constants.NUMBER_OBJECTS-1);
if(array.get(rand) == false)
{
array.set(rand, true);
KNode temp = new KNode(array, 0);
if(!Util.isValidSolution(temp.getKnapsackContents()))
{
array.set(rand, false);
}
}
}
KNode tem = new KNode(array, 0);
if(Util.calculateValue(tem.getKnapsackContents()) > Util.calculateValue(sack.getKnapsackContents()))
sack = new KNode((BitSet)array.clone(), 0);
}
return sack;
}
}