THINK FIRST·CODE LATER

← All labs

A fixed-capacity circular queue

Problem

Implement a queue of int on a circular array of fixed capacity, with fields data, front (index of the oldest element, initially 0) and size. The array never grows.

  • enqueue stores at (front + size) % capacity;
  • dequeue returns data[front] and sets front = (front + 1) % capacity.

Input: the capacity (≥ 1) on the first line, then one command per line until the input ends:

Command Output
enqueue x nothing, or full if the queue already holds capacity elements (x is then discarded)
dequeue the removed value, or empty
peek the front value without removing it, or empty
size size <n>
print front=<front index> followed by the elements from front to back, e.g. front=2 [30, 40, 50]

Example with capacity 3:

enqueue 1
enqueue 2
enqueue 3
enqueue 4
print
dequeue
enqueue 4
print

prints

full
front=0 [1, 2, 3]
1
front=1 [2, 3, 4]

(4 was stored in slot 0: the queue wrapped round.)

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d10-2-data-1.txt

3
enqueue 1
enqueue 2
enqueue 3
enqueue 4
print
dequeue
enqueue 4
print
size
What your program must print for d10-2-data-1.txt
full
front=0 [1, 2, 3]
1
front=1 [2, 3, 4]
size 3

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d10-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content d10-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.