简体   繁体   English

最大化二维数组第 n 行的总和所需的最小交换?

[英]Minimum swaps needed to maximize sum of nth row of a 2D array?

I am experimenting with different array sizes and elements.我正在试验不同的数组大小和元素。 For simplicity I'm taking an array of size: 3x3.为简单起见,我采用了大小为 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.如果我使用嵌套循环,那么对于我想要避免的 O(n^2) 复杂性的简单任务来说,这将是一种矫枉过正。

EDIT 1:编辑 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那么我需要多少次交换才能得到这样的安排,即行的总和是通过将整个数组中的元素放入第一行可以实现的所有可能总和的最大值

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:在这种情况下,它可以通过 numpy 完成,如下所示:

(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 (ie r) then count it as a swap because thats where you need to swap and sum it.这里的技巧是找到每列的最大元素,然后如果它不在所需的行(即 r)中,则将其视为交换,因为那是您需要交换和求和的地方。

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.它继续在数组中找到n最大元素,找到它们的索引,如果它们不在所需的行中,则将它们计为交换并返回交换的总数。 Function credit goes to this answer .功能功劳归于这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM