根据指定条件C#从List中选择随机数

时间:2017-12-26 13:02:53

标签: c# arrays random unique

我试图从列表中生成一个唯一的随机数。在这里,用户将输入以下内容:

  1. 所需的随机数
  2. 编号C1,C2和C3项目。
  3. 示例: 10个包含C1-5,C2-4和C3-1的随机数。

    因此,根据这些条件,需要生成随机数列表。

    我的列表看起来像这样

    1   C1
    2   C2
    3   C3
    4   C3
    5   C2
    6   C1
    7   C2
    8   C3
    9   C1
    10  C2
    11  C1
    12  C3
    13  C3
    14  C1
    15  C2
    16  C2
    17  C4
    18  C3
    19  C4
    20  C4
    21  C4
    22  C1
    23  C2
    24  C3
    25  C4
    26  C3
    27  C4
    

    我的代码如下所示:

    protected void BtnGenerate_Click(object sender, EventArgs e)
    {
                List<string> labels; // Holds all Labels (unique)
                List<string> values; // Holds all numbers of labels
                Random r = new Random();
                StringBuilder sb=new StringBuilder(100);
    
                sb.Clear();
                var randoms = values.OrderBy(x => r.Next()).Take(Convert.ToInt16(txtNumberOfRandomNumbers.Text));
                foreach (var item in randoms)
                {
                    sb.Append(item.ToString() + ",");
                }
    
                lblRandomNumbers.Text = sb.ToString().Remove(sb.ToString().LastIndexOf(","));
    }
    

    我坚持如何将这些条件添加到随机函数中。请帮帮我。

2 个答案:

答案 0 :(得分:2)

我建议生成必需的项目,然后改组合并,例如:

// Simplest, but not thread safe
static Random s_Gen = new Random();

private static string Solution(int all, int c1, int c2, int c3) {
  return string.Join(",", new[] {
    Enumerable.Repeat("C1", c1),
    Enumerable.Repeat("C2", c2),
    Enumerable.Repeat("C3", c3),
    Enumerable.Repeat("C4", all - c1 - c2 - c3), }
  .SelectMany(item => item)
  .OrderBy(item => s_Gen.NextDouble()));  
}

protected void BtnGenerate_Click(object sender, EventArgs e) {
  lblRandomNumbers.Text = Solution(27, 10, 5, 3);
}

答案 1 :(得分:-1)

请尝试以下操作:

List<string> input = new string[] { "C1", "C1", "C1", "C1", "C1", "C1", "C2", "C2", "C2", "C2", "C2", "C2", "C2", "C3", "C3", "C3", "C3", "C3", "C3", "C3", "C3", "C4", "C4", "C4", "C4", "C4", "C4" }.ToList();

Random rand = new Random();

List<string> output = input.Select(x => new { number = x, rand = rand.Next() }).OrderBy(x => x.rand).Select(x => x.number).ToList();