/** * @param k knapsack to find a solution for * @return new knapsack with a random solution */ knapsack randomSolution(knapsack &k) { int i = 0; while (checkValid(k) && i < k.getNumObjects()) { int random = rand() % 2; if (random == 1 && (k.getCost() + k.getCost(i)) < k.getCostLimit()) k.select(i); else k.unSelect(i); i++; } return k; }
/** * Finds a local optimum and returns the result * * @param k knapsack to find local optimum for * @param int 2-opt or 3-opt * @return new knapsack with a local opt solution */ knapsack localOptimum(knapsack &k, int opt) { knapsack original(k); deque<knapsack> problem; knapsack bestFound = knapsack(k); try { for (int l = 0; l < k.getNumObjects() - 1; l++) { k = knapsack(original); if (!k.isSelected(l)) continue; k.unSelect(l); for (int m = l; m < k.getNumObjects() - 1; m++) { if (!k.isSelected(m)) continue; k.unSelect(m); if (opt == 3) { for (int n = m; n < k.getNumObjects() - 1; n++) { if (!k.isSelected(n)) continue; k.unSelect(n); problem.push_front(knapsack(k)); } } else problem.push_front(knapsack(k)); } } while(problem.size() > 0) { checkTimeLimit(); knapsack current = problem.front(); problem.pop_front(); deque<knapsack> solution; solution.push_front(knapsack(current)); int currentIndex = 0; while(solution.size() > 0) { knapsack currentSolution = solution.front(); solution.pop_front(); if (currentSolution.getValue() > bestFound.getValue()) { bestFound = knapsack(currentSolution); } if (currentIndex < currentSolution.getNumObjects() - 1) { if (!currentSolution.isSelected(currentIndex) && (currentSolution.getCost() + currentSolution.getCost(currentIndex)) < currentSolution.getCostLimit()) { currentSolution.select(currentIndex); solution.push_front(knapsack(currentSolution)); } currentIndex++; } } } return bestFound; } catch (baseException &ex) { cout << ex.what() << endl; return bestFound; } } //end localOptimum