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

Time:02-23

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 5x5 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?

CodePudding user response:

Base Python solution:

from random import shuffle

n = 5
#create all combinations of index values
l = [[i, j]  for i in range(n) for j in range(n)]
#shuffle the list
shuffle(l)
#subdivide into chunks
res = [l[i:i n] for i in range(0, n**2, n)]
print(res)

Sample output:

[[[0, 2], [3, 3], [4, 3], [4, 0], [3, 4]], [[1, 0], [0, 4], [0, 1], [4, 4], [2, 1]], [[0, 0], [2, 3], [2, 2], [2, 0], [1, 1]], [[1, 2], [3, 0], [4, 1], [3, 1], [2, 4]], [[0, 3], [1, 4], [1, 3], [3, 2], [4, 2]]]

CodePudding user response:

Another alternative that uses a set to generate the desired number of unique pairs.

from random import randrange

pairs = set()
while len(pairs) < 25:
    pair = randrange(5), randrange(5)
    pairs.add(pair)

pairs = list(pairs)
array = [pairs[i: i 5] for i in range(0, 25, 5)]

for i, row in enumerate(array, start=1):
    print(f'row {i} -> {row}')

Result:

row 1 -> [(0, 0), (3, 1), (1, 1), (0, 2), (3, 3)]
row 2 -> [(1, 3), (2, 4), (0, 4), (1, 0), (4, 0)]
row 3 -> [(2, 0), (1, 2), (4, 2), (3, 4), (2, 2)]
row 4 -> [(1, 4), (4, 4), (3, 0), (4, 1), (2, 1)]
row 5 -> [(0, 1), (3, 2), (4, 3), (2, 3), (0, 3)]
  • Related