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,
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)