Taskintro
Use a queue
Also called enqueue and dequeue, fifo queue, first in first out, round robin, list pop 0 is slow.
Run jobs in turn with round-robin scheduling, with enqueue and dequeue on the standard queue type of each tier 1 language, and see why list.pop(0) is slow.
- Evidence
- Code in 10 languages
Task
Use a queue to run jobs in turn. This is round-robin scheduling. The function finish_order(work, slice) gets a list of jobs: job i needs work[i] time units. At the start, the jobs wait in a queue in the order 0, 1, 2 and so on. The scheduler takes the job at the front, and runs it for slice time units or until it is done. If the job needs more time, it goes to the back of the queue. The function returns the job numbers in the order in which the jobs finish.
For example, finish_order([3, 1, 2], 1) is [1, 2, 0]. Job 1 finishes in the first round. Job 2 finishes in the second round, and job 0 finishes in the third round. Each job gets the same share of time, and that is the order of a queue: the first job in is the first job out. For the idea, see Queue.
Solutions
| Language | Queue | Enqueue and dequeue |
|---|---|---|
| Python | collections.deque |
append(x), popleft() |
| JavaScript | an array and a head index | push(x), queue[head++] |
| TypeScript | number[] and a head index |
push(x), queue[head++] |
| Java | ArrayDeque<Integer> as a Queue |
offer(x), poll() |
| C | a ring buffer: an array, a head index and a count | queue[(head + count) % n] = x, queue[head] |
| C++ | std::queue<std::size_t> |
push(x), front() and then pop() |
| C# | Queue<int> |
Enqueue(x), TryDequeue(out x) |
| Go | a slice []int |
append(q, x), q[0] and then q = q[1:] |
| Rust | VecDeque<usize> |
push_back(x), pop_front() that gives an Option |
| Bash | an indexed array and a head index | q+=("$x"), ${q[head]} |
- Python uses
collections.deque, not a list. A list can be a queue, but the tutorial says that "lists are not efficient for this purpose."1 A deque supports "memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction."2 The modulequeueis a different tool. "It is especially useful in threaded programming when information must be exchanged safely between multiple threads."3 One thread does not need its locks. - JavaScript keeps a head index. JavaScript has no queue type.
shift()removes the first element of an array, but its description says that it "shifts all values to the left by 1 and decrements the length by 1"4. The solution does not depend on how an engine does this. It readsqueue[head]and movesheadforward, so a dequeue does not move the other elements. - Java uses the
Queuemethods ofArrayDeque.ArrayDequeis "faster than LinkedList when used as a queue"5. Useofferandpoll. "The remove() and poll() methods remove and return the head of the queue."6 They differ only when the queue is empty:poll()returns null, andremove()throws an exception. - C++ and C# have a queue type.
std::queuegives "the functionality of a queue - specifically, a FIFO (first-in, first-out) data structure."7 In .NET,Queue<T>"Represents a first-in, first-out collection of objects."8 The C# solution usesTryDequeuein the loop condition, so the loop stops when the queue is empty. - C uses a ring buffer. The queue never holds more than
njobs, so an array ofnslots is sufficient. The index of the back is(head + count) % n. For the idea, see Ring buffer. - Go uses a slice.
q[0]is the front, andq = q[1:]removes it. The packagecontainer/listis another choice: "Package list implements a doubly linked list."9 - Rust uses
VecDeque.pop_front"Removes the first element and returns it, or None if the deque is empty."10 Sowhile let Some(job) = queue.pop_front()is the loop. - Bash keeps a head index. The solution adds with
q+=("$x")and reads${q[head]}. It does not remove items from the array, so the indices stay 0, 1, 2 and so on.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: no jobs give an empty list. The C solution returns at once whennis 0, before it gets memory.one: one job finishes after enough rounds, with no other job between them.big-slice: each job finishes in its first turn, so the order is the queue order, 0, 1, 2.slice-one: the jobs take turns one time unit at a time.equal-work: jobs with the same work finish in queue order.long-job-first: a long job at the front goes to the back again and again, and the short jobs after it finish first.
Pitfalls
- Python
list.pop(0)is slow. The tutorial says: "While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one)."1 With 20,000 items, the time to empty a list withpop(0)is much more than the time to empty a deque withpopleft():
import time
from collections import deque
n = 20_000
items = list(range(n))
start = time.perf_counter()
while items:
items.pop(0)
list_time = time.perf_counter() - start
queue = deque(range(n))
start = time.perf_counter()
while queue:
queue.popleft()
deque_time = time.perf_counter() - start
print("list.pop(0) more than 5 times slower:", "yes" if list_time > 5 * deque_time else "no")
list.pop(0) more than 5 times slower: yes
- Java
poll()cannot tell null from empty. "Queue implementations generally do not allow insertion of null elements"6, butLinkedListallows them. The documentation continues: "null is also used as a special return value by the poll method to indicate that the queue contains no elements."6 With a null in aLinkedList, the two results ofpoll()look the same.ArrayDequerefuses null, so use it:
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.offer(null);
System.out.println("poll: " + queue.poll() + ", size: " + queue.size());
System.out.println("poll: " + queue.poll() + ", size: " + queue.size());
}
}
poll: null, size: 0
poll: null, size: 0
- C++
front()on an empty queue is not checked. The default container ofstd::queueisstd::deque. Forfront()on an empty container, "the behavior is undefined"11 (until C++26).pop()returns nothing, so readfront()first, and testempty()before both. - C#
Dequeuethrows on an empty queue. TheDequeuepage givesInvalidOperationExceptionfor the case "The Queue is empty."12 UseTryDequeuewhen the queue can be empty. - Bash
unset 'q[0]'leaves a hole. "unset name[subscript] unsets the array element at index subscript."13 The other elements keep their indices, so${q[0]}is then empty and the front is at index 1. Keep a head index, or read the indices with${!q[@]}:
q=(a b c)
unset 'q[0]'
echo "count: ${#q[@]}, q[0]: [${q[0]}]"
echo "indices: ${!q[@]}"
count: 2, q[0]: []
indices: 1 2
Related tasks
- Use a stack: the last item in is the first item out.
- Use a priority queue: the item with the best priority is the next item out.
- Queue: the idea behind this task and the operations.
- Ring buffer: a queue with a fixed size in an array.
- Producer-consumer: a queue between threads.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-queue/.
from collections import deque
def finish_order(work: list[int], slice: int) -> list[int]:
"""Returns the job numbers in the order in which round-robin finishes them."""
left = list(work) # a copy, so the list of the caller does not change
queue = deque(range(len(work))) # not a list: list.pop(0) is slow
done = []
while queue:
job = queue.popleft() # dequeue from the front
left[job] -= min(slice, left[job])
if left[job] == 0:
done.append(job)
else:
queue.append(job) # enqueue at the back
return done
test_round_robin.py 25 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-queue/.
import pytest
from round_robin import finish_order
CASES = {
"example": ([3, 1, 2], 1, [1, 2, 0]),
"slice-two": ([4, 1, 3, 2], 2, [1, 3, 0, 2]),
"empty": ([], 3, []),
"one": ([7], 2, [0]),
"big-slice": ([3, 1, 2], 10, [0, 1, 2]),
"slice-one": ([2, 2, 1], 1, [2, 0, 1]),
"equal-work": ([2, 2, 2], 1, [0, 1, 2]),
"long-job-first": ([10, 1, 1], 3, [1, 2, 0]),
}
@pytest.mark.parametrize("case", CASES)
def test_finish_order(case):
work, slice_, want = CASES[case]
before = list(work)
assert finish_order(work, slice_) == want
assert work == before
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
#include "round_robin.hpp"
#include <algorithm>
#include <queue>
std::vector<std::size_t> finish_order(const std::vector<std::int32_t> &work, std::int32_t slice) {
std::vector<std::int32_t> left = work;
std::queue<std::size_t> queue;
for (std::size_t i = 0; i < work.size(); i++) {
queue.push(i); // enqueue at the back
}
std::vector<std::size_t> done;
while (!queue.empty()) {
std::size_t job = queue.front(); // read the front first:
queue.pop(); // pop() returns nothing
left[job] -= std::min(slice, left[job]);
if (left[job] == 0) {
done.push_back(job);
} else {
queue.push(job);
}
}
return done;
}
round_robin.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
#pragma once
#include <cstddef>
#include <cstdint>
#include <vector>
// finish_order returns the job numbers in the order in which round-robin
// finishes them.
std::vector<std::size_t> finish_order(const std::vector<std::int32_t> &work, std::int32_t slice);
test_round_robin.cpp 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
#include "round_robin.hpp"
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view label, const std::vector<std::int32_t> &work, std::int32_t slice,
const std::vector<std::size_t> &want) {
if (finish_order(work, slice) != want) {
std::cerr << "case " << label << " failed\n";
failures++;
}
}
int main() {
check("example", {3, 1, 2}, 1, {1, 2, 0});
check("slice-two", {4, 1, 3, 2}, 2, {1, 3, 0, 2});
check("empty", {}, 3, {});
check("one", {7}, 2, {0});
check("big-slice", {3, 1, 2}, 10, {0, 1, 2});
check("slice-one", {2, 2, 1}, 1, {2, 0, 1});
check("equal-work", {2, 2, 2}, 1, {0, 1, 2});
check("long-job-first", {10, 1, 1}, 3, {1, 2, 0});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
final class RoundRobin {
private RoundRobin() {}
/** Returns the job numbers in the order in which round-robin finishes them. */
static List<Integer> finishOrder(List<Integer> work, int slice) {
int[] left = new int[work.size()];
Queue<Integer> queue = new ArrayDeque<>();
for (int i = 0; i < left.length; i++) {
left[i] = work.get(i);
queue.offer(i); // enqueue at the tail
}
List<Integer> done = new ArrayList<>();
while (!queue.isEmpty()) {
int job = queue.poll(); // dequeue from the head
left[job] -= Math.min(slice, left[job]);
if (left[job] == 0) {
done.add(job);
} else {
queue.offer(job);
}
}
return done;
}
}
RoundRobinTest.java 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class RoundRobinTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("example", List.of(3, 1, 2), 1, List.of(1, 2, 0)),
Arguments.of("slice-two", List.of(4, 1, 3, 2), 2, List.of(1, 3, 0, 2)),
Arguments.of("empty", List.of(), 3, List.of()),
Arguments.of("one", List.of(7), 2, List.of(0)),
Arguments.of("big-slice", List.of(3, 1, 2), 10, List.of(0, 1, 2)),
Arguments.of("slice-one", List.of(2, 2, 1), 1, List.of(2, 0, 1)),
Arguments.of("equal-work", List.of(2, 2, 2), 1, List.of(0, 1, 2)),
Arguments.of("long-job-first", List.of(10, 1, 1), 3, List.of(1, 2, 0)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void finishOrder(String name, List<Integer> work, int slice, List<Integer> want) {
List<Integer> before = new ArrayList<>(work);
assertEquals(want, RoundRobin.finishOrder(work, slice));
assertEquals(before, work);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
#include "round_robin.h"
#include <stdlib.h>
bool finish_order(const int32_t *work, size_t n, int32_t slice, size_t *order) {
if (n == 0) {
return true;
}
// C has no queue type. The queue is a ring buffer of n slots: the queue
// never holds more than n jobs. head is the front, and count is the
// number of jobs in the queue.
size_t *queue = malloc(n * sizeof *queue);
int32_t *left = malloc(n * sizeof *left);
if (queue == NULL || left == NULL) {
free(queue);
free(left);
return false;
}
for (size_t i = 0; i < n; i++) {
queue[i] = i;
left[i] = work[i];
}
size_t head = 0;
size_t count = n;
size_t done = 0;
while (count > 0) {
size_t job = queue[head]; // dequeue
head = (head + 1) % n;
count--;
left[job] -= left[job] < slice ? left[job] : slice;
if (left[job] == 0) {
order[done++] = job;
} else {
queue[(head + count) % n] = job; // enqueue at the back
count++;
}
}
free(queue);
free(left);
return true;
}
round_robin.h 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
#ifndef ROUND_ROBIN_H
#define ROUND_ROBIN_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
// finish_order writes the n job numbers to order, in the order in which
// round-robin finishes them. work has n values. order must have room for n
// values. It returns false if it cannot get memory.
bool finish_order(const int32_t *work, size_t n, int32_t slice, size_t *order);
#endif
test_round_robin.c 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
#include "round_robin.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
#define CHECK(label, w, s, want) \
do { \
const int32_t work[] = w; \
const size_t expect[] = want; \
const size_t n = sizeof work / sizeof work[0]; \
size_t order[sizeof work / sizeof work[0]] = {0}; \
if (!finish_order(work, n, (s), order) || \
memcmp(order, expect, sizeof expect) != 0) { \
fprintf(stderr, "case %s failed\n", label); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("example", L(3, 1, 2), 1, L(1, 2, 0));
CHECK("slice-two", L(4, 1, 3, 2), 2, L(1, 3, 0, 2));
size_t none[1] = {0};
if (!finish_order(NULL, 0, 3, none)) { // the case "empty"
fprintf(stderr, "case empty failed\n");
failures++;
}
CHECK("one", L(7), 2, L(0));
CHECK("big-slice", L(3, 1, 2), 10, L(0, 1, 2));
CHECK("slice-one", L(2, 2, 1), 1, L(2, 0, 1));
CHECK("equal-work", L(2, 2, 2), 1, L(0, 1, 2));
CHECK("long-job-first", L(10, 1, 1), 3, L(1, 2, 0));
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
using System;
using System.Collections.Generic;
public static class RoundRobin
{
// Returns the job numbers in the order in which round-robin finishes them.
public static List<int> FinishOrder(IReadOnlyList<int> work, int slice)
{
var left = new int[work.Count];
var queue = new Queue<int>();
for (int i = 0; i < work.Count; i++)
{
left[i] = work[i];
queue.Enqueue(i);
}
var done = new List<int>();
while (queue.TryDequeue(out int job))
{
left[job] -= Math.Min(slice, left[job]);
if (left[job] == 0)
{
done.Add(job);
}
else
{
queue.Enqueue(job);
}
}
return done;
}
}
RoundRobinTests.cs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
using System.Linq;
using Xunit;
public sealed class RoundRobinTests
{
public static TheoryData<string, int[], int, int[]> Cases => new()
{
{ "example", new[] { 3, 1, 2 }, 1, new[] { 1, 2, 0 } },
{ "slice-two", new[] { 4, 1, 3, 2 }, 2, new[] { 1, 3, 0, 2 } },
{ "empty", new int[0], 3, new int[0] },
{ "one", new[] { 7 }, 2, new[] { 0 } },
{ "big-slice", new[] { 3, 1, 2 }, 10, new[] { 0, 1, 2 } },
{ "slice-one", new[] { 2, 2, 1 }, 1, new[] { 2, 0, 1 } },
{ "equal-work", new[] { 2, 2, 2 }, 1, new[] { 0, 1, 2 } },
{ "long-job-first", new[] { 10, 1, 1 }, 3, new[] { 1, 2, 0 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[] work, int slice, int[] want)
{
Assert.NotNull(name);
var before = work.ToArray();
Assert.Equal(want, RoundRobin.FinishOrder(work, slice));
Assert.Equal(before, work);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
// finishOrder returns the job numbers in the order in which round-robin
// finishes them. JavaScript has no queue type. shift() on an array moves all
// of the other elements, so the queue is an array with a head index: push
// adds at the back, and the head index moves forward to dequeue.
export function finishOrder(work, slice) {
const left = [...work];
const queue = work.map((_, i) => i);
let head = 0;
const done = [];
while (head < queue.length) {
const job = queue[head++];
left[job] -= Math.min(slice, left[job]);
if (left[job] === 0) {
done.push(job);
} else {
queue.push(job);
}
}
return done;
}
round_robin.test.js 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { finishOrder } from "./round_robin.js";
const cases = [
["example", [3, 1, 2], 1, [1, 2, 0]],
["slice-two", [4, 1, 3, 2], 2, [1, 3, 0, 2]],
["empty", [], 3, []],
["one", [7], 2, [0]],
["big-slice", [3, 1, 2], 10, [0, 1, 2]],
["slice-one", [2, 2, 1], 1, [2, 0, 1]],
["equal-work", [2, 2, 2], 1, [0, 1, 2]],
["long-job-first", [10, 1, 1], 3, [1, 2, 0]],
];
for (const [name, work, slice, want] of cases) {
test(name, () => {
const before = [...work];
assert.deepEqual(finishOrder(work, slice), want);
assert.deepEqual(work, before);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
// finishOrder returns the job numbers in the order in which round-robin
// finishes them. The queue is an array with a head index, because shift()
// moves all of the other elements.
export function finishOrder(work: readonly number[], slice: number): number[] {
const left = [...work];
const queue: number[] = work.map((_, i) => i);
let head = 0;
const done: number[] = [];
while (head < queue.length) {
const job = queue[head++];
left[job] -= Math.min(slice, left[job]);
if (left[job] === 0) {
done.push(job);
} else {
queue.push(job);
}
}
return done;
}
round_robin.test.ts 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { finishOrder } from "./round_robin.ts";
const cases: [string, number[], number, number[]][] = [
["example", [3, 1, 2], 1, [1, 2, 0]],
["slice-two", [4, 1, 3, 2], 2, [1, 3, 0, 2]],
["empty", [], 3, []],
["one", [7], 2, [0]],
["big-slice", [3, 1, 2], 10, [0, 1, 2]],
["slice-one", [2, 2, 1], 1, [2, 0, 1]],
["equal-work", [2, 2, 2], 1, [0, 1, 2]],
["long-job-first", [10, 1, 1], 3, [1, 2, 0]],
];
for (const [name, work, slice, want] of cases) {
test(name, () => {
const before = [...work];
assert.deepEqual(finishOrder(work, slice), want);
assert.deepEqual(work, before);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
// Package roundrobin runs jobs in turn with a queue.
package roundrobin
// FinishOrder returns the job numbers in the order in which round-robin
// finishes them. Go has no queue type in the language. A slice is the queue:
// append adds at the back, and queue[1:] removes the front.
func FinishOrder(work []int, slice int) []int {
left := append([]int(nil), work...)
queue := make([]int, 0, len(work))
for i := range work {
queue = append(queue, i)
}
done := []int{}
for len(queue) > 0 {
job := queue[0]
queue = queue[1:]
left[job] -= min(slice, left[job])
if left[job] == 0 {
done = append(done, job)
} else {
queue = append(queue, job)
}
}
return done
}
round_robin_test.go 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
package roundrobin
import (
"slices"
"testing"
)
var cases = []struct {
name string
work []int
slice int
want []int
}{
{"example", []int{3, 1, 2}, 1, []int{1, 2, 0}},
{"slice-two", []int{4, 1, 3, 2}, 2, []int{1, 3, 0, 2}},
{"empty", []int{}, 3, []int{}},
{"one", []int{7}, 2, []int{0}},
{"big-slice", []int{3, 1, 2}, 10, []int{0, 1, 2}},
{"slice-one", []int{2, 2, 1}, 1, []int{2, 0, 1}},
{"equal-work", []int{2, 2, 2}, 1, []int{0, 1, 2}},
{"long-job-first", []int{10, 1, 1}, 3, []int{1, 2, 0}},
}
func TestFinishOrder(t *testing.T) {
for _, c := range cases {
before := slices.Clone(c.work)
if got := FinishOrder(c.work, c.slice); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
if !slices.Equal(c.work, before) {
t.Errorf("%s: the input changed", c.name)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
use std::collections::VecDeque;
/// Returns the job numbers in the order in which round-robin finishes them.
pub fn finish_order(work: &[u32], slice: u32) -> Vec<usize> {
let mut left = work.to_vec();
let mut queue: VecDeque<usize> = (0..work.len()).collect();
let mut done = Vec::new();
while let Some(job) = queue.pop_front() {
left[job] -= slice.min(left[job]);
if left[job] == 0 {
done.push(job);
} else {
queue.push_back(job);
}
}
done
}
tests/round_robin_test.rs 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-queue/.
use algo_use_a_queue::finish_order;
#[test]
fn cases() {
let cases: Vec<(&str, Vec<u32>, u32, Vec<usize>)> = vec![
("example", vec![3, 1, 2], 1, vec![1, 2, 0]),
("slice-two", vec![4, 1, 3, 2], 2, vec![1, 3, 0, 2]),
("empty", vec![], 3, vec![]),
("one", vec![7], 2, vec![0]),
("big-slice", vec![3, 1, 2], 10, vec![0, 1, 2]),
("slice-one", vec![2, 2, 1], 1, vec![2, 0, 1]),
("equal-work", vec![2, 2, 2], 1, vec![0, 1, 2]),
("long-job-first", vec![10, 1, 1], 3, vec![1, 2, 0]),
];
for (name, work, slice, want) in cases {
assert_eq!(finish_order(&work, slice), want, "case {name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-queue/.
# finish_order SLICE WORK...
# Prints the job numbers in the order in which round-robin finishes them, on
# one line. The queue is an indexed array with a head index: q+=(x) adds at
# the back, and the head index moves forward to dequeue.
finish_order() {
local slice=$1 job head=0 run
shift
local -a left=("$@") q=() finished=()
for ((job = 0; job < $#; job++)); do
q+=("$job")
done
while ((head < ${#q[@]})); do
job=${q[head]}
head=$((head + 1))
run=$((left[job] < slice ? left[job] : slice))
left[job]=$((left[job] - run))
if ((left[job] == 0)); then
finished+=("$job")
else
q+=("$job")
fi
done
printf '%s\n' "${finished[*]}"
}
test_round_robin.bats 26 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-queue/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/round_robin.sh"
}
check() { # check WANT SLICE WORK...
local want=$1
shift
run finish_order "$@"
[ "$status" -eq 0 ]
[ "$output" = "$want" ] || { printf 'got: %s\nwant: %s\n' "$output" "$want"; return 1; }
}
@test "example" { check '1 2 0' 1 3 1 2; }
@test "slice-two" { check '1 3 0 2' 2 4 1 3 2; }
@test "empty" { check '' 3; }
@test "one" { check '0' 2 7; }
@test "big-slice" { check '0 1 2' 10 3 1 2; }
@test "slice-one" { check '2 0 1' 1 2 2 1; }
@test "equal-work" { check '0 1 2' 1 2 2 2; }
@test "long-job-first" { check '1 2 0' 3 10 1 1; }
References
- The Python Tutorial, 5. Data Structures, 5.1.2 Using Lists as Queues
- collections, Container datatypes, Python documentation, deque objects
- queue, A synchronized queue class, Python documentation, the introduction
- Array.prototype.shift(), MDN Web Docs, Description
- ArrayDeque (Java SE 27 and JDK 27), the class description
- Queue (Java SE 27 and JDK 27), the interface description
- std::queue, cppreference.com, the introduction
- Queue<T> Class, .NET API reference, the summary; Methods
- Package list, Go standard library, Overview
- Struct VecDeque, The Rust Standard Library, the description; pop_front
- std::deque::front, cppreference.com, the description
- Queue<T>.Dequeue Method, .NET API reference, Exceptions
- Bash Reference Manual, 6.7 Arrays
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag HF28E8 Edit this page History Report an error Markdown