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.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. // initialize a first solution to the problem.
  16. for(int j = 0 ; j<instance.numJobs ; j++) {
  17. for(int t = 0 ; t<instance.numTasks ; t++) {
  18. sol.addTask(j);
  19. }
  20. }
  21. // best solution is currently the initial one
  22. Optional<Schedule> best = sol.toSchedule();
  23. // while we have some time left, generate new solutions by shuffling the current one
  24. while(deadline - System.currentTimeMillis() > 1) {
  25. shuffleArray(sol.jobs, generator);
  26. Optional<Schedule> candidate = sol.toSchedule();
  27. if(candidate.isPresent()) {
  28. if (best.isEmpty() || candidate.get().makespan() < best.get().makespan()) {
  29. best = candidate;
  30. }
  31. }
  32. }
  33. return new Result(instance, best, Result.ExitCause.Timeout);
  34. }
  35. /** Simple Fisher–Yates array shuffling */
  36. private static void shuffleArray(int[] array, Random randomNumberGenerator)
  37. {
  38. int index;
  39. for (int i = array.length - 1; i > 0; i--)
  40. {
  41. index = randomNumberGenerator.nextInt(i + 1);
  42. if (index != i)
  43. {
  44. array[index] ^= array[i];
  45. array[i] ^= array[index];
  46. array[index] ^= array[i];
  47. }
  48. }
  49. }
  50. }