1

如题。

例如,我有一个包含 10 个项目的列表。

Id    Name   GroupId
1     abc     123
2     abc1    124
3     abc2    125
4     abc3    126
5     abc4    123
6     abc5    123
7     abc6    124
8     abc7    125
9     abc8    127
10    abc9    124

Var groups = items.OrderBy(m => m.GroupId).GroupBy(o => o.GroupId);

然后我有5组。

组 1 (123):{1、5、6}

组 2 (124):{2、7、10}

组 3 (125): {3, 8}

第 4 组 (126):{4}

第 5 组 (127):{9}

现在,我想根据新组的最大数量重新组合它们。

例如:如果 maxQuantity = 4

newGroup1: {1,5,6,4}(4 是因为 group2 和 group3 不能在 newGroup1 中分组)“他们有超过 1 个项目,newGroup1 只能插入 1 个项目。”

newGroup2:{2,7,10,9}(与 newGroup1 解释相同)

newGroup3: {3,8} (只剩下 2 个项目,然后他们必须组合在一起。)

对编码有任何想法吗?我在坐在椅子上浪费了 8 个小时来思考这个问题并且还在数数。

*另一种情况,如果 maxQuantity = 2

newGroup1: {1, 5}
newGroup2: {6, 4}
newGroup3: {2, 7}
newGroup4: {10, 9}
newGroup5: {3, 8}

解释同上例

4

1 回答 1

0

基本思路:

  • 按数量对组进行排序。
  • 从双方迭代,组合加起来不超过最大数量的组。

伪代码:

sort groups by quantity (biggest group first)
i = 0
j = groups.size-1

while i <= j
  // if the indices met, pick either
  // if the two groups are larger than max quantity, simply pick the larger one
  if i == j || union(groups[i], groups[j]).size > maxQuantity
    output groups[i]
    i++
  else
    output union(groups[i], groups[j])
    i++
    j--

如果元素是唯一的:

union(groups[i], groups[j]).size = groups[i].size + groups[j].size

林克?

这很可能超出了 LINQ 的能力。至于 C# 代码,它应该足够简单,可以从伪代码中派生出来。

于 2013-08-30T06:44:35.407 回答