A ROM is a truth table made of hardware. The address lines are the inputs, and the word stored at an address is the row's outputs, so a ROM with k bits per word can hold k functions of the address at once.
What to build
Write out the contents of the ROM that holds several functions of the same inputs.
Requirements
- Each function is given by its output column as a string of bits, in row order.
- The first function is the leftmost bit of each word.
- Print one line for each address, in order: the address in binary with
ndigits, a space, and the word.
Input
The first line has n (the number of inputs, 1 to 4) and k (the number of functions, 1 to 4). Then k lines, each with the 2ⁿ output bits of one function.
Output
2ⁿ lines, one for each address.
Constraints
1 ≤ n ≤ 4, 1 ≤ k ≤ 4.
Example
Input:
2 2
0110
0001
Output:
00 00
01 10
10 10
11 01
Why it works
A ROM does no calculating at all: it looks up the answer stored for each address. Any set of functions of n variables can be built this way, with 2ⁿ words of k bits. The price is that the size doubles for every new input, so ROMs are good for a few inputs.
Examples
2 2 0110 0001
00 00 01 10 10 10 11 01
3 2 00010111 01101001
000 00 001 01 010 01 011 10 100 01 101 10 110 10 111 11
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The address of the ROM is the input row number. The word at that address has one bit from each function.
Hint 2
For address `a`, the word is the character at position `a` of each function string, written one after the other.
Hint 3
Print the address as `n` binary digits, then a space, then the word.
Solution
Show one correct solution (try it yourself first)
n, k = map(int, input().split())
functions = [input().strip() for _ in range(k)]
for address in range(2 ** n):
word = "".join(f[address] for f in functions)
print(format(address, "0" + str(n) + "b"), word)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step