130. Circular Buffer Indexing

A AudioBuffer class acts as a circular buffer (ring buffer) for processing audio samples. It has a fixed capacity of 8 slots. The class tracks the buffer's state using a head_index, which indicates where the next sample will be written. Currently, head_index is public. Client code frequently adds samples by directly adding to the index (e.g., index += samples), forgetting to handle the wrap-around logic. This causes the index to exceed the buffer size, leading to out-of-bounds memory access. Your task is to encapsulate the head_index. Implement a public method advanceHead(int steps) that:

  1. Updates the index by adding steps.
  2. Enforces the circular property using modulo arithmetic.
  3. Ensures the index remains strictly within the range [0, 7].

Program Flow:

  1. Initialize AudioBuffer (index starts at 0).
  2. Read integer N (number of operations).
  3. Loop N times:
  4. Read integer steps (number of samples processed).
  5. Call the driver's method to advance the index.
  6. Print the updated head_index.

Input Format:

  • First line: Integer N (number of inputs).
  • Next N lines: Integer steps (amount to advance).
  • Input is provided via standard input (stdin).

Output Format:

  • For each operation, print the current index: Head: <value>
  • Each output must be on a new line.

Example: 

Example 1

Input:

3
5
4
10

Output:

Head: 5
Head: 1
Head: 3

 

Constraints:

  • N range: 1 to 20
  • steps range: 0 to 1000
  • Buffer Capacity: 8
  • Index Valid Range: [0, 7]
  • No dynamic memory allocation

 

 

 

Loading...

Input

3 5 4 10

Expected Output

Head: 5 Head: 1 Head: 3