-1

I have a matrix (3x5) where a number is randomly selected in this matrix. I want to swap the selected number with the one down-right. I'm able to locate the index of the randomly selected number but not sure how to replace it with the one that is down then right. For example, given the matrix:

[[169 107 229 317 236]
 [202 124 114 280 106]
 [306 135 396 218 373]]

and the selected number is 280 (which is in position [1,3]), needs to be swapped with 373 on [2,4]. I'm having issues on how to move around with the index. I can hard-code it but it becomes a little more complex when the number to swap is randomly selected.

If the selected number is on [0,0], then hard-coded would look like:

selected_task = tard_generator1[0,0]
right_swap = tard_generator1[1,1]
tard_generator1[1,1] = selected_task
tard_generator1[0,0] = right_swap

Any suggestions are welcome!

jmar225
  • 3
  • 1
  • 1
    Does this answer your question? [Is there a standardized method to swap two variables in Python?](https://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python) – Grismar May 05 '20 at 04:40

2 Answers2

0

How about something like

chosen = (1, 2)
right_down = chosen[0] + 1, chosen[1] + 1

matrix[chosen], matrix[right_down] = matrix[right_down], matrix[chosen]

will output:

>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
>>> index = (1, 2)
>>> right_down = index[0] + 1, index[1] + 1
>>> a[index], a[right_down] = a[right_down], a[index]
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6, 13,  8,  9],
       [10, 11, 12,  7, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

There should be a boundary check but its omitted

0

Try this:

import numpy as np

def swap_rdi(mat, index):
    row, col = index
    rows, cols = mat.shape
    assert(row + 1 != rows and col + 1 != cols)
    mat[row, col], mat[row+1, col+1] = mat[row+1, col+1], mat[row, col]
    return

Example:

mat = np.matrix([[1,2,3], [4,5,6]])
print('Before:\n{}'.format(mat))
print('After:\n{}'.format(swap_rdi(mat, (0,1))))

Outputs:

Before:
  [[1 2 3]
   [4 5 6]]

After:
  [[1 6 3]
   [4 5 2]]    
LIU
  • 41
  • 6