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 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package jobshop.solvers;
  2. import jobshop.*;
  3. import jobshop.encodings.JobNumbers;
  4. import jobshop.encodings.Schedule;
  5. import java.awt.*;
  6. import java.util.ArrayList;
  7. import java.util.Optional;
  8. import java.util.Random;
  9. /** A solver that generates random solutions until a deadline is met.
  10. * Then returns the best solution that was generated.
  11. */
  12. public class RandomSolver implements Solver {
  13. int pts = 10;
  14. @Override
  15. public ArrayList<Result> solve(Instance instance, long deadline) {
  16. Random generator = new Random(0);
  17. JobNumbers sol = new JobNumbers(instance);
  18. // initialize a first solution to the problem.
  19. for (int j = 0; j < instance.numJobs; j++) {
  20. for (int t = 0; t < instance.numTasks; t++) {
  21. sol.addTaskOfJob(j);
  22. }
  23. }
  24. // best solution is currently the initial one
  25. Optional<Schedule> best = sol.toSchedule();
  26. // while we have some time left, generate new solutions by shuffling the current one
  27. while (deadline - System.currentTimeMillis() > 1) {
  28. shuffleArray(sol.jobs, generator);
  29. Optional<Schedule> candidate = sol.toSchedule();
  30. if (candidate.isPresent()) {
  31. if (best.isEmpty() || candidate.get().makespan() < best.get().makespan()) {
  32. best = candidate;
  33. }
  34. }
  35. }
  36. Result result = new Result(instance, best, Result.ExitCause.Timeout);
  37. ArrayList<Result> list = new ArrayList<>();
  38. int i;
  39. for (i=0; i<pts; i++) {
  40. list.add(result);
  41. }
  42. return list;
  43. }
  44. /**
  45. * Simple Fisher–Yates array shuffling
  46. */
  47. private static void shuffleArray(int[] array, Random randomNumberGenerator) {
  48. int index;
  49. for (int i = array.length - 1; i > 0; i--) {
  50. index = randomNumberGenerator.nextInt(i + 1);
  51. if (index != i) {
  52. array[index] ^= array[i];
  53. array[i] ^= array[index];
  54. array[index] ^= array[i];
  55. }
  56. }
  57. }
  58. @Override
  59. public void setIterMax(int iterMax) {
  60. }
  61. @Override
  62. public void setpts(int pts) {this.pts = pts;}
  63. }