-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprinter_simulation.cpp
More file actions
130 lines (109 loc) · 2.24 KB
/
Copy pathprinter_simulation.cpp
File metadata and controls
130 lines (109 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Task
{
public:
Task(int time)
{
timestamp = time;
pages = (rand() % 20) + 1;
}
int get_stamp()
{
return timestamp;
}
int get_pages()
{
return pages;
}
int wait_time(int current_time)
{
return (current_time - timestamp);
}
private:
int timestamp;
int pages;
};
class Printer
{
public:
Printer(int page_speed)
{
pagerate = page_speed;
time_remaining = 0;
working = false;
}
void tick()
{
if (working)
{
time_remaining--;
if (time_remaining <= 0)
{
working = false;
}
}
}
void start_next_task(Task next)
{
current_task = next;
time_remaining = next.get_pages() * 60 / pagerate;
working = true;
}
bool busy()
{
return working;
}
private:
int pagerate;
Task current_task = {0};
bool working;
int time_remaining;
};
bool new_print_task()
{
return !(rand() % 180);
}
void Simulation(int num_seconds, int page_speed)
{
//initialize Printer
Printer lab_printer(page_speed);
//initialize print queue
queue<Task> print_queue;
//waiting times vector
vector<int> waiting_times;
//loop for num_seconds seconds
for (int i = 0; i < num_seconds; i++)
{
if (new_print_task())
{
Task new_task(i);
print_queue.push(new_task);
}
if (!lab_printer.busy() && !print_queue.empty())
{
Task next_task = print_queue.front();
print_queue.pop();
waiting_times.push_back(next_task.wait_time(i));
lab_printer.start_next_task(next_task);
}
// advance time one second
lab_printer.tick();
}
float total = 0.0;
int i = 1;
for (int time : waiting_times)
{
total += (time - total) / i++;
}
cout << "The average wait was " << total << " seconds, with " << print_queue.size() << " printjobs not yet completed." << endl;
}
int main()
{
for (int i = 0; i < 10; i++)
{
Simulation(3600, 5);
}
}