Problem Solving with Go course

Stacks, Queues and SearchQueues: First Come, First Served

Problem Solving with Go

Display

Theme

Stacks, Queues and Search · Test exercise

Queues: First Come, First Served

A queue is the opposite of a stack: things join at the back and leave from the front. The first in is the first out (FIFO). Print jobs, customers at a counter, and in the next lesson the cells still to explore in a search: all of them are queues.

A slice as a queue

The simplest queue is a slice too. Add with append, take from index 0:

queue := []string{"soup"}
queue = append(queue, "pizza") // join at the back

front := queue[0]  // "soup"
queue = queue[1:]  // leave from the front

queue[1:] doesn't copy anything: it moves the start of the slice one place on. The old front values stay in memory until the slice is copied again by append, which is fine for puzzle-sized input.

A ring: a queue with a fixed size

When you know the most values the queue will ever hold, a ring buffer reuses the same array forever. Keep the index of the front (head) and the number of values (size). The back is head + size, and % len(buf) wraps it to the start when it runs off the end:

capacity 4, after pushing 1 2 3, popping 1, pushing 4 5:

buf:  [5] [2] [3] [4]
            ↑ head = 1, size = 4

Nothing is ever moved or copied, so a ring suits a stream that never ends: the last 100 readings, a fixed waiting area, a buffer between two parts of a program.

Taking turns

Queues are also how you share one resource fairly. The front of the queue gets a short turn; if it isn't done, it goes to the back and waits again. Nothing waits forever, and short jobs finish early.

Task

  1. Complete Push and Pop on Ring. Push returns false and changes nothing when the ring is full; Pop returns ok == false when it is empty.
  2. Complete serve(orders []Order, slice int) []Finished. A cook has one stove and cooks the front order for up to slice minutes. If it needs no more than that, it is ready, and the next order starts straight away. Otherwise it goes to the back of the queue with the minutes it still needs. Return the dishes in the order they are ready, with the minute each was ready (the clock starts at 0). Don't change the orders argument; slice is at least 1.

This lesson's input starts with the length of a turn, followed by one order per line.

main.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

// Ring is a first-in, first-out queue of ints with a fixed capacity. The values
// live in buf, starting at index head and wrapping around to the start.
type Ring struct {
	buf  []int
	head int // index of the front value
	size int // how many values are queued
}

// NewRing returns an empty ring that holds up to capacity values.
func NewRing(capacity int) *Ring {
	return &Ring{buf: make([]int, capacity)}
}

// Len returns how many values are queued.
func (q *Ring) Len() int {
	return q.size
}

// Push adds v at the back. When the ring is full it changes nothing and returns false.
func (q *Ring) Push(v int) bool {
	// TODO: write v at (head + size) % len(buf)
	return false
}

// Pop removes the front value and returns it. ok is false when the ring is empty.
func (q *Ring) Pop() (v int, ok bool) {
	// TODO: read buf[head], then move head one place on, wrapping around
	return 0, false
}

// Order is a dish and the minutes of cooking it still needs.
type Order struct {
	Name    string
	Minutes int
}

// Finished is a dish and the minute it was ready.
type Finished struct {
	Name string
	At   int
}

// serve cooks the orders in turns: the front order gets up to slice minutes, then it is
// either ready or goes to the back of the queue with the minutes it still needs.
// It returns the dishes in the order they were ready, counting minutes from 0.
func serve(orders []Order, slice int) []Finished {
	// TODO: a slice as a queue: take from queue[0], add with append
	return nil
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	slice := 0
	var orders []Order
	for scanner.Scan() {
		name, value, _ := strings.Cut(strings.TrimSpace(scanner.Text()), " ")
		n, err := strconv.Atoi(value)
		if err != nil {
			fmt.Println("bad line:", scanner.Text())
			return
		}
		if name == "slice" {
			slice = n
		} else {
			orders = append(orders, Order{name, n})
		}
	}
	for _, f := range serve(orders, slice) {
		fmt.Printf("%-6s ready at minute %d\n", f.Name, f.At)
	}
}
Go runtime not loaded yet

6 lines · 48 B of the 1 MB limit. Submit always uses the lesson's own input.