* Header File */ /**************************************************************
ID: 3827629 • Letter: #
Question
* Header File */
/**********************************************************************
cs2123p4.h
Purpose:
Defines constants:
max constants
error constants
event type constants
boolean constants
Defines typedef for
Widget
Event (instead of Element)
For Linked List
NodeLL
LinkedListImp
LinkedList
For Queues
QElement
NodeQ
QueueImp
Queue
For the Servers
ServerImp
Server
For the Simulation
SimulationImp
Simulation
Protypes
Functions provided by student
Other functions provided by Larry previously (program 2)
Utility functions provided by Larry previously (program 2)
Notes:
**********************************************************************/
/*** constants ***/
// Maximum constants
#define MAX_TOKEN 50 // Maximum number of actual characters for a token
#define MAX_LINE_SIZE 100 // Maximum number of character per input line
#define MAX_ARRIVAL_TIME 600
// Error constants (program exit values)
#define ERR_COMMAND_LINE 900 // invalid command line argument
#define ERR_ALGORITHM 903 // Error in algorithm - almost anything else
#define ERR_BAD_INPUT 503 // Bad input
// Error Messages
#define ERR_MISSING_SWITCH "missing switch"
#define ERR_EXPECTED_SWITCH "expected switch, found"
#define ERR_MISSING_ARGUMENT "missing argument for"
// Event Constants
#define EVT_ARRIVAL 1 // when a widget arrives
#define EVT_SERVERM_COMPLETE 2 // when a widget completes with server M
#define EVT_SERVERW_COMPLETE 3 // when a widget completes with server W
#define EVT_SERVERX_COMPLETE 4 // when a widget completes with server X
#define EVT_SERVERY_COMPLETE 5 // when a widget completes with server Y
// exitUsage control
#define USAGE_ONLY 0 // user only requested usage information
#define USAGE_ERR -1 // usage error, show message and usage information
// boolean constants
#define FALSE 0
#define TRUE 1
/* EOF */
#define REACHED_EOF 1
/*** typedef ***/
// Widget typedef
typedef struct
{
long lWidgetNr; // Identifies a widget
int iStep1tu; // Step 1 time units
int iStep2tu; // Step 2 time units
int iArrivalTime; // Arrival time in tu
int iWhichServer; // For the alternatives, this specifies which server
} Widget;
// Event typedef
typedef struct
{
int iEventType; // The type of event as an integer:
// EVT_ARRIVAL - arrival event
// EVT_SERVERM_COMPLETE - servicing by server M is complete
// EVT_SERVERW_COMPLETE - servicing by server W is complete
// EVT_SERVERX_COMPLETE - servicing by server X is complete
// EVT_SERVERY_COMPLETE - servicing by server Y is complete
int iTime; // The time the event will occur
Widget widget; // The widget involved in the event.
} Event;
// typedefs for the Linked Lists used for the event list
typedef struct NodeLL
{
Event event;
struct NodeLL *pNext;
} NodeLL;
typedef struct
{
NodeLL *pHead;
} LinkedListImp;
typedef LinkedListImp *LinkedList;
// typedefs for the queues
typedef struct
{
Widget widget;
int iEnterQTime; // time widget was inserted in queue
} QElement;
typedef struct NodeQ
{
QElement element;
struct NodeQ *pNext;
} NodeQ;
typedef struct
{
NodeQ *pHead;
NodeQ *pFoot;
long lQueueWaitSum; // Sum of wait times for the queue
long lQueueWidgetTotalCount; // Total count of widgets that entered queue
char szQName[12];
} QueueImp;
typedef QueueImp *Queue;
// typedefs for server
typedef struct
{
char szServerName[12];
int bBusy; // TRUE - server is busy, FALSE - server is free
Widget widget; // Widget the server is currently working
} ServerImp;
typedef ServerImp *Server;
// typedefs for the Simulation
typedef struct
{
int iClock; // clock time
int bVerbose; // When TRUE, this causes printing of event information
long lSystemTimeSum; // Sum of times widgets are in the system
long lWidgetCount; // The number of widgets processed
char cRunType; // A - Alternative A, B - Alternative B, C - Current
LinkedList eventList;
} SimulationImp;
typedef SimulationImp *Simulation;
/********** prototypes ***********/
// linked list functions - you must provide the code for these (see course notes)
int removeLL(LinkedList list, Event *pValue);
NodeLL *insertOrderedLL(LinkedList list, Event value);
NodeLL *searchLL(LinkedList list, int match, NodeLL **ppPrecedes);
LinkedList newLinkedList();
NodeLL *allocateNodeLL(LinkedList list, Event value);
// queue functions
int removeQ(Queue queue, QElement *pFromQElement);
void insertQ(Queue queue, QElement element);
NodeQ *allocNodeQ(Queue queue, QElement value);
Queue newQueue(char szQueueNm[]);
// simulation functions - you must provide code for this
void runSimulation(Simulation simulation, int iTimeLimit);
// functions in most programs, but require modifications
void exitUsage(int iArg, char *pszMessage, char *pszDiagnosticInfo);
// Utility routines provided by Larry (copy from program #2)
void ErrExit(int iexitRC, char szFmt[], ...);
char * getToken(char *pszInputTxt, char szToken[], int iTokenSize);
/*Starting Point*/
void runSimulation(Simulation simulation, int iTimeLimit)
{
generateArrival(sim, 0);
while (removeLL(sim->eventList, &event))
{
sim->iClock = event.iTime; // advance clock
switch(event.eventType);
{
case EVT_ARRIVAL:
arrival(sim, &event.widget);
queueUp(sim, queueTeller, &event.widget);
seize(sim, queueTeller, serverTeller);
break;
case EVT_TELLER_COMPLETE:
release(sim, queueTeller, serverTeller, &event.widget);
leaveSystem(sim, event.widget);
break;
default:
ErrExit(ERR_ALGORITHM, "Unknown event type: %d ", event.iEventType);
}
}
Pgm #4 Machine improvement Proposals 50 points Server Wis a bottleneck and does many things. Its step 1 takes an average of 10 tu and its step 2 takes erage of 20 tu dget at a step 2, no widg time. ls on an only pl an be serviced every 10 tu. Running the erver for widgets, ou on step i. Average arrival rate average watt time has been over 500 Alternative A. Add a new server [server Ml simila o server W to do the same work as server W. Serve M d ep 1 p 2 Eet al y p Widgets will either queue up for server M (and be processed by server M) or queue up for server W and be pr ocessed to purchase Server M wi be $2M $200K m server W Cost ainten ance per are doubling our server capacity, the execu tives think th cut both the year. Sin average wait time and average time In the system in half, he downtime to expected to be the same for both alternatives so it isn a factor o produce Statist e Average time in system (from arrival to completion at step 2) verage queue time for each serve Input-p4input txt Widget Nr istepltu iStep2tu iArrivalDelta iWhich Server Midge entifies a widget going through the system step 1 for this widget istep1tu or step 2 for this widget iStep2tu valDelta delta time units before next widget arrives rWhichServer-determines which server to use when given an option or alternative For alternative B (extra credit): 1 server X, 2 erver Y cument, whichServer isn't u Paints Part A-50 points Provide a simulati of alternative A. e nclude a switch (-v) which has no corresponding argument, If-vis specified, this is verbose mode. This causes your to print all clock times and events as they happen: Arrival, Enter Queue M, Leave Queue Mr Seize Server M, Release Server M, Enter Queue W, Leave Queue W, Seize Server W, Release Server w, Exit system. Fol some of those events, you should print additional information (time in queue, time i system See the sample output below When mulating for alternative Aw make certain you add iStep1tu and istep2tu for the for eac rocessing show the statistics sp above. Run the simulation for 50 widgets. Allow all of the widgets to complete both steps and exit the system Sample output: Simulation Alternative A Time Widget Event 1 Arrived a 1 Er Queue M nter a 1 Leave Queue M, waited 1 Seized Server M 13 ved 13 2 Enter e N 13 2 Leave Queue W, waited 0 13 2 Seized Server W 3 Arrived 3 Enter e MA 36 1 Released Server M 36 3 Leave e M. ted 8 36 3 Seized Server M 36 1 Exit System, in system 36 42 4 Arrived 42 ue W nter 49 5 Arrived 49 5 Enter ue M 56 2 R Server elease W 56 4 Leave Queue W, waited 14 56 Seized Server W 56 2 Exit Syste in syst em 43 67 6 A ved 67 6 Enter e N 77 3 Released Server M 924 Simulation Complete for Alternative A Average Q ue Time for Server M Average Queue Time for Server W Average Time in SystemExplanation / Answer
//main.c
/*** Includes ***/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include "cs2123p3.h"
LinkedList newListFromInput();
Simulation newSim(LinkedList eventList);
void runSimulation(Simulation simulation, int iTimeLimit);
void runStartEvent();
void runEvent(Event event);
void runEndEvent();
void freeSim(Simulation sim);
/*** Functions ***/
int main(int argc, char *argv[])
{
//setting up the variables
LinkedList list;
Simulation sim;
//initializing the simulation
list = newListFromInput();
sim = newSim(list);
//the actual simulation
runSimulation(sim, 1000);
//frees everything
freeSim(sim);
return 0;
}
LinkedList newListFromInput()
{
/***variables***/
char szInputBuffer[100];
Person person;
Event arrival, departure;
LinkedList list;
int iClock, iNextArrival, iScanfCnt;
//set up a new list
list = newLinkedList();
iClock = 0; //the clock time for the next arrival
while (fgets(szInputBuffer, 100, stdin) != NULL) //goes through the file line by line
{
//if the line is empty, just ignore it
if (szInputBuffer[0] == ' ')
{
continue;
}
//counts the tokens in the line and place them in their desired variables
iScanfCnt = sscanf(szInputBuffer, "%s %d %d ", person.szName,
&person.iDepartUnits, &iNextArrival);
//if the line had less than 3 tokens, print the line, a warning,
//and go to the next line
if (iScanfCnt < 3)
{
ErrExit(ERR_BAD_INPUT, "%sExpected Name, DeltaDepart, and DeltaNextArrival,received %d successful values ",
szInputBuffer, iScanfCnt);
continue;
}
//if the DeltaDepart or DeltaNextArrival are negative values, print
//the line, a warning, and go to the next line
if (person.iDepartUnits < 0 || iNextArrival < 0)
{
ErrExit(ERR_BAD_INPUT, "%sDeltaDepart and DeltaNextArrival cannot be negative values. ",
szInputBuffer, iScanfCnt);
continue;
}
//create the arrival event for the current person/line
arrival.iEventType = EVT_ARRIVE;
arrival.iTime = iClock;
arrival.person = person;
//create the departure event
departure.iEventType = EVT_DEPART;
departure.iTime = iClock + person.iDepartUnits;
departure.person = person;
//insert both events in the list
insertOrderedLL(list, arrival);
insertOrderedLL(list, departure);
//increment clock to correspond to the next arrival time
iClock += iNextArrival;
}
return list;
}
Simulation newSim(LinkedList eventList)
{
//allocate the memory
Simulation sim = (Simulation) malloc(sizeof(SimulationImp));
sim->iClock = 0; //set clock to 0
sim->eventList = eventList; //insert list in the simulation
return sim;
}
void runSimulation(Simulation sim, int iTimeLimit)
{
Event event;
runStartEvent(); //in this case just prints a header
//removes the events from the list one by one while placing them in the current event variable
while (removeLL(sim->eventList, &event))
{
if (event.iTime > iTimeLimit)
//if the current event is over the time limit, terminate the simulation and send error
{
runEndEvent(sim->iClock);
ErrExit(ERR_BAD_INPUT, "Event time (%d) is out of simulation bounds (%d) ",
event.iTime, iTimeLimit);
}
sim->iClock = event.iTime; //set simulation clock to current event clock
runEvent(event); //in this case just prints the event
}
runEndEvent(sim->iClock); //in this case just prints a termination event
}
void runStartEvent()
{
printf("%-5s %-11s %-11s ", "Time", "Person", "Event");
}
void runEvent(Event event)
{
switch (event.iEventType)
{
case EVT_ARRIVE:
printf("%5d %-11s %-11s ", event.iTime, event.person.szName, "Arrive");
break;
case EVT_DEPART:
printf("%5d %-11s %-11s ", event.iTime, event.person.szName, "Depart");
break;
default:
ErrExit(ERR_ALGORITHM, "Unknown event type: %d ", event.iEventType);
}
}
void runEndEvent(int iEventTime)
{
printf("%5d %-11s %-11s ", iEventTime, "SIMULATION", "TERMINATES");
}
void freeSim(Simulation sim)
{
NodeLL *p = sim->eventList->pHead;
while (p != NULL)
{
NodeLL *pFree = p;
p = p->pNext;
free(pFree);
}
free(sim->eventList);
free(sim);
}
int removeLL(LinkedList list, Event *pValue)
{
NodeLL *pRemove;
if (list->pHead->pNext == NULL)
{
return FALSE;
}
*pValue = list->pHead->pNext->event;
pRemove = list->pHead->pNext;
list->pHead->pNext = list->pHead->pNext->pNext;
free(pRemove);
return TRUE;
}
NodeLL *insertOrderedLL(LinkedList list, Event value)
{
NodeLL *pNew, *pPrecedes;
searchLL(list, value.iTime, &pPrecedes);
pNew = allocateNodeLL(list, value);
pNew->pNext = pPrecedes->pNext;
pPrecedes->pNext = pNew;
return pNew;
}
NodeLL *searchLL(LinkedList list, int match, NodeLL **ppPrecedes)
{
NodeLL *p;
*ppPrecedes = list->pHead;
for (p = list->pHead->pNext; p != NULL; p = p->pNext)
{
if (match == p->event.iTime)
{
return p;
}
if (match < p->event.iTime)
{
return NULL;
}
*ppPrecedes = p;
}
return NULL;
}
LinkedList newLinkedList()
{
LinkedList list = (LinkedList) malloc(sizeof(LinkedListImp));
if (list == NULL)
{
ErrExit(ERR_ALGORITHM, "No available memory for linked list");
}
NodeLL *pHeader = (NodeLL *) malloc(sizeof(NodeLL));
list->pHead = pHeader;
list->pHead->pNext = NULL;
return list;
}
NodeLL *allocateNodeLL(LinkedList list, Event value)
{
NodeLL *pNew = (NodeLL *) malloc(sizeof(NodeLL));
if (pNew == NULL)
{
ErrExit(ERR_ALGORITHM, "No available memory for linked list");
}
pNew->event = value;
pNew->pNext = NULL;
return pNew;
}
/*** Utility Routines Provided ***/
void ErrExit(int iexitRC, char szFmt[], ... )
{
va_list args; // This is the standard C variable argument list type
va_start(args, szFmt); // This tells the compiler where the variable arguments
// begins. They begin after szFmt.
printf("ERROR: ");
vprintf(szFmt, args); // vprintf receives a printf format string and a
// va_list argument
va_end(args); // let the C environment know we are finished with the
// va_list argument
printf(" ");
exit(iexitRC);
}
void exitUsage(int iArg, char *pszMessage, char *pszDiagnosticInfo)
{
switch (iArg)
{
case USAGE_ERR:
fprintf(stderr, "Error: %s %s "
, pszMessage
, pszDiagnosticInfo);
break;
case USAGE_ONLY:
break;
default:
fprintf(stderr, "Error: bad argument #%d. %s %s "
, iArg
, pszMessage
, pszDiagnosticInfo);
}
// print the usage information for any type of command line error
fprintf(stderr, "p3 < inputFile.txt ");
if (iArg == USAGE_ONLY)
exit(USAGE_ONLY);
else
exit(ERR_COMMAND_LINE);
}
char * getToken(char *pszInputTxt, char szToken[], int iTokenSize)
{
int iDelimPos; // found position of delim
int iCopy; // number of characters to copy
char szDelims[20] = " "; // delimiters
szToken[0] = '';
// check for NULL pointer
if (pszInputTxt == NULL)
ErrExit(ERR_ALGORITHM
, "getToken passed a NULL pointer");
// Check for no token if at zero byte
if (*pszInputTxt == '')
return NULL;
// get the position of the first delim
iDelimPos = strcspn(pszInputTxt, szDelims);
// if the delim position is at the first character, return no token.
if (iDelimPos == 0)
return NULL;
// see if we have more characters than target token, if so, trunc
if (iDelimPos > iTokenSize)
iCopy = iTokenSize; // truncated size
else
iCopy = iDelimPos;
// copy the token into the target token variable
memcpy(szToken, pszInputTxt, iCopy);
szToken[iCopy] = ''; // null terminate
// advance the position
pszInputTxt += iDelimPos;
if (*pszInputTxt == '')
return pszInputTxt;
else
return pszInputTxt + 1;
}
=========================================================
/**********************************************************************
cs2123p3.h
Purpose:
Defines constants:
max constants
error constants
event type constants
boolean constants
Defines typedef for
Token
Person
Event (instead of Element)
For Linked List
NodeLL
LinkedListImp
LinkedList
For the simulation
SimulationImp
Simulation
Protypes
Functions provided by student
Other functions provided by Larry previously (program 2)
Utility functions provided by Larry previously (program 2)
Notes:
**********************************************************************/
/*** constants ***/
// Maximum constants
#define MAX_TOKEN 50 // Maximum number of actual characters for a token
#define MAX_LINE_SIZE 100 // Maximum number of character per input line
// Error constants (program exit values)
#define ERR_COMMAND_LINE 900 // invalid command line argument
#define ERR_ALGORITHM 903 // Error in algorithm - almost anything else
#define ERR_BAD_INPUT 503 // Bad input
// Error Messages
#define ERR_MISSING_SWITCH "missing switch"
#define ERR_EXPECTED_SWITCH "expected switch, found"
#define ERR_MISSING_ARGUMENT "missing argument for"
// Event Constants
#define EVT_ARRIVE 1 // when a person arrives
#define EVT_DEPART 2 // when a person departs the simulation
// exitUsage control
#define USAGE_ONLY 0 // user only requested usage information
#define USAGE_ERR -1 // usage error, show message and usage information
// boolean constants
#define FALSE 0
#define TRUE 1
/*** typedef ***/
// Token typedef used for operators, operands, and parentheses
typedef char Token[MAX_TOKEN + 1];
// Typedefs for the queues
// Element typedef
typedef struct
{
char szName[12]; // Name
int iDepartUnits; // time units representing how long he stays around
} Person;
typedef struct
{
int iEventType; // The type of event as an integer:
// EVT_ARRIVE - arrival event
// EVT_DEPART - departure event
int iTime; // The time the event will occur
Person person; // The person invokved in the event.
} Event;
// typedefs for the Linked Lists
typedef struct NodeLL
{
Event event;
struct NodeLL *pNext;
} NodeLL;
typedef struct
{
NodeLL *pHead;
} LinkedListImp;
typedef LinkedListImp *LinkedList;
// typedefs for the Simulation
typedef struct
{
int iClock; // clock time
LinkedList eventList;
} SimulationImp;
typedef SimulationImp *Simulation;
/********** prototypes ***********/
// linked list functions - you must provide the code for these (see course notes)
int removeLL(LinkedList list, Event *pValue);
NodeLL *insertOrderedLL(LinkedList list, Event value);
NodeLL *searchLL(LinkedList list, int match, NodeLL **ppPrecedes);
LinkedList newLinkedList();
NodeLL *allocateNodeLL(LinkedList list, Event value);
// simulation functions - you must provide code for this
void runSimulation(Simulation simulation, int iTimeLimit);
// functions in most programs, but require modifications
void exitUsage(int iArg, char *pszMessage, char *pszDiagnosticInfo);
// Utility routines provided by Larry (copy from program #2)
void ErrExit(int iexitRC, char szFmt[], ...);
char * getToken(char *pszInputTxt, char szToken[], int iTokenSize);
================================================================
Input:
The standard input file stream contains records in the following format:
szName iDeltaDepart iDeltaNextArrival
11s 3d 3d
Some sample data:
Fred 10 5
Daphne 4 3
Velma 6 6
Shaggy 9 6
Scooby 2 5
Scrappy 1 3
Results:
Prints an ordered formatted list of the events.
For each person in the input file:
- create an arrival and a departure event
- place the events in an ordered linked list
Once every event is in the list, goes through it and print them
in a table format
Returns:
0 - normal
900 - command line argument syntax error
903 - algorithm error (see message for details)
503 - bad input
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.