Ring and Johnson counters

A ring counter passes a single 1 round a loop of flip-flops. A Johnson counter (a twisted ring) feeds the inverted last bit back to the first, so it has twice as many states with the same number of flip-flops.

What to build

Simulate a ring or Johnson counter, and print its states and its period.

Requirements

  • The register shifts to the right at every clock. The new leftmost bit is the last bit (ring) or its complement (Johnson).
  • A ring counter with n bits starts as 1 followed by n − 1 zeros. A Johnson counter starts as n zeros.
  • Print the state after each of the t clocks, one per line, then a line period followed by the number of clocks after which the counter first returns to its starting state.

Input

One line with ring or johnson, the number of bits n and the number of clocks t.

Output

t lines with the states, then the period line.

Constraints

2 ≤ n ≤ 8, 1 ≤ t ≤ 20.

Example

Input:

ring 4 5

Output:

0100
0010
0001
1000
0100
period 4

Why it works

The ring counter has n states, one for each place of the single 1. The Johnson counter fills the register with 1s one at a time, and then empties it with 0s one at a time, so it has 2n different states with the same flip-flops. Its states differ in only one bit from one to the next, which helps decoding.

Examples

Example 1 · Input
ring 4 5
Expected output
0100
0010
0001
1000
0100
period 4
Example 2 · Input
johnson 4 9
Expected output
1000
1100
1110
1111
0111
0011
0001
0000
1000
period 8

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

Hints

Hint 1

Both counters shift to the right: new = last bit (ring) or 1 minus the last bit (Johnson), and the bit goes in at the left: reg = new + reg[:-1].

Hint 2

The ring counter starts as a 1 followed by zeros, the Johnson counter starts as all zeros.

Hint 3

To find the period, simulate until the register equals its starting value again and count the clocks.

Solution

Show one correct solution (try it yourself first)
kind, n, t = input().split()
n, t = int(n), int(t)
start = "1" + "0" * (n - 1) if kind == "ring" else "0" * n


def step(reg):
    new = reg[-1] if kind == "ring" else str(1 - int(reg[-1]))
    return new + reg[:-1]


reg = start
for _ in range(t):
    reg = step(reg)
    print(reg)
reg = step(start)
period = 1
while reg != start:
    reg = step(reg)
    period += 1
print("period", period)

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

Lesson: Registers and counters →