trosy
trosy

Reputation: 93

How to make a circular buffer?

I have to make a circular buffer out of an array for class and I can't quite grasp how the concept is implemented. I get that there are are indexes that go back and forth but I don't really understand how this is actually implemented. How do you even assign a tail or head to elements of an array, or index them both ways? Any advice, code or explanation would be extremely helpful.

Upvotes: 0

Views: 394

Answers (2)

bwegs
bwegs

Reputation: 3767

You make something circular by connecting the tail of the structure to its head. In an array this can be done in a number of different ways (Iterator, custom class/handler, etc.) but what they all have in common is the next element after the tail is the head.

Here is a very simple example using the % operator to handle the tail to head 'connection':

int[] ary = {0, 3, 5};

for(int i = 0; i < 100; i++) {
    System.out.println(ary[i % 3]);
}

this loop will output: 0 3 5 0 3 5 0 3 5......for 100 iterations

Upvotes: 0

Thilo
Thilo

Reputation: 262474

A circular buffer is basically just an array and two integers that keep track of the positions that you consider to be the "tail" and the "head".

The empty buffer starts out with both "tail" and "head" at the same index (0 is as good a choice as any).

When you add to the buffer, you insert at where the "tail" points add, and then move the tail to next position. It gets "circular" because when the "tail" falls off the end of the array, it jumps back to its beginning (index 0).

Similarly, you remove from the buffer from either head or tail end by looking at and adjusting the respective positions.

Upvotes: 1

Related Questions