@Test public void testSolveByHeavierFirst(){ KnapsackInstanceWithSolution p = KnapsackInstanceWithSolution.problemP05(); boolean[] res = GreedyForKnapsack.solveByHeavierFirst(p.getProblem()); double fitness = p.getProblem().evaluate(res); assertEquals(47d, fitness, 0.001); double best = p.getBestFitness(); assertNotEquals(best, fitness); assertTrue(best > fitness); }
public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); }
GreedyForKnapsack { public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } }
GreedyForKnapsack { public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); }  }
GreedyForKnapsack { public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); }  static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); }
GreedyForKnapsack { public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); }  static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem);  }