Activity 33: The printer queue
Name:
Problem 1: trace a ring (in lecture)
A VecDeque<i32> with capacity 4, starting empty:
push_back(7), push_back(3), push_back(9), push_back(10)
pop_front(), pop_front()
push_back(4)
push_front(8)
- Draw the block after every line, with
headandlennext to it. Elementilives at slot(head + i) % 4. - What does
println!("{:?}", line)print at the end? - Which slot holds the front of the queue? Which slot holds the back?
Answer.
push_back x4: [ 7 | 3 | 9 | 10 ] head 0 len 4
pop_front x2: [ | | 9 | 10 ] head 2 len 2
push_back(4): [ 4 | | 9 | 10 ] head 2 len 3
push_front(8): [ 4 | 8 | 9 | 10 ] head 1 len 4
[8, 9, 10, 4]. Printing starts atheadand walks around the ring- The front is slot 1 (the 8), because
push_frontsteppedheadback from 2 to 1. The back is slot 0 (the 4):(head + len - 1) % 4 = (1 + 4 - 1) % 4 = 0, so it wrapped
Problem 2: the printer queue
A printer takes jobs in the order they arrive, except that an urgent job cuts to the front. Build it on a VecDeque.
The cell below runs right here on the website: edit the code in the box, press the play button in its corner, read the output. Don't refresh the page, or your edits will disappear.
We'll write new, add_job, and print_next together. Then add_urgent_job, total_pages, and print_all are yours. You'll fill in everywhere that's marked todo!().
use std::collections::VecDeque; #[derive(Debug)] struct PrintJob { id: u32, pages: u32, } #[derive(Debug)] struct PrinterQueue { jobs: VecDeque<PrintJob>, } impl PrinterQueue { fn new() -> PrinterQueue { // An empty queue todo!() } fn add_job(&mut self, id: u32, pages: u32) { // A normal job joins at the back todo!() } fn add_urgent_job(&mut self, id: u32, pages: u32) { // An urgent job cuts to the front todo!() } fn total_pages(&self) -> u32 { // Add up the pages of every job waiting. A for loop over &self.jobs works todo!() } fn print_next(&mut self) { // Take the next job and print "Printing job [id]: [pages] pages" // If there's nothing waiting, print "Nothing to print" todo!() } fn print_all(&mut self) { // Print every job that's waiting, in order todo!() } } fn main() { let mut printer = PrinterQueue::new(); printer.add_job(1, 5); printer.add_job(2, 10); printer.add_job(3, 3); println!("Pages waiting: {}", printer.total_pages()); printer.print_next(); printer.add_urgent_job(99, 2); printer.print_all(); printer.print_next(); }
If it runs with time to spare, try adding these to the same cell and call them from main:
fn queue_size(&self) -> usize: how many jobs are waitingfn peek_next(&self) -> Option<&PrintJob>: the next job, without taking itfn cancel_job(&mut self, id: u32) -> bool: remove one job by itsid, and say whether it was there
What your program printed when every todo!() was filled in:
Question 1. Why is VecDeque the right structure here, and what would go wrong with a Vec?
Question 2. total_pages walks through every job, so it's O(n). How would you make it O(1)?
Solutions
Complete code:
#![allow(unused)] fn main() { impl PrinterQueue { fn new() -> PrinterQueue { PrinterQueue { jobs: VecDeque::new() } } fn add_job(&mut self, id: u32, pages: u32) { self.jobs.push_back(PrintJob { id, pages }); } fn add_urgent_job(&mut self, id: u32, pages: u32) { self.jobs.push_front(PrintJob { id, pages }); } fn total_pages(&self) -> u32 { let mut total = 0; for job in &self.jobs { total += job.pages; } total } fn print_next(&mut self) { match self.jobs.pop_front() { Some(job) => println!("Printing job {}: {} pages", job.id, job.pages), None => println!("Nothing to print"), } } fn print_all(&mut self) { while !self.jobs.is_empty() { self.print_next(); } } } }
Extensions: queue_size is self.jobs.len(). peek_next is self.jobs.front(). cancel_job is a for i in 0..self.jobs.len() loop that checks self.jobs[i].id, calls self.jobs.remove(i), and returns true; false after the loop.
Follow-up questions
What your program printed:
Expected output.
Pages waiting: 18
Printing job 1: 5 pages
Printing job 99: 2 pages
Printing job 2: 10 pages
Printing job 3: 3 pages
Nothing to print
Job 99 was added after job 1 was printed, and cut in front of jobs 2 and 3.
Question 1:
Answer. The printer always takes from the front, and urgent jobs go in at the front. On a VecDeque both are O(1): move head. On a Vec they're remove(0) and insert(0, ..), and each one shifts every waiting job by one slot, so O(n).
Question 2:
Answer. Keep a running total in the struct: a total: u32 field. add_job and add_urgent_job add to it, print_next subtracts the job it takes, and total_pages just returns it.