# include <stdio.h>
# include <stdlib.h>
// ÇÁ·Î±×·¥ 5.2¿¡¼ ´ÙÀ½°ú °°Àº ºÎºÐÀ» º¹»çÇÑ´Ù.
// ================ ¿øÇüÅ¥ ÄÚµå ½ÃÀÛ =================
typedef struct { // ¿ä¼Ò ŸÀÔ
int id;
int arrival_time;
int service_time;
} element; // ±³Ã¼!
// ================ ¿øÇüÅ¥ ÄÚµå Á¾·á =================
// ===== ¿øÇüÅ¥ ÄÚµå ½ÃÀÛ ======
#define MAX_QUEUE_SIZE 100
typedef struct { // Å¥ ŸÀÔ
element data[MAX_QUEUE_SIZE];
int front, rear;
} QueueType;
// ¿À·ù ÇÔ¼ö
void error(char *message)
{
fprintf(stderr, "%s\n", message);
exit(1);
}
// °ø¹é »óÅ °ËÃâ ÇÔ¼ö
void init_queue(QueueType *q)
{
q->front = q->rear = 0;
}
// °ø¹é »óÅ °ËÃâ ÇÔ¼ö
int is_empty(QueueType *q)
{
return (q->front == q->rear);
}
// Æ÷È »óÅ °ËÃâ ÇÔ¼ö
int is_full(QueueType *q)
{
return ((q->rear + 1) % MAX_QUEUE_SIZE == q->front);
}
// ¿øÇüÅ¥ Ãâ·Â ÇÔ¼ö
void queue_print(QueueType *q)
{
printf("QUEUE(front=%d rear=%d) = ", q->front, q->rear);
if (!is_empty(q)) {
int i = q->front;
do {
i = (i + 1) % (MAX_QUEUE_SIZE);
printf("%d | ", q->data[i]);
if (i == q->rear)
break;
} while (i != q->front);
}
printf("\n");
}
// »ðÀÔ ÇÔ¼ö
void enqueue(QueueType *q, element item)
{
if (is_full(q))
error("Å¥°¡ Æ÷È»óÅÂÀÔ´Ï´Ù");
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
q->data[q->rear] = item;
}
// »èÁ¦ ÇÔ¼ö
element dequeue(QueueType *q)
{
if (is_empty(q))
error("Å¥°¡ °ø¹é»óÅÂÀÔ´Ï´Ù");
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
return q->data[q->front];
}
// »èÁ¦ ÇÔ¼ö
element peek(QueueType *q)
{
if (is_empty(q))
error("Å¥°¡ °ø¹é»óÅÂÀÔ´Ï´Ù");
return q->data[(q->front + 1) % MAX_QUEUE_SIZE];
}
// ===== ¿øÇüÅ¥ ÄÚµå ³¡ ======
int main(void)
{
int minutes = 60;
int total_wait = 0;
int total_customers = 0;
int service_time = 0;
int service_customer;
QueueType queue;
init_queue(&queue);
srand(34);
for (int clock = 0; clock < minutes; clock++) {
printf("ÇöÀç½Ã°¢=%d\n", clock);
if ((rand()%10) < 7) {
element customer;
customer.id = total_customers++;
customer.arrival_time = clock;
customer.service_time = rand() % 10+1;
enqueue(&queue, customer);
printf("°í°´ %dÀÌ %dºÐ¿¡ µé¾î¿É´Ï´Ù. ¾÷¹«Ã³¸®½Ã°£= %dºÐ\n",
customer.id, customer.arrival_time, customer.service_time);
}
if (service_time > 0) {
printf("°í°´ %d ¾÷¹«Ã³¸®ÁßÀÔ´Ï´Ù. \n", service_customer);
service_time--;
}
else {
if (!is_empty(&queue)) {
element customer = dequeue(&queue);
service_customer = customer.id;
service_time = customer.service_time;
printf("°í°´ %dÀÌ %dºÐ¿¡ ¾÷¹«¸¦ ½ÃÀÛÇÕ´Ï´Ù. ´ë±â½Ã°£Àº %dºÐÀ̾ú½À´Ï´Ù.\n",
customer.id, clock, clock - customer.arrival_time);
total_wait += clock - customer.arrival_time;
}
}
}
printf("Àüü ´ë±â ½Ã°£=%dºÐ \n", total_wait);
printf("1Àδç Æò±Õ ´ë±â ½Ã°£=%lfºÐ \n", (double)total_wait/(double)(service_customer+1));
return 0;
}