Permutation through binary representations

Common computers do their calculations with binary numbers (0 and 1). In the following we’ll use binary counting as a structure to get all possible combinations in a given range. Then we’ll interpret 0’s as white cells and 1’s as black cells.

Inspect binary representations

number = 3
binary_representation = f'{number:0b}'  # literal string interpolation (see the Appendix below)
print('number:', number)
print('binary_representation:', binary_representation)
number: 3
binary_representation: 11

For-Loop

for i in range(5):
    print(i)
0
1
2
3
4
# Print several numbers:
for number in range(16):
    binary_representation = f"{number:0b}"
    print(number, '\t', binary_representation)
0 	 0
1 	 1
2 	 10
3 	 11
4 	 100
5 	 101
6 	 110
7 	 111
8 	 1000
9 	 1001
10 	 1010
11 	 1011
12 	 1100
13 	 1101
14 	 1110
15 	 1111
# Same with leading zeros.
max_int = 15 # counting from 0 to 15 = 16 numbers = 4 x 4 grid
max_int_bin = f'{max_int:0b}'
print('max_int_bin:', max_int_bin)

# Get the amount of maximum digits to represent the maximum integer:
digits = len(max_int_bin)
print('digits / cells:', digits, '\n')

for number in range(max_int+1):
    binary_representation = f"{number:0{digits}b}"
    print(number, '\t', binary_representation)
max_int_bin: 1111
digits / cells: 4 

0 	 0000
1 	 0001
2 	 0010
3 	 0011
4 	 0100
5 	 0101
6 	 0110
7 	 0111
8 	 1000
9 	 1001
10 	 1010
11 	 1011
12 	 1100
13 	 1101
14 	 1110
15 	 1111
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np

fig=plt.figure(figsize=(20, 20))
columns = 4
rows = 4
cmap = colors.ListedColormap(['white','black'])

for i in range(max_int+1):
    number = i
    binary_representation = f"{number:0{digits}b}"
    data = [int(n) for n in binary_representation]
    data = np.array(data).reshape((2,2))
    title = f'{i} ( {binary_representation} )'
    fig.add_subplot(rows, columns, i+1).set_title(title)

    # exclude ticks
    plt.xticks(ticks=[])
    plt.yticks(ticks=[])
    plt.imshow(data, cmap=cmap)
plt.show()
_images/permutations_binary_7_0.png

Note that the last one and the first one are displayed in the same color although one is 0,0,0,0 and the other is 1,1,1,1. This is related to matplotlib. You have to figure out how to solve it if necessary.

Appendix

Literal string interpolation

The indicator for string interpolation is a leading f in front of the string, followed by the string indicators ' or ". Inside of the string we can enclose variables or expressions with {}.

name = 'Alice'
print(f'Hello, {name}!')

a = 5
b = 10
print(f"{a} plus {b} is {a + b}.")
Hello, Alice!
5 plus 10 is 15.