⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bank.cpp

📁 BigC++的源码
💻 CPP
字号:
#include <deque>
#include <iostream>

using namespace std;

int rand_int(int a, int b)
{
    return a + rand() % (b - a + 1);
}

double rand_double(double a, double b)
{
    return a + (b - a) * rand() * (1.0 / RAND_MAX);
}

const int MIN_PROCESS_TIME = 2;
const int MAX_PROCESS_TIME = 8;

/**
    A typical customer.
    Customers arrive at random time,
    and take random time to process work.
*/
class Customer
{
public:
    Customer(int at = 0);
    /**
       Return arrival time, set by constructor.
       @return arrival time
    */
    int get_arrival_time() const;

    /**
       Return process time, set randomly by constructor.
       @return process time
    */
    int get_process_time() const;
private:
    int arrival_time;
    int process_time;
};

Customer::Customer(int at) :
    arrival_time(at),
    process_time(rand_int(MIN_PROCESS_TIME, MAX_PROCESS_TIME)) { }

int Customer::get_arrival_time() const
{
    return arrival_time;
}

int Customer::get_process_time() const
{
    return process_time;
}

/**
    Simulation of bank teller.
*/
class Teller
{
public:
    Teller();

    /**
       @return true if teller is free to service customer
    */
    bool is_free() const;

    /**
       Updates the teller status.
       @param time the current time
    */
    void update(int time);

    /**
       Assign a teller to customer.
       @param c the customer
    */
    void add_customer(const Customer& c, int time);
private:
    bool free;
    Customer customer;
    int start_time;
};

Teller::Teller()
{
    free = true;
}

bool Teller::is_free() const
{
    return free;
}

void Teller::update(int time)
{
    if (free) return;
    if (time > start_time + customer.get_process_time())
       free = true;
}

void Teller::add_customer(const Customer& c, int time)
{
    free = false;
    customer = c;
    start_time = time;
}

int main()
{
    const int NUMBER_OF_TELLERS = 5;
    const int NUMBER_OF_MINUTES = 60;

    const double ARRIVAL_RATE = 0.9;
    double total_wait = 0;
    int number_of_customers = 0;
    deque<Teller> teller(NUMBER_OF_TELLERS);
    deque<Customer> line;

    for (int time = 0; time < NUMBER_OF_MINUTES; time++)
    {
       if (rand_double(0, 1) < ARRIVAL_RATE)
       {
          line.push_back(Customer(time));
       }

       for (int i = 0; i < NUMBER_OF_TELLERS; i++)
       {
          teller[i].update(time);
          if (teller[i].is_free() && !line.empty())
          {
             Customer front_customer = line.front();
             total_wait += (time - front_customer.get_arrival_time());
             teller[i].add_customer(front_customer, time);
             number_of_customers++;
             line.pop_front();
          }
       }
    }
    cout << "average wait: " << (total_wait / number_of_customers) << "\n";
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -