No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RandomSolver.java 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package jobshop.solvers;
  2. import jobshop.*;
  3. import jobshop.encodings.JobNumbers;
  4. import jobshop.encodings.Schedule;
  5. import java.util.Optional;
  6. import java.util.Random;
  7. /** A solver that generates random solutions until a deadline is met.
  8. * Then returns the best solution that was generated.
  9. */
  10. public class RandomSolver implements Solver {
  11. @Override
  12. public Result solve(Instance instance, long deadline) {
  13. Random generator = new Random(0);
  14. JobNumbers sol = new JobNumbers(instance);
  15. for(int j = 0 ; j<instance.numJobs ; j++) {
  16. for(int t = 0 ; t<instance.numTasks ; t++) {
  17. sol.jobs[sol.nextToSet++] = j;
  18. }
  19. }
  20. Optional<Schedule> best = sol.toSchedule();
  21. while(deadline - System.currentTimeMillis() > 1) {
  22. shuffleArray(sol.jobs, generator);
  23. Optional<Schedule> candidate = sol.toSchedule();
  24. if(candidate.isPresent()) {
  25. if (best.isEmpty() || candidate.get().makespan() < best.get().makespan()) {
  26. best = candidate;
  27. }
  28. }
  29. }
  30. return new Result(instance, best, Result.ExitCause.Timeout);
  31. }
  32. /** Simple Fisher–Yates array shuffling */
  33. private static void shuffleArray(int[] array, Random random)
  34. {
  35. int index;
  36. for (int i = array.length - 1; i > 0; i--)
  37. {
  38. index = random.nextInt(i + 1);
  39. if (index != i)
  40. {
  41. array[index] ^= array[i];
  42. array[i] ^= array[index];
  43. array[index] ^= array[i];
  44. }
  45. }
  46. }
  47. }