The Rock Game

Interview

Time limit1sMemory limit128 MB

Summary
Print the reflected binary Gray code cycle for N bits as 2^N + 1 lines, each line showing X for covered holes and O for uncovered ones.
Level

Easy3 of 10

Topics
Bit manipulation, Math, Implementation, Simulation
Solved
No attempts yet

Problem

Before the cows head home to rest, Farmer John wants them to get some intellectual stimulation by playing a game.

The board has NN (1≤N≤151 \le N \le 15) identical holes in the ground, numbered 11 through NN from left to right. Every hole starts uncovered. In one move a cow either covers exactly one currently uncovered hole with a rock, or uncovers exactly one currently covered hole.

The state of the game is described by which holes are covered and which are not: a string of length NN whose jj-th character is X if hole jj is covered and O if it is uncovered. There are 2N2^N possible states.

The cows want to begin from the all-uncovered state, visit every one of the 2N2^N states exactly once, and then return to the all-uncovered state. Because each move flips exactly one hole, such a tour changes one character at a time and closes back onto its start.

Reaching every state is not automatic. For example, with N=3N = 3 a cow can play seven moves and arrive at state XXX, only to find that uncovering any single hole leads to a state it has already visited — the tour gets stuck before it can return to OOO.

Many valid tours exist. To make the answer unique, you must output one specific canonical tour, defined below in the Output section.

Input

The single line contains one integer NN (1≤N≤151 \le N \le 15).

Output

Print exactly 2N+12^N + 1 lines. Line t+1t + 1 (for t=0,1,…,2Nt = 0, 1, \ldots, 2^N) is the state at time tt of the required canonical tour, the reflected binary Gray-code cycle:

  • Let m=t mod 2Nm = t \bmod 2^N and g=m⊕⌊m/2⌋g = m \oplus \lfloor m / 2 \rfloor (the bitwise XOR of mm with mm shifted right by one bit).
  • Write gg as an NN-bit binary number, most significant bit first. Hole 11 is the most significant bit and hole NN is the least significant bit.
  • Print X for each bit equal to 11 (covered) and O for each bit equal to 00 (uncovered).

Since g=0g = 0 at both t=0t = 0 and t=2Nt = 2^N, the first and last lines are always all O. Consecutive lines always differ in exactly one hole, and the states on lines 11 through 2N2^N are all distinct.

Examples3

  1. Example 1

    Input
    1
    
    Expected output
    O
    X
    O
    
  2. Example 2

    Input
    2
    
    Expected output
    OO
    OX
    XX
    XO
    OO
    
  3. Example 3

    Input
    3
    
    Expected output
    OOO
    OOX
    OXX
    OXO
    XXO
    XXX
    XOX
    XOO
    OOO