Моделирование супермаркета в C - PullRequest
0 голосов
/ 08 мая 2020

У меня есть задача, которая выглядит так ЗАДАЧА1

Я написал несколько строк, в которых я могу получить максимальный рынок клиентов, время прибытия и время обслуживания для каждого клиента, но я не могу понять, как мне отслеживать время и очередь, чтобы получить ответы на вопросы a) и b). Мой код выглядит так

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct customer {
    int serveTime;
    int arriveTime;
} customer[1000];

int main()
{
    srand( time(NULL) );
    int randArrive, randServe, longestWait, currentQ, totalTime=0, i;

    randArrive = rand() % 4 + 1;
    customer[0].arriveTime = randArrive;
    customer[0].serveTime = rand() % 4 + 1;
    totalTime += randArrive;
    currentQ = 1;

    for ( i=1; totalTime<720; i++ )
    {
        customer[i].arriveTime = rand() % 4 + 1;
        customer[i].serveTime = rand() % 4 + 1;

        if ( customer[i].arriveTime < customer[i-1].serveTime )
            totalTime += customer[i-1].serveTime;
        else
            totalTime += customer[i].arriveTime;
    }

    printf( "%d,%d", totalTime, i );

    return 0;
}

PS: Я новичок в программировании, будучи студентом, каждый совет поможет, спасибо.

1 Ответ

1 голос
/ 09 мая 2020

Ниже приведен код моего решения задачи.

Обратите внимание, что я не строго следовал алгоритму, описанному в задаче. Согласно задаче, клиент, обслуживаемый в данный момент, не должен быть частью очереди, но должен быть исключен из очереди перед обслуживанием. Однако мне показалось, что проще программировать, если рассматривать клиента, обслуживаемого в настоящее время, как клиента в начале очереди.

Задача также требует, чтобы вы изменили максимальное время прибытия с 4 на 3 и соблюдали изменения. Поскольку я определил значение 4 в центре, все, что вам нужно сделать, это изменить строку

#define MAX_MINUTES_PER_ARRIVAL 4

на следующее:

#define MAX_MINUTES_PER_ARRIVAL 3

После этого значение 4 будет автоматически изменено на 3 в обоих местах кода.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// This header is only required in order to use the assert macro used below,
// but both this header and the assert macros are only used for debugging
// purposes and can be removed.
#include <assert.h>

// Instead of writing the value 720 in several places in the program, it is
// usually better to define the number in one place, so it can more easily be
// changed.
#define NUM_MINUTES 720

// Also, if the minimum and maximum random waiting times are defined in one
// central place, they are also easier to change, which actually must be done
// as part of the task.
#define MIN_MINUTES_PER_ARRIVAL 1
#define MAX_MINUTES_PER_ARRIVAL 4
#define MIN_MINUTES_PER_SERVICE 1
#define MAX_MINUTES_PER_SERVICE 4

// Since no more than one customer can arrive per minute, there can be no more
// than NUM_MINUTES customers, so this array is guaranteed to be large enough.
// If you want to save memory, you can use a linked list and dynamic memory
// allocation instead, but this may be be slower.
static int customerArrivalTimes[NUM_MINUTES];

