C ++ Car Simulation - PullRequest
       11

C ++ Car Simulation

0 голосов
/ 11 октября 2019

C ++ Структуры данных, использующие очередь, мой вывод кода не верный, я не уверен, что изменить.

C ++, используя библиотеку очереди stl, у меня возникают проблемы с получением правильного вывода из моей программы. Время ожидания отображается неправильно, а время начала стирки отображается неправильно. Это код, который у меня есть:

#include <iostream>
#include <assert.h>
#include <fstream>
#include <queue>
#include <stdlib.h>

using namespace std;

class averager {
private:
    int cnt;
    int sum;

public:
    averager() {
        cnt = 0;
        sum = 0;
    }
    void plus_next_number(int value) {
        cnt++;
        sum += value;
    }
    double average_time() {
        assert(cnt > 0);
        return (sum / cnt);
    }
    int how_many_cars() { return cnt; }
};

class Washmachine {
private:
    int time_for_wash;
    int time_left;

public:
    Washmachine(int n) {
        time_for_wash = n;
        time_left = 0;
    }

    bool is_busy() { return time_left > 0; }

    void startWashing() {
        assert(!is_busy());
        time_left = time_for_wash;
    }

    void one_second() {
        if(is_busy()) {
            --time_left;
        }
    }
};

int main() {
    queue<int> waitQueue;
    int carArrival;
    averager cal;
    ifstream infile;
    ofstream arrivalrec;
    arrivalrec.open("arrival_time.txt");
    arrivalrec << "Car Number  "
               << "Arrival Time  "
               << "Car Wash Start Time  "
               << "Departure Time  "
               << "Wait Time  "
               << "Total Time  " << endl
               << endl;

    int maxWaitTime;   // maxWaitTime initially 0:00
    int totalWaitTime; // total time customers wait
    int endTime = 60;  // times for the simulation
    int totalServiceTime;
    int startTime;
    int carNum = 0;   // number of cars washed in study
    int washTime = 3; // fixed time for a wash in minutes
    int DeptTime;
    int TotalTime;
    int timeleft = 0;
    int waitTime;

    Washmachine carwashing(washTime);

    infile.open("input.txt");
    for(int startWash = 0; startWash <= endTime; startWash++) {
        infile >> startWash;
        waitQueue.push(startWash);
        if((!carwashing.is_busy()) && (!waitQueue.empty())) {
            carArrival = waitQueue.front();
            waitQueue.pop();
            cal.plus_next_number(startWash - carArrival);
            carwashing.startWashing();
        }
        carwashing.one_second();
        waitTime = startWash - carArrival;

        if(maxWaitTime < waitTime) maxWaitTime = waitTime;
        // add waiting time for customer to totalWaitTime.
        totalWaitTime += waitTime;
        totalServiceTime += washTime;

        startTime = startWash + waitTime;
        TotalTime = startWash + waitTime;

        DeptTime = startTime + washTime;
        // increment the number of customers served
        carNum++;
        // set washAvailable to false since equipment back in service

        // output the summary data for the simulation include number of cars
        // washed, average customer waiting time and pct of time wash operates

        arrivalrec << carNum << "              " << startWash
                   << "                   " << startTime << "                  "
                   << DeptTime << "              " << waitTime << "                "
                   << TotalTime << endl
                   << endl
                   << endl;
    }
    arrivalrec << "Maximum customer waiting time for a car wash is " << maxWaitTime
               << " minutes" << endl;
    arrivalrec << "Percentage of time car wash operates is  "
               << ((totalServiceTime / endTime) * 100.0) << '%' << endl;
    arrivalrec << "Number of customers remaining at " << endTime << " is "
               << waitQueue.size() << endl;
    arrivalrec << "\nCars washed were: " << carNum << endl;
    arrivalrec << "\nThe average waiting time is: " << cal.average_time() << endl;
    int car_denied = 0;
    while(!waitQueue.empty()) {
        waitQueue.pop();
        car_denied++;
    }
    arrivalrec << "\nThe number of denied cars is: " << car_denied << endl;
    arrivalrec << endl;
    return 0;
}

Правильный вывод кода

enter image description here

Вывод моего кода

enter image description here

1 Ответ

1 голос
/ 14 октября 2019

Следующий код решает вашу задачу в соответствии с сфотографированным описанием с двумя исключениями:

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

Остальное работает так, как указано:

#include <iostream>
#include <cassert>
#include <fstream>
#include <queue>
#include <cstdlib>

constexpr auto SIMULATION_END_TIME = 80;
constexpr auto OPENING_END_TIME = 60;

using namespace std;

class averager {
private:
    int cnt;
    int sum;
public:
    averager(){
        cnt=0;
        sum=0;
    }
    void plus_next_number(int value)
    {
        cnt++;
        sum+=value;
    }
    double average_time()
    {
        assert(cnt>0);
        return (sum/static_cast<double>(cnt));
    }
    int how_many_cars()
    {
        return cnt;
    }
};

