icp/oer/courses/c-newcomers/sections/04-supermarket/05-customers/solution.c

89 lines
1.9 KiB
C

;; This buffer is for text that is not saved, and for Lisp evaluation.
;; To create a file, visit it with C-x C-f and enter text in its buffer.
#include <stdio.h>
#include <stdbool.h>
#include "supermarket.h"
#define CUSTOMER_ITEM_COUNT 5
typedef struct
{
item Items[CUSTOMER_ITEM_COUNT];
int PackingSpeed;
}customer;
int main()
{
bool CustomersLeft = true;
int TimePast = 0;
customer CustomerQueue[3] = {
// NOTE: the {...} syntax is an easy way to initialize structs
{
{tissues, pasta, tomato_sauce, bread, butter},
2
},
{
{toothbrush, batteries, bread, bread, butter},
3
},
{
{bread, batteries, tomato_sauce, pasta, tissues},
9
}
};
int NextQueueIndex = 0;
initTimeTable();
int ItemsLeft = CUSTOMER_ITEM_COUNT;
state CurrentState = STATE_ready_for_customer;
int CurrentCustomer = 0;
int TimeToScan = 0;
while(CustomersLeft)
{
if(CurrentState == STATE_ready_for_item)
{
if(ItemsLeft > 0)
{
int CurrentItemIndex = CUSTOMER_ITEM_COUNT - ItemsLeft;
item CurrentItem = CustomerQueue[CurrentCustomer].Items[CurrentItemIndex];
TimeToScan = Time[CurrentItem] + CustomerQueue[CurrentCustomer].PackingSpeed;
CurrentState = STATE_scanning;
}
else
{
CurrentState = STATE_ready_for_customer;
}
}
else if (CurrentState == STATE_scanning)
{
TimePast ++;
TimeToScan --;
if (TimeToScan == 0)
{
ItemsLeft--;
CurrentState = STATE_ready_for_item;
}
printf("Time since start: %d. Scanning a product. %d to go.\n", TimePast, ItemsLeft);
}
else
{
if(NextQueueIndex < 3)
{
CurrentCustomer = NextQueueIndex++;
CurrentState = STATE_ready_for_items;
}
else
{
CustomersLeft = false;
}
}
}
}