Two-bit branch predictor

A 2-bit saturating counter predicts a branch from its recent past. It needs two wrong guesses in a row to change its mind.

What to build

A program that runs a 2-bit predictor over a list of branch outcomes and reports how well it did.

Requirements

  • The counter holds 0 to 3. It predicts taken when it is 2 or 3.
  • For each outcome (T taken, N not taken) first predict, then update: taken adds 1 up to 3, not taken subtracts 1 down to 0.
  • Print one line of marks, C for a correct prediction and W for a wrong one, then correct X of N.

Input

A line with the starting counter value, and a line with the outcomes as a string of T and N.

Output

Two lines.

Constraints

The outcome string has 1 to 200 letters.

Example

Input:

3
TTTTNTTTTN

Output:

CCCCWCCCCW
correct 8 of 10

Why it works

Saturating at 0 and 3 means a long run of one outcome cannot push the counter far, so a single surprise, such as a loop exit, moves it only one step and the next prediction stays the same.

Examples

Example 1 · Input
3
TTTTNTTTTN
Expected output
CCCCWCCCCW
correct 8 of 10
Example 2 · Input
0
TTTT
Expected output
WWCC
correct 2 of 4

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Predict taken when the counter is 2 or 3, not taken when it is 0 or 1.

Hint 2

After a taken branch add 1 to the counter (at most 3); after a not-taken branch subtract 1 (at least 0).

Solution

Show one correct solution (try it yourself first)
counter = int(input())
outcomes = input().strip()
marks = ""
for o in outcomes:
    guess = "T" if counter >= 2 else "N"
    marks += "C" if guess == o else "W"
    counter = min(3, counter + 1) if o == "T" else max(0, counter - 1)
print(marks)
print(f"correct {marks.count('C')} of {len(marks)}")

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

Lesson: Pipeline hazards →