Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to generate a 2D array of fixed size containing Random Unique Numbers (with Random.Sample)

I know that I can create an array of unique random numbers using Random.Sample within a defined range of numbers.

What I need to do is basically create a 2D array of 5 rows and 5 columns and each index will contain a pair of two numbers. However, all the 25 pairs must be unique in the whole 2D Array, and the range of numbers is 0-4 (five numbers in total, so total possible pairs are also 5×5 which is 25)

That is, one possible 2D array can be,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Row 1 -> [[0,1], [0,2], [0,3], [1,0], [2,0]]
Row 2 -> [[0,4], [1,1], [1,2], [2,1], [3,0]]
Row 3 -> [[1,3], [1,4], [4,0], [4,1], [3,1]]
Row 4 -> [[2,2], [2,4], [2,3], [4,2], [3,2]]
Row 5 -> [[4,3], [3,3], [4,4], [3,4], [0,0]]

I have tried various ways to do this but I couldn’t achieve the required results. How can I do this using Random.Sample function?

>Solution :

Base Python solution:

from random import shuffle

n = 5

l = [[i, j]  for i in range(n) for j in range(n)]
shuffle(l)
res = [l[i:i+n] for i in range(0, n**2, n)]
print(res)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading