Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

python - Shuffle matrix without the shuffle() method


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...