0

I am experimenting with different array sizes and elements. For simplicity I'm taking an array of size: 3x3. In a form of 2D list as follows:

input_matrix = [[80,81,84],[69,80,51],[13,37,65]]

So, what might be a best way to do it? If I use nested loops, that would be an overkill to such simple task with O(n^2) complexity which I want to avoid.

EDIT 1:

By Sum maximization I meant that I can swap elements within the array and for each arrangement in first row there would be a different sum. So how many swaps do I need to get that arrangement for which the sum of the rows is maximum of all the possible sums that can be achieved by putting elements from whole array into the first row

  • what do you mean by maximize sum? – Aleka Sep 19 '20 at 18:14
  • Means I can swap elements and for each arrangement there would be a different sum. So how many swaps do I need to get that arrangement for which the sum of the rows is maximum of all the possible sums that can be achieved by putting elements from whole array into the first row –  Sep 19 '20 at 18:17

1 Answers1

1

If you can swap only across columns:

By row maximization I assumed you meant you can swap vertically in an array to make a row maximum. In that case it can be done via numpy as follows:

(np.argmax(np.array(input_matrix), axis = 0)!=r).sum()

Trick here is to find the maximum element of each column and then if its not in the required row (i.e. r) then count it as a swap because thats where you need to swap and sum it.

If you can swap any element from the array:

In case where you can take values from whole array you need a more complex mechanism as follows:

def largest_indices(ary, n):
    """Returns the n largest indices from a numpy array."""
    flat = ary.flatten()
    indices = np.argpartition(flat, -n)[-n:]
    indices = indices[np.argsort(-flat[indices])]
    return np.unravel_index(indices, ary.shape)

(largest_indices(np.array(input_matrix), len(input_matrix[0]))[0]!=r).sum()

It goes on to find n maximum elements across the array, finds their indices and if they are not in the required row, it counts them as swaps and return total number of swaps. Function credit goes to this answer.

Hamza
  • 5,373
  • 3
  • 28
  • 43