You can shuffle the "flattened" indices. By "flattened" in case of 2x2 matrix I mean index 0
is a [0][0]
, 1
is [0][1]
, 2
is [1][0]
, and 3
is [1][1]
. In general for the matrix with c
columns, index n
is equivalent to [n//c][n%c]
.
The shuffled indices (numbers from 0
to #rows * #columns
) use as indices for the new matrix. I.e. replace_indices = [3, 1, 0, 2]
would mean that in shuffled matrix 0th index ([0][0]
) will be taken from the 3rd index ([1][1]
) of the original matrix. And so on:
from random import shuffle
m = ...
rows = len(m)
cols = len(m[0])
replace_indices = list(range(rows * cols))
shuffle(replace_indices)
shuffled_m = [[0] * cols for c in range(rows)]
for idx, sidx in enumerate(replace_indices):
shuffled_m[idx//rows][idx%rows] = m[sidx//rows][sidx%rows]
now to unshuffle, you can use the same replace_indices
but in reverse:
unshuffled_m = [[0] * cols for c in range(rows)]
for idx, sidx in enumerate(replace_indices):
unshuffled_m[sidx//rows][sidx%rows] = shuffled_m[idx//rows][idx%rows]
In other words, replace_indices
is a symmetric-key of your encryption.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…