简体   繁体   English

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

[英]Pick random numbers from List based on specified condition C#

I'm trying to generate a unique random numbers from the list. 我正在尝试从列表中生成唯一的随机数。 Here user will input the followings: 用户在这里输入以下内容:

  1. Number of random numbers required 所需的随机数
  2. Number C1, C2 and C3 items. 编号C1,C2和C3项目。

Example: 10 Random numbers with C1-5, C2-4, and C3-1. 示例:带有C1-5,C2-4和C3-1的10个随机数。

So based on these conditions a random number list need to generate. 因此,根据这些条件,需要生成一个随机数列表。

My list looks like this 我的清单看起来像这样

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

My code looks like this: 我的代码如下所示:

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(","));
}

I'm stuck with how to add these conditions to Random function. 我对如何将这些条件添加到“随机”函数感到困惑。 Please help me on this. 请帮我。

I suggest generating required items and then shuffling the colelction, eg: 我建议生成所需的项目,然后洗牌 colelction,如:

// 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);
}

Try following : 尝试以下操作:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM