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 (
Ttaken,Nnot taken) first predict, then update: taken adds 1 up to 3, not taken subtracts 1 down to 0. - Print one line of marks,
Cfor a correct prediction andWfor a wrong one, thencorrect 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
3 TTTTNTTTTN
CCCCWCCCCW correct 8 of 10
0 TTTT
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