0

I have a matrix as follows.

mat = [[23,45,56,67],
       [12,67,09,78],
       [20,59,48,15],
       [00,06,51,90]]

I want to write a function where depending on the argument passed to the function, the rows of the matrix must be shifted and shuffled. For eg: if the argument passed to the function is 2, then the 2nd row of the matrix mat must be made as 0th row while the rest of the rows 1-3 must be shuffled as shown below.

value = 2

mat = [[20,59,48,15],
       [00,06,51,90],
       [23,45,56,67],
       [12,67,09,78]]

The rows 1-3 in the above matrix should be randomly shuffled. One example of how the matrix should look like is shown above.

Is there a way to write a function for this?

Thanks!

EngGu
  • 459
  • 3
  • 14
  • Does this answer your question? [Numpy shuffle multidimensional array by row only, keep column order unchanged](https://stackoverflow.com/questions/35646908/numpy-shuffle-multidimensional-array-by-row-only-keep-column-order-unchanged) This doesn't answer the shifting part, but there you can just take out the one row that you want to shift, then shuffle the array that's left and append the shifted row to the end of the shuffled array. – MangoNrFive Jul 26 '22 at 11:27

1 Answers1

1
mat = [[23,45,56,67],
       [12,67,9,78],
       [20,59,48,15],
       [0,6,51,90]]

def shift(mat, row_index):
    return mat[row_index:] + mat[:row_index]

for row in shift(mat, 2): print(row)   

Output

[20, 59, 48, 15]
[0, 6, 51, 90]
[23, 45, 56, 67]
[12, 67, 9, 78]

EDIT :

My bad, I didn't read the shuffle randomly part. Here's the right function, put the 2th row in first place and shuffle the rest of the matrix.

def shift_and_shuffle(mat, row_index):
    rest_mat = mat[row_index+1:] + mat[:row_index]
    return [mat[row_index]] + random.sample(rest_mat, len(rest_mat))
ArrowRise
  • 608
  • 2
  • 7