|
| 1 | +import java.util.Arrays; |
| 2 | +import java.util.Collections; |
| 3 | +import java.util.List; |
| 4 | + |
| 5 | +public class ElevatorAlgorithm { |
| 6 | + |
| 7 | + static void startCSCAN(int pos, List<Integer> disk_requests) |
| 8 | + { |
| 9 | + System.out.println("Using C-SCAN algorithm on pending dist requests: " + disk_requests); |
| 10 | + System.out.println("Starting position is: " + pos + "\n"); |
| 11 | + |
| 12 | + if (disk_requests.size() == 0) |
| 13 | + { |
| 14 | + System.out.println("Nothing to do."); |
| 15 | + } |
| 16 | + |
| 17 | + Collections.sort(disk_requests); |
| 18 | + |
| 19 | + int next_array_pos = disk_requests.stream() |
| 20 | + .map(disk_requests::indexOf) |
| 21 | + .filter(x -> disk_requests.get(x) > pos) |
| 22 | + .findFirst().orElse(0); |
| 23 | + |
| 24 | + int curr_position = pos; |
| 25 | + int seek_number = 1; |
| 26 | + int motion_sum = 0; |
| 27 | + |
| 28 | + for (int i = 0; i < disk_requests.size(); i++) |
| 29 | + { |
| 30 | + if (next_array_pos == 0 && curr_position != 0) |
| 31 | + { |
| 32 | + curr_position = 0; |
| 33 | + System.out.println("Seek " + seek_number + ": returning head to track 0, motion: 0"); |
| 34 | + seek_number++; |
| 35 | + } |
| 36 | + |
| 37 | + int next_position = disk_requests.get(next_array_pos); |
| 38 | + int motion = Math.abs(curr_position-next_position); |
| 39 | + System.out.println("Seek " + seek_number + ": " + next_position + "-" + curr_position + " motion: " + motion); |
| 40 | + |
| 41 | + seek_number++; |
| 42 | + motion_sum += motion; |
| 43 | + |
| 44 | + curr_position = next_position; |
| 45 | + next_array_pos = (next_array_pos+1)%disk_requests.size(); |
| 46 | + } |
| 47 | + |
| 48 | + System.out.println("\nTotal motion C-SCAN: " + motion_sum); |
| 49 | + } |
| 50 | + |
| 51 | + public static void main(String... arg) |
| 52 | + { |
| 53 | + int pos = 35; |
| 54 | + |
| 55 | + List<Integer> disk_request_list = Arrays.asList(100, 50, 10, 20, 75); |
| 56 | + |
| 57 | + startCSCAN(pos, disk_request_list); |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | +} |
0 commit comments