1

I am looking for a way to generate a matrix with integers values within an interval, where each row of the matrix will be unique (i.e. the set of the elements a row consists of will not be exactly the set of the elements of any other row) Basically, I am looking for the row-wise matrix equivalent of:

random.sample(range(0, 35), i+1

Edit:

The matrix size changes after every iteration. The interval is 0-35. At the moment i have this implemented

for j in range (5):
    comb_elms_list.append(random.sample(range(0, 35), i+1))

where basically I create a unique row and append it. But this has the danger that two rows will have the same elements (even in different order).

martineau
  • 119,623
  • 25
  • 170
  • 301
john
  • 373
  • 1
  • 16

1 Answers1

1

set()s can only hold unique elements - tuples are hashable and can be put into a set.

Create tuples of numbers from an interval and add them into a set until the set-length matches your amount of rows. Then create a list of lists from the set:

import random

interval = range(100) # plenty more numbers then neeeded to fill 5*3 w/o repeats

matrix = (5,3)

ranges= set()
while len(ranges) < matrix[0]:
    ranges.add(tuple(random.sample(interval, k=matrix[1])))

matrix = [ list(t) for t in ranges ]

print(matrix)

Make sure you have a big enought of an interval, else you'll get the same tuples over and over and your while will never finish.

Output:

[[23, 16, 93], [50, 60, 38], [86, 12, 3], [35, 28, 89], [77, 47, 36]]

If you want to use all numbers in your range it is easier to shuffle them and partition them:

import random

matrix = (5,3)           # dimension of matrix
m = matrix[0]*matrix[1]  # total numbers needed

interval = random.sample(range(m), k=m) # create a shuffled list of the complete range

# partition the list into correctly sized intervals    
k = [ interval[i*matrix[1]:(i+1)*matrix[1]] for i in range(matrix[0])]


print(k) # [[12, 3, 4], [2, 11, 8], [10, 5, 14], [1, 0, 6], [13, 9, 7]]

For partitioning you can read more in How do you split a list into evenly sized chunks?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Thank you for the answer. It doesnt do quite what i was looking for, but this is good enough, thanks! – john Feb 15 '19 at 15:56