Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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)
  1. Draw the block after every line, with head and len next to it. Element i lives at slot (head + i) % 4.
  2. What does println!("{:?}", line) print at the end?
  3. 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
  1. [8, 9, 10, 4]. Printing starts at head and walks around the ring
  2. The front is slot 1 (the 8), because push_front stepped head back 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:

  1. fn queue_size(&self) -> usize: how many jobs are waiting
  2. fn peek_next(&self) -> Option<&PrintJob>: the next job, without taking it
  3. fn cancel_job(&mut self, id: u32) -> bool: remove one job by its id, 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.