int main()
{
    // This will seed the random number generator.
    unsigned int seed = (unsigned)time( NULL );
    printf( "seeding with %u\n", seed );
    srand( seed );

    // This variable always holds the time the next customer will arrive.
    int nextArrival;

    // This variable holds the time the cashier will finish serving the current
    // customer. The value of -1 is reserved to indicate that no customer is
    // currently being serviced.
    int nextService = -1;

    // This variable keeps record of the maximum waiting time a single customer
    // experienced.
    int longestWait = 0;

    // This variable keeps track of the longest Queue Size ever encountered.
    int longestQueue = 0;

    // This variable specifies the current length of the queue.
    int queueLength = 0;

    // When queueLength == 0, queueStart specifies the index into the array
    // customerArrivalTimes which will hold the next customer that arrives, so
    // in that case it should be identical to the value of queueEnd.
    // When queueLength != 0, queueStart specifies the index into the array
    // customerArrivalTimes of the customer which is currently being serviced.
    int queueStart = 0;

    // When queueLength == 0, queueEnd specifies the index into the array
    // customerArrivalTimes which will hold the next customer that arrives, so
    // in that case it should be identical to the value of queueStart.
    // When queueLength != 0, queueEnd specifies the index into the array
    // customerArrivalTimes which will hold the next arriving customer (i.e.
    // one beyond the last customer in the queue).
    int queueEnd = 0;

    // This will use the random number generator to set the arrival time of
    // the first customer.
    nextArrival = rand() % (MAX_MINUTES_PER_ARRIVAL + 1 - MIN_MINUTES_PER_ARRIVAL) + MIN_MINUTES_PER_ARRIVAL;

    // This simulation will start at minute 0 and end at minute NUM_MINUTES - 1
    for ( int i = 0; i < NUM_MINUTES; i++ )
    {
        //check if the next customer is scheduled to arrive in this minute
        if ( nextArrival == i )
        {
            //update queueLength and test if record has been broken
            queueLength++;
            if ( queueLength > longestQueue ) longestQueue = queueLength;

            //print information message
            printf( "%03d:New customer arriving, queue length now: %d.\n", i, queueLength );

            //remember the arrival time of the current customer
            customerArrivalTimes[queueEnd++] = i;

            //set random arrival time for next customer
            nextArrival = rand() % (MAX_MINUTES_PER_ARRIVAL + 1 - MIN_MINUTES_PER_ARRIVAL) + MIN_MINUTES_PER_ARRIVAL + i;

            //if queue was empty, start servicing the new customer
            if ( queueLength == 1 )
            {
                // The following line will abort the program with an error
                // message if nextService is a valid time value (not -1).
                // This should not happen if the queue was empty. Therefore,
                // this would indicate a bug in the program.
                assert( nextService == -1 );

                //schedule completion time of next customer service
                nextService = rand() % (MAX_MINUTES_PER_SERVICE + 1 - MIN_MINUTES_PER_SERVICE) + MIN_MINUTES_PER_SERVICE + i;
            }
        }

        //check if customer service is scheduled to finish in this minute
        if ( nextService == i )
        {
            //print information message
            printf(
                "%03d:Customer service completed, total time: %d.\n",
                i, i - customerArrivalTimes[queueStart]
            );

            // This code block will update the variable longestWait if the
            // record was broken
            if ( longestWait < i - customerArrivalTimes[queueStart] )
            {
                longestWait = i - customerArrivalTimes[queueStart];
            }

            //update the starting point and length of the queue
            queueStart++;
            queueLength--;

            // The following line will abort the program with an error message
            // if queueLength ever becomes negative (which should never happen
            // and would indicate a bug in the program).
            assert( queueLength >= 0 );

            //if queue is not empty, start servicing the next customer
            if ( queueLength != 0 )
            {
                //schedule completion time of next customer service
                nextService = rand() % (MAX_MINUTES_PER_SERVICE + 1 - MIN_MINUTES_PER_SERVICE) + MIN_MINUTES_PER_SERVICE + i;
            }
            //otherwise indicate that no customer is currently being serviced
            else
            {
                nextService = -1;
            }
        }
    }

    // This will print the longest total waiting time a customer experienced.
    // This includes the waiting time for a customer to finish being serviced
    // by the cashier, although the task description does not clearly specify
    // whether this should be the case. Also, this does not take into account
    // whether customers still waiting in the queue when the store closes
    // will or already have had a longer waiting time, as the task does not
    // specify how these customers should be handled.
    printf( "Longest wait: %d\n", longestWait );

    // This will print the maximum queue length that was encountered.
    printf( "Longest queue: %d\n", longestQueue );

    return 0;
}
...