Skip to content

Instantly share code, notes, and snippets.

@dziemborowicz
Created July 13, 2013 20:21
Show Gist options
  • Save dziemborowicz/5992080 to your computer and use it in GitHub Desktop.
Save dziemborowicz/5992080 to your computer and use it in GitHub Desktop.
Solution in C to Round 3 of the 2013 Codehire Cup.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "codehire.h"
int main()
{
/* Read input */
char *input = readInput();
char *line1 = strtok(input, "\n");
char *line2 = strtok(NULL, "\n");
/* Parse elevator floors */
int elevators[5];
for (int i = 0; i < 5; i++) {
char *s = strtok(i == 0 ? line1 : NULL, ",");
elevators[i] = atoi(s);
}
/* Parse requests */
int request_floors[5];
int request_ages[5];
int num_requests = 0;
for (int i = 0; i < 5; i++) {
char *floor = strtok(i == 0 ? line2 : NULL, ",");
char *age = strtok(NULL, ";");
if (floor && age) {
request_floors[i] = atoi(floor);
request_ages[i] = atoi(age);
num_requests++;
}
}
/* Satisfy requests */
int output[5];
for (int i = 0; i < num_requests; i++) {
/* Find oldest request */
int oldest = 0;
for (int j = 1; j < num_requests; j++) {
if (request_ages[j] > request_ages[oldest]) {
oldest = j;
}
}
/* Find closest elevator */
int closest = 0;
for (int j = 1; j < 5; j++) {
if (abs(elevators[j] - request_floors[oldest]) < abs(elevators[closest] - request_floors[oldest])) {
closest = j;
}
}
output[oldest] = closest;
/* Mark off elevator and request */
elevators[closest] = 0x7FFFFFFF;
request_ages[oldest] = -1;
}
/* Print output */
for (int i = 0; i < num_requests; i++) {
printf(i == 0 ? "%d" : ",%d", output[i]);
}
/* Release memory */
free(input);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment