A group on a K-map must be a block of 1, 2, 4, 8 or 16 cells in which some variables stay fixed and the others take every combination. Then it becomes one product term.
What to build
Decide whether a set of cells is a valid K-map group, and print its product term if it is.
Requirements
- The variables are A, B, C, D with A as the leftmost bit.
- A valid group has 2ᶜ cells, and in the cells exactly
cvariables change while all combinations of those variables appear. - If the group is valid, print its product term: the variables that stay fixed, written in order, with
'for a variable that is 0. A group with no fixed variable gives1. - If it is not valid, print
no.
Input
A line with n (2 to 4), then a line with the minterm numbers of the cells, separated by spaces, with no number repeated.
Output
The product term, or no.
Constraints
2 ≤ n ≤ 4. A group has at least one cell.
Example
Input:
3
3 7
Output:
BC
Why it works
If c bits change among the cells, the cells can only form a block when every one of the 2ᶜ combinations of those bits is present. Since the cells are all different, having exactly 2ᶜ cells guarantees that. Cells such as 0 and 3 in a 2-variable map change two bits but there are only 2 cells, so they are diagonal and cannot be a group.
Examples
3 3 7
BC
2 0 3
no
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The group size must be a power of 2: 1, 2, 4, 8 or 16.
Hint 2
A bit that is the same in every cell stays in the term. Find it with AND of all the cells (the bits that are 1 everywhere) and OR of all the cells (the bits that are 1 anywhere); the two differ exactly in the bits that change.
Hint 3
If the number of changing bits is `c`, a valid group has 2ᶜ cells. If the count does not match, some cell is missing.
Solution
Show one correct solution (try it yourself first)
n = int(input())
cells = list(map(int, input().split()))
names = "ABCD"
all_and = (1 << n) - 1
all_or = 0
for c in cells:
all_and &= c
all_or |= c
changing = all_and ^ all_or
count_changing = bin(changing).count("1")
if len(cells) != 2 ** count_changing:
print("no")
else:
term = ""
for i in range(n):
bit = 1 << (n - 1 - i)
if not changing & bit:
term += names[i] if all_and & bit else names[i] + "'"
print(term if term else "1")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step