【问题标题】:Need to get all combinations of several lists, taking sets amounts from each list需要获取多个列表的所有组合,从每个列表中获取集合数量
【发布时间】:2014-11-12 04:11:59
【问题描述】:
class Employee
{
    int id;
    Position position;
}

class Position
{
    string name;
}

public List<List<Tuple<Position, Employee>>> getAllCombinations(Dictionary<Position, int> positionToCountMap, List<Employee> allEmployees)
{
}

positionToCountMap to 会是这样的:{"Manager", 1}, {"Developer", "3"}, {"PM", "1"}(不知道有多少键)

我需要返回 allEmployees 的所有可能组合的列表,以满足 positionToCountMap 中的计数要求。我需要 1 名经理、3 名开发人员和 1 名 PM 的组合。我的第一步是为具有该职位的员工列表创建一个新的职位字典。

var positionToEmployeeMap = new Dictionary<Position, List<Employee>>()
//Loop through allEmployees adding each to this dictionary

现在问题变成了我有几个列表,我需要从每个列表中找到所有可能的组合,其中包含 positionToCountMap 中指定的数量。

这是解决问题的好方法吗?即使是这样,我也无法理解我将如何实际暴力破解。我最初试图考虑一些递归解决方案,但列表的大小可能足够大,递归可能不是一个很好的选择。我被困住了,可以使用一些建议。

编辑认为我有一个解决方案,虽然它不是很好,但我仍然很想得到一些建议。

var positionToEmployeeMap = new Dictionary<Position, List<Employee>>()
//Loop through allEmployees adding each to this dictionary

var relevantLists = new List<Employee>();
//for each key in positionToCountMap, find the list in positionToEmployeeMap and add it to relevantLists

var allCombos = new List<List<Employee>>();
//Loop through relevantLists. For each list, recursively generate all possible combinations of sublists of size N, where N is the number in positionToCountMap. Add a list of all the combinations to allCombos

//recursively loop through allCombos finding all possible combinations taking 1 element from each list

【问题讨论】:

    标签: c# algorithm list


    【解决方案1】:

    我会使用 LINQ。您可以使用以下内容执行类似于 SQL CROSS JOIN 操作的操作:

    var ListA = new List<object>();
    var ListB = new List<object>();
    var ListC = new List<object>();
    
    var result = (from a in listA
      from b in listB
      from c in listC
      select new { a, b, c }).ToList();
    

    这将生成一个列表,其中包括 ListA、ListB 和 ListC 中值的所有组合。

    【讨论】:

    • 问题在于它需要的不仅仅是每个列表中的一个。就像上面 OP 中的示例一样,我需要列表 A 中的一项,列表 B 中的三项和列表 C 中的一项。
    • 另外,不知道字典中有多少键,所以我不能假设它只有 3 个列表。
    猜你喜欢
    • 1970-01-01
    • 2023-01-09
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多