从列表生成所有随机弯刀,但有一些例外

本文关键字:随机 列表 弯刀 | 更新日期: 2023-09-27 18:00:59

假设我有五个类似的列表

  List<string> A = new List<string> {"A1", "A2", "A3", "A4", "A5"};
  List<string> B = new List<string> {"B1", "B2", "B3", "B4", "B5"};
  List<string> C = new List<string> {"C1", "C2", "C3", "C4", "C5"};
  List<string> D = new List<string> {"D1", "D2", "D3", "D4", "D5"};
  List<string> E = new List<string> {"E1", "E2", "E3", "E4", "E5"};

我想从它们的元素中随机生成所有可能的对,如"A1 E2"、"D4 A2"(A1 E2和E2 A1是不同的匹配项(等。但是这样列表B和C中的元素就永远不会匹配

所以我只是试着做一些类似的事情

  Random X = new Random();
  int rand = X.Next(1, 10); // actual range depends on number of lists
  if (rand == 1)
  Console.WriteLine(A[X.Next(A.Count)] + B[X.Next(B.Count)]) // AB match
  else if (rand == 2)
  Console.WriteLine(A[X.Next(A.Count)] + C[X.Next(C.Count)]) // AC match
  else if (rand == 3)
  Console.WriteLine(A[X.Next(A.Count)] + A[X.Next(A.Count)]) // AA match

等等。不包括BC比赛。如果我有一些清单,它会很好。但是,如果列表的数量越来越高,那么代码就会变得太长和笨拙即使有4个列表,我也需要14个组合来描述(16减去BC和CB(。所以我的问题是-如何使它更短、更高效

问题2——如果我不仅要生成对,还要生成三元组,该怎么办?如"A1 B3 E5"。有例外(B和C(或没有。

从列表生成所有随机弯刀,但有一些例外

解决此问题的一种方法是为第一个项目创建一个所有列表的列表。然后,如果第一个项目是B,则从列表中删除C并随机化第二个项目。

以下是一些示例代码:

List<List<string>> group = new List<List<string>> { A, B, C, D, E };
Random rnd = new Random();
List<string> firstList = group[rnd.Next(group.Count)];
if (firstList == B) group.Remove(C);
else if (firstList == C) group.Remove(B);
List<string> secondList = group[rnd.Next(group.Count)];
Console.WriteLine(firstList[rnd.Next(firstList.Count)] + secondList[rnd.Next(secondList.Count)]);

对于您的第二个问题:您可以通过循环和将项目存储在结果列表中来概括第一个解决方案:

List<List<string>> group = new List<List<string>> { A, B, C, D, E };
Random rnd = new Random();
int count = 3; //for triplets
List<string> result = new List<string>(count);
for (int i = 0; i < count; i++)
{
   List<string> row = group[rnd.Next(group.Count)];
   if (row == B) group.Remove(C);
   else if (row == C) group.Remove(B);
   result.Add(row[rnd.Next(row.Count)]);
}
foreach (string item in result)
{
     Console.Write(item);
}
Console.WriteLine();