Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import static java.lang.Math.min;
- public abstract class KnapsackStrategy implements Strategy{
- private int fromOneRod;
- private PartitionSet [] bestCut;
- private PartitionSet [] oneRod;
- private Offer offer;
- private Requirements requirements;
- private int writes;
- public PartitionSet solve(Offer offer, Requirements requirements) {
- Mask mask = new Mask(requirements);
- this.requirements = requirements;
- this.offer = offer;
- int sizeOfDP = 1<<requirements.getRods().length;
- fromOneRod = 0;
- writes = 0;
- bestCut = new PartitionSet[sizeOfDP];
- oneRod = new PartitionSet[sizeOfDP];
- bestCut[0] = new PartitionSet(0, 0, new RodPartition[0]);
- PartitionSet result = getBestCut((Mask) mask.clone());
- System.out.println(fromOneRod);
- System.out.println(writes);
- return result;
- }
- public PartitionSet getBestCut(Mask mask){
- int positionFromMask = mask.getPosition();
- if(bestCut[positionFromMask] != null){
- return bestCut[positionFromMask];
- }
- writes +=1;
- Mask ourMask = (Mask) mask.clone();
- while(ourMask.nextSubset(mask)){
- PartitionSet set1 = getFromOneRod(ourMask.getComplement(mask));
- if(! set1.isReachable()){
- continue;
- }
- PartitionSet set2 = getBestCut(ourMask);
- bestCut[positionFromMask]=chooseBestSet(bestCut[positionFromMask], new PartitionSet(set1, set2));
- }
- return bestCut[positionFromMask];
- }
- private PartitionSet getFromOneRod(Mask mask){
- //TODO tablicowac
- if(oneRod[mask.getPosition()] == null){
- Rod[] fulfilled = requirements.getRods(mask);
- int fulfilledLength = 0;
- for(Rod rod : fulfilled){
- fulfilledLength += rod.getLength();
- }
- Rod source = chooseBestRod(offer, fulfilledLength);
- if(source == null){
- return PartitionSet.getDummy();
- }
- Integer[] lengths = new Integer[fulfilled.length];
- for(int i = 0; i< fulfilled.length; i++) {
- lengths[i] = fulfilled[i].getLength();
- }
- int wasteSum = source.getLength()-fulfilledLength;
- RodPartition[] partitions = new RodPartition[1];
- partitions[0] = new RodPartition(source.getLength(), lengths);
- fromOneRod +=1;
- oneRod[mask.getPosition()] = new PartitionSet(source.getPrice(), wasteSum, partitions);
- }
- return oneRod[mask.getPosition()];
- }
- abstract protected Rod chooseBestRod(Offer offer, int length);
- abstract protected PartitionSet chooseBestSet(PartitionSet set1, PartitionSet set2);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement