Detect 1011, overlapping

A sequence detector is a state machine that outputs 1 when the latest bits match a pattern. The matches may overlap, so the end of one match can be the start of the next.

What to build

Run a Mealy machine that detects 1011 on a bit string, and print its output string and the number of matches.

Requirements

  • The output is 1 on the clock when the last bit of 1011 arrives, and 0 on every other clock.
  • Overlapping matches count: in 1011011 the pattern is found twice.
  • Print the output string on the first line, and the number of matches on the second.

Input

One line with a string of 0 and 1.

Output

Two lines: the output string (as long as the input) and the number of 1s in it.

Constraints

The string has 1 to 40 bits.

Example

Input:

1011011

Output:

0001001
2

Why it works

The machine does not need to remember the whole input. It keeps the longest end of the input that is also the start of 1011, and that is exactly what its four states say. After a match, the longest such end is 1, so the machine goes to S1 and a match like 1011011 is not missed.

Examples

Example 1 · Input
1011011
Expected output
0001001
2
Example 2 · Input
1011
Expected output
0001
1

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

Hints

Hint 1

The states are how much of 1011 has just been seen: S0 (nothing useful), S1 (1), S2 (10), S3 (101).

Hint 2

From S3, a 1 completes the pattern (output 1). The last 1 can start a new match, so the next state is S1.

Hint 3

Other moves: S0 on 1 goes to S1; S1 on 0 goes to S2, and on 1 stays in S1; S2 on 1 goes to S3, and on 0 goes back to S0; S3 on 0 goes to S2 (the last `10` is a start of 1011).

Solution

Show one correct solution (try it yourself first)
bits = input().strip()
table = {(0, "0"): (0, "0"), (0, "1"): (1, "0"), (1, "0"): (2, "0"), (1, "1"): (1, "0"),
         (2, "0"): (0, "0"), (2, "1"): (3, "0"), (3, "0"): (2, "0"), (3, "1"): (1, "1")}
state = 0
out = ""
for b in bits:
    state, o = table[(state, b)]
    out += o
print(out)
print(out.count("1"))

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

Lesson: Finite state machines →