Where is the cell on the map?

On a Karnaugh map, the row and column labels are in Gray code, so cells that touch (even across the edge) differ in exactly one variable.

What to build

Given a minterm number, print the labels of its row and column and the minterms that are its neighbours on the map.

Requirements

  • The variables are A, B, C, D with A as the leftmost bit. With 2 variables, the row variable is A and the column variable is B. With 3 variables, the rows are A and the columns are BC. With 4 variables, the rows are AB and the columns are CD.
  • Line 1 is row , the row label, col, then the column label, for example row 11 col 01.
  • Line 2 is neighbours followed by the minterm numbers of the cells that differ by exactly one bit, in increasing order.

Input

One line with n (2 to 4) and the minterm number k.

Output

Two lines, as described.

Constraints

2 ≤ n ≤ 4, 0 ≤ k < 2ⁿ.

Example

Input:

4 13

Output:

row 11 col 01
neighbours 5 9 12 15

Why it works

The labels are just the bits of k: the row label is its first half and the column label is its second half. The map is laid out so that these labels follow Gray code, so a cell and the cell beside it differ in one bit. Every cell has exactly n neighbours, one for each bit that can be flipped, which includes the neighbours across the edge of the map.

Examples

Example 1 · Input
4 13
Expected output
row 11 col 01
neighbours 5 9 12 15
Example 2 · Input
3 6
Expected output
row 1 col 10
neighbours 2 4 7

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

Hints

Hint 1

Rows use the first half of the variables, columns the second half. For 3 variables, the rows are A and the columns are BC; for 2 variables, rows A and columns B.

Hint 2

Gray code position p is p ^ (p >> 1). The columns and rows are labelled with Gray code, so the label of the cell is the Gray code of its row and column positions.

Hint 3

Neighbours of a cell are the minterms that differ in exactly one bit: flip each bit in turn with k ^ (1 << i).

Solution

Show one correct solution (try it yourself first)
n, k = map(int, input().split())
bits = format(k, "0" + str(n) + "b")
rows = n // 2
print("row", bits[:rows], "col", bits[rows:])
print("neighbours", *sorted(k ^ (1 << i) for i in range(n)))

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

Lesson: Karnaugh maps →