Lab 5 – Queues
Part 1 – A queue on a circular array¶
Task 1 – How a circular array works¶
Create an array T of size 10 filled with 1 to 10. Then write the values 1 to 3214 into
it in a circular way, starting at index 0: value v goes into cell (v - 1) % 10.
What does T contain at the end? Predict it before running the code.
Solution
int[] T = new int[10];
for (int i = 0; i < 10; i++)
T[i] = i + 1; // 1..10
for (int v = 1; v <= 3214; v++)
T[(v - 1) % 10] = v; // value v goes to cell (v-1) % 10
for (int x : T)
System.out.print(x + " ");
System.out.println();Expected output:
3211 3212 3213 3214 3205 3206 3207 3208 3209 3210 Task 2 – A generic queue¶
The ADT:
interface QueueADT<E> {
void enqueue(E x);
E dequeue();
E front();
boolean isEmpty();
}Implement it with a circular array of capacity + 1 cells, starting with front = 1 and
rear = 0:
| state | condition |
|---|---|
| empty | (rear + 1) % size == front |
| full | (rear + 2) % size == front |
🚩 Java cannot create a generic array with
new E[size]. Create anObject[]and cast it:data = (E[]) new Object[size];
class Queue<E> implements QueueADT<E> {
private int size, front, rear;
private E[] data;
public Queue(int capacity) {
// ToDo
}
public boolean isEmpty() { /* ToDo */ }
private boolean full() { /* ToDo */ }
public void enqueue(E x) { /* ToDo */ }
public E dequeue() { /* ToDo */ }
public E front() { /* ToDo */ }
}Solution
class Queue<E> implements QueueADT<E> {
private int size, front, rear;
private E[] data;
@SuppressWarnings("unchecked")
public Queue(int capacity) {
size = capacity + 1; // one cell always stays empty
data = (E[]) new Object[size]; // a generic array, created as Object[]
front = 1;
rear = 0;
}
public boolean isEmpty() {
return (rear + 1) % size == front;
}
private boolean full() {
return (rear + 2) % size == front;
}
public void enqueue(E x) {
if (full()) {
System.out.println("queue is full");
return;
}
rear = (rear + 1) % size;
data[rear] = x;
}
public E dequeue() {
if (isEmpty())
return null;
E x = data[front];
data[front] = null; // let the garbage collector free it
front = (front + 1) % size;
return x;
}
public E front() {
return isEmpty() ? null : data[front];
}
}Test your queue¶
Queue<Integer> Q = new Queue<>(9);
System.out.println(Q.isEmpty());
for (int i = 1; i < 9; i++) {
Q.enqueue(i);
if (i % 3 == 0)
Q.dequeue();
}
System.out.println("front: " + Q.front());
while (!Q.isEmpty())
System.out.print(Q.dequeue() + " ");
System.out.println();Expected output:
true
front: 3
3 4 5 6 7 8 Task 3 – Reverse a queue with a stack¶
A queue keeps the order; a stack reverses it. Move all the elements of the queue to your
Stack of Lab 4, then back into the queue.
Solution
Queue<Integer> q = new Queue<>(9);
Stack<Integer> s = new Stack<>();
for (int i = 1; i <= 9; i++)
q.enqueue(i);
while (!q.isEmpty()) // queue -> stack
s.push(q.dequeue());
while (!s.isEmpty()) // stack -> queue: reversed
q.enqueue(s.pop());
while (!q.isEmpty())
System.out.print(q.dequeue() + " ");
System.out.println();Expected output:
9 8 7 6 5 4 3 2 1 Part 2 – Use the JDK¶
Challenge 1 – The Josephus problem¶
n people stand in a circle; counting round, every k-th person leaves. Who remains? The
queue is the circle: move k - 1 people from the front to the back, then remove the
next one. Print the order in which people leave.
Solution
static int josephus(int n, int k) {
Queue<Integer> q = new ArrayDeque<>();
for (int i = 1; i <= n; i++)
q.offer(i);
StringBuilder order = new StringBuilder();
while (q.size() > 1) {
for (int i = 1; i < k; i++)
q.offer(q.poll()); // skipped: back to the end of the line
order.append(q.poll()).append(' '); // the k-th person leaves
}
System.out.println("leave in order: " + order);
return q.poll();
}System.out.println("survivor: " + josephus(7, 3));
System.out.println("survivor: " + josephus(6, 2));Expected output:
leave in order: 3 6 2 7 5 1
survivor: 4
leave in order: 2 4 6 3 1
survivor: 5Challenge 2 – The binary numbers from 1 to n¶
Start with "1" in a queue. Repeatedly take a string s from the front, output it, and
add s + "0" and s + "1" at the back. In FIFO order the numbers come out increasing.
Solution
static List<String> binaries(int n) {
List<String> res = new ArrayList<>();
Queue<String> q = new ArrayDeque<>();
q.offer("1");
while (res.size() < n) {
String s = q.poll();
res.add(s);
q.offer(s + "0"); // the two "children" of s
q.offer(s + "1");
}
return res;
}System.out.println(binaries(10));Expected output:
[1, 10, 11, 100, 101, 110, 111, 1000, 1001, 1010]Challenge 3 – Round-robin scheduling¶
Processes wait in a ready queue. Each one runs for at most quantum time units, then goes
back to the end of the queue if it is not finished. Print when each process finishes, for
P1, P2, P3 needing 5, 3 and 1 units with a quantum of 2 (the example of the slides).
Solution
static void roundRobin(String[] names, int[] needs, int quantum) {
Queue<Integer> ready = new ArrayDeque<>(); // process numbers
int[] left = needs.clone();
for (int i = 0; i < names.length; i++)
ready.offer(i);
int time = 0;
while (!ready.isEmpty()) {
int p = ready.poll();
int run = Math.min(quantum, left[p]);
time += run;
left[p] -= run;
if (left[p] > 0)
ready.offer(p); // not finished: back of the line
else
System.out.println(names[p] + " finishes at " + time);
}
}roundRobin(new String[]{"P1", "P2", "P3"}, new int[]{5, 3, 1}, 2);Expected output:
P3 finishes at 5
P2 finishes at 8
P1 finishes at 9