Ring Buffer That Overwrites
Implement a class RingBuffer, a buffer of integers with room for capacity values that overwrites its oldest value once it is full. Write these methods:
RingBuffer(capacity)makes an empty buffer.write(x)addsxas the newest value. If the buffer was already full, its oldest value is thrown away to make room andwritereturns that value. Otherwisewritereturns-1.read()removes the oldest value and returns it, or returns-1if the buffer is empty.to_list()returns the values in the buffer from oldest to newest (an empty list if there are none). The buffer does not change.count_free()returns how many more values fit before the buffer is full.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
RingBuffer(3)
write(1) returns -1
write(2) returns -1
write(3) returns -1
write(4) returns 1
to_list() returns [2,3,4]
read() returns 2
count_free() returns 1
write(5) returns -1
to_list() returns [3,4,5]
The buffer fills with 1 2 3. Writing 4 throws away the oldest value 1. Reading takes 2, which leaves one free slot, so writing 5 overwrites nothing.
Constraints
1 <= capacity <= 60 <= x <= 99- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.