The keyboard buffer

A key press raises an interrupt. The handler must be quick, so it only stores the character in a small ring buffer in the kernel. The program reads the characters later, when it asks. If the buffer is full when a key arrives, the character is lost.

What to build

Simulate the keyboard handler and a program that reads from the buffer.

Requirements

  • The buffer holds up to N characters, first in, first out, and starts empty.
  • key c: the interrupt handler stores the character c if there is room; if the buffer is full the character is dropped and counted.
  • read: the program takes the oldest character and prints it on its own line; if the buffer is empty it prints empty.
  • At the end print dropped: D and left: L, the number of dropped characters and the number still in the buffer.

Input

The first line has N (1 ≤ N ≤ 8) and q (1 ≤ q ≤ 40). Then q events, one per line: key c (a single letter or digit) or read.

Output

One line for each read, then dropped: D and left: L.

Constraints

Characters are letters and digits only.

Example

Input:

3 7
key a
key b
read
key c
key d
key e
read

Output:

a
b
dropped: 1
left: 2

Why it works

The handler never waits: when the buffer is full it just drops the key, because blocking inside an interrupt handler would freeze the whole machine. The ring buffer lets the fast interrupt side and the slow program side work at their own speed.

Examples

Example 1 · Input
3 7
key a
key b
read
key c
key d
key e
read
Expected output
a
b
dropped: 1
left: 2
Example 2 · Input
2 3
read
key x
read
Expected output
empty
x
dropped: 0
left: 0

Hints

Hint 1

Use an array of N chars as a circular queue with in, out and count, like the bounded buffer.

Hint 2

Read the event word, then for key read one character with scanf(" %c", &c).

Hint 3

A key into a full buffer is dropped: count it and change nothing else.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>
#include <string.h>

int main(void) {
    int cap, q, in = 0, out = 0, count = 0, dropped = 0;
    char buffer[8], word[8], c;
    scanf("%d %d", &cap, &q);
    for (int i = 0; i < q; i++) {
        scanf("%7s", word);
        if (strcmp(word, "key") == 0) {
            scanf(" %c", &c);
            if (count == cap) {
                dropped++;
            } else {
                buffer[in] = c;
                in = (in + 1) % cap;
                count++;
            }
        } else {
            if (count == 0) {
                printf("empty\n");
            } else {
                printf("%c\n", buffer[out]);
                out = (out + 1) % cap;
                count--;
            }
        }
    }
    printf("dropped: %d\n", dropped);
    printf("left: %d\n", count);
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Input, output and interrupts →