Compare commits

..

2 Commits

Author SHA1 Message Date
f049e8aeff Cleanup 2023-12-02 23:16:56 -04:00
025b2640fc Pass tests 2023-12-02 22:41:41 -04:00
3 changed files with 20 additions and 24 deletions

View File

@@ -75,36 +75,30 @@ void destroyDiskQueue(DiskQueue *queue) {
free(queue); free(queue);
} }
int calcDistance(int position, int destination) {
if (position > destination) {
return destination + (9999 + 1 - position);
} else {
return destination - position;
}
}
DiskRequest* findClosest(DiskQueue *queue, int position, double time) { DiskRequest* findClosest(DiskQueue *queue, int position, double time) {
DiskRequest *current = queue->head; DiskRequest *current = queue->head;
DiskRequest *next = NULL; DiskRequest *closest = NULL;
DiskRequest *first = NULL;
while (current != NULL) { while (current != NULL) {
if (current->time <= time) { // Filter out requests that haven't come in yet if (current->time <= time) { // Filter out requests that haven't come in yet
if (first == NULL) { if (closest == NULL) { // If there is no closest yet, set it to the current
first = current; closest = current;
} else { } else {
if (current->position < first->position) { int closestDistance = calcDistance(position, closest->position); // Distance from the closest to the current position, negative means down (bad)
first = current; int currentDistance = calcDistance(position, current->position); // Distance from the current to the current position, negative means down (bad
} if (currentDistance < closestDistance) { // If the current is closer than the closest
} closest = current;
int currentDistance = current->position - position; // Distance from the current to the current position, negative means down (bad)
if (currentDistance > 0) { // If the current is up
if (next == NULL) { // If there is no next yet, set it to the current
next = current;
} else {
int nextDistance = next->position - position; // Distance from the next to the current position, negative means down (bad)
if (currentDistance < nextDistance) { // If the current is closer than the next
next = current;
}
} }
} }
} }
current = current->next; current = current->next;
} }
// If we didn't find a request that is above the current position, return the first as a fallback return closest;
if (next == NULL) { }
return first;
}
return next;
}

View File

@@ -26,3 +26,5 @@ DiskRequest *dequeue(DiskQueue *queue);
DiskRequest *findClosest(DiskQueue *queue, int position, double time); DiskRequest *findClosest(DiskQueue *queue, int position, double time);
void destroyDiskQueue(DiskQueue *queue); void destroyDiskQueue(DiskQueue *queue);
int calcDistance(int position, int destination);

View File

@@ -92,4 +92,4 @@ int main(int argc, char **argv) {
destroyDiskQueue(queue); destroyDiskQueue(queue);
return 0; return 0;
} }