问题描述
我在努力奋斗着这个算法我需要写。我使用C#。
I'm struggling with this algorithm I need to write. I'm using C#.
说我有一个名单,其中,袋>
和我有一个名单,其中,午餐>
。我需要写一个算法,将枚举午餐的所有排列在所有的包装袋。
Say I have a List<Bag>
and I have a List<Lunch>
.I need to write an algorithm which will enumerate all permutations of lunches in all bags.
举例来说,假设有3个午餐,2袋:
For example, say there are 3 lunches and 2 bags:
// Permutation 1
Bag 1, Lunch 1
Bag 2, Lunch 1
// Permutation 2
Bag 1, Lunch 1
Bag 2, Lunch 2
// Permutation 3
Bag 1, Lunch 1
Bag 2, Lunch 3
// Permutation 4
Bag 1, Lunch 2
Bag 2, Lunch 1
// Permutation 5
Bag 1, Lunch 2
Bag 2, Lunch 2
// Permutation 6
Bag 1, Lunch 2
Bag 2, Lunch 3
// Permutation 7
Bag 1, Lunch 3
Bag 2, Lunch 1
// Permutation 8
Bag 1, Lunch 3
Bag 2, Lunch 2
// Permutation 9
Bag 1, Lunch 3
Bag 2, Lunch 3
这两个排列袋1午餐1和包2午餐2
和袋1午餐2袋2午餐1
是不同的,因为包包有不同的容量,因此他们都需要加以列举。
The two permutations Bag 1 Lunch 1 and Bag 2 Lunch 2
and Bag 1 Lunch 2 and Bag 2 Lunch 1
are different because the bags have different capacities, hence they would both need to be enumerated.
的袋和午餐的数量可以是任何数量。
The number of bags and lunches can be any number.
我已经创建了一个名为 BagLunch
,其中包含一个包和午餐对。我在上面已经给出的例子清单将被存储在一个名单,其中,BagLunch&GT;
I have created a class called BagLunch
which contains a bag and lunch pair. The example list I've given above would be stored in a List<BagLunch>
.
感谢你。
推荐答案
使用交叉联接在LINQ:
Use a cross join in LINQ:
var qry = from bag in bags
from lunch in lunches
select new BagLunch
{ Bag=bag, Lunch=lunch};
var baglunches = qry.ToList();
编辑:
你要修改的SELECT子句来处理你的 BagLunch
类的结构。
You'll want to modify the select clause to handle the structure of your BagLunch
class.
这篇关于在C#中置换算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!