class Washmachine {
private:
    int time_for_wash;
    int time_left;
public:
    Washmachine(int n) {
        time_for_wash = n;
        time_left = 0;

    }

    bool is_busy() {
        return (time_left > 0);
    }

    void startWashing() {
        if(!is_busy()) {
            time_left = time_for_wash;
        }

    }

    void one_second(){
        if(is_busy()) {
            --time_left;
        }
    }
};

int main() {
    queue<int> waitQueue;
    int carArrival = 0;
    averager cal;
    ifstream infile;
    ofstream arrivalrec;
    arrivalrec.open("arrival_time.txt");
    arrivalrec << "Start of Simulation" << endl;
    arrivalrec << "Car\t\tArrival\tCar Wash\tDeparture\tWait\tTotal" << endl;
    arrivalrec << "Number\tTime\tStart Time\tTime\t\tTime\tTime" << endl;
    arrivalrec << "------------------------------------------------------------" << endl;

    int maxWaitTime = 0;   // maxWaitTime initially 0:00
    int totalWaitTime = 0;           // total time customers wait
    int totalServiceTime = 0;
    int startTime = 0;
    int carNum = 0;         // number of cars washed in study
    int washTime = 3;                       // fixed time for a wash in minutes
    int DeptTime = 0;
    int TotalTime = 0;
    int timeleft=0;
    int waitTime=0;
    int temp;
    int sw;
    int runTime;
    Washmachine carwashing(washTime);



    infile.open("input.txt");
    infile >> temp;
    carNum = 1;

    for (runTime=1;runTime<=SIMULATION_END_TIME;runTime++){

        if (runTime == temp) {
            waitQueue.push(temp);
            infile >> temp;
        }
        if((runTime <= OPENING_END_TIME)&&(!carwashing.is_busy())&&(!waitQueue.empty())) {
            carArrival=waitQueue.front();
            waitQueue.pop();
            startTime = runTime;
            waitTime=startTime-carArrival;
            totalWaitTime += waitTime;
            TotalTime = washTime + waitTime;
            if (maxWaitTime < waitTime)
                maxWaitTime = waitTime;
            cal.plus_next_number(startTime-carArrival);
            carwashing.startWashing();
        }
        else
        {
            waitTime++;
        }
        if (carwashing.is_busy())
            carwashing.one_second();

        if ((!carwashing.is_busy())&&(startTime >= DeptTime)) {
            DeptTime = startTime + washTime;
            totalServiceTime += washTime;
            arrivalrec << carNum << "\t\t" << carArrival << "\t\t" << startTime
                << "\t\t\t" << DeptTime << "\t\t\t" <<
                waitTime << "\t\t" << TotalTime << endl;
            carNum++;
        }
    }
    int car_denied = 0;
    while (!waitQueue.empty())
    {
        arrivalrec << carNum << "\t\t" << waitQueue.front() << "\tCar arrived after closing time and was not served." << endl;
        waitQueue.pop();
        car_denied++;
        carNum++;
    }
    arrivalrec << "End of Simulation" << endl << endl;
    arrivalrec << "Statistics:" << endl;
    arrivalrec << "\tTotal wait time: " << totalWaitTime << " minutes" << endl;
    arrivalrec << "\tMaximum customer waiting time for a car wash is "
                << maxWaitTime << " minutes" << endl;
    arrivalrec << "\tPercentage of time car wash operates is "
                << ((totalServiceTime / static_cast<double>(OPENING_END_TIME)) * 100.0)
                << " %" << endl;
    arrivalrec<<"\tCars washed were: "<<carNum - car_denied - 1<<endl;
    arrivalrec<<"\tThe average waiting time is: "<<cal.average_time()<<endl; // TODO: Convert time to minutes and seconds
    arrivalrec<<"\tThe number of denied cars is:"<<car_denied<<endl;
    arrivalrec<<endl;
    return 0;
}

Вывод arrival_time.txt файла:

Start of Simulation
Car     Arrival Car Wash    Departure   Wait    Total
Number  Time    Start Time  Time        Time    Time
------------------------------------------------------------
1       1       1           4           2       3
2       2       4           7           4       5
3       4       7           10          5       6
4       10      10          13          2       3
5       13      13          16          2       3
6       15      16          19          3       4
7       16      19          22          5       6
8       75  Car arrived after closing time and was not served.
End of Simulation

Statistics:
    Total wait time: 9 minutes
    Maximum customer waiting time for a car wash is 3 minutes
    Percentage of time car wash operates is 35 %
    Cars washed were: 7
    The average waiting time is: 1.28571
    The number of denied cars is:1

Пожалуйста, проверьте кодс вашим и примите этот ответ, если он соответствует вашей проблеме. Спасибо.

...