LINQ - 生成一组随机整数,其总和落在一个范围内

时间:2014-07-09 10:57:52

标签: c# linq

我有一个List" VisitScores"在这个例子中,它需要包含4个随机整数分数,其中4个分数的总和落在" min"为了生成单个分数,我必须从" valueNumbers"中取3个随机整数,所以选择19,15,21会得到55分,I知道如何生成随机单一分数,但解决其余问题让我头疼

        var visitScores = new List<int>();
        var valueNumbers = new List<int>() { 5, 20, 1, 7, 19, 3, 15, 60, 21, 57, 9 };
        var totalVisits = 4;
        var min = 241;
        var max = 261;

        var r = new Random();
        var randomScore = (from int value1 in valueNumbers
                           from int value2 in valueNumbers
                           from int value3 in valueNumbers
                           select (value1 + value2 + value3)).OrderBy(z => r.NextDouble()).First();

我的预期结果是visitScores包含一组4个随机分数,100(60,19,21),44(20,19,5),73(57,9,7),40(20,15, 5)总共257

--------------------------- MY LINQ SOLUTION ----------------- -----

        var randomScores = (from int value1 in valueNumbers
                           from int value2 in valueNumbers
                           from int value3 in valueNumbers
                           select (value1 + value2 + value3)).Distinct().OrderBy(z => r.NextDouble()).ToList();

        var scores = (from int score1 in randomScores
                            from int score2 in randomScores
                            from int score3 in randomScores
                            from int score4 in randomScores
                      where ((score1 + score2 + score3 + score4) > min) && ((score1 + score2 + score3 + score4) < max) &&
                                  new int[] { score1, score2, score3, score4 }
                                  .Distinct().Count() == 4
                      select new List<int>() { score1, score2, score3, score4 }).Distinct().First();

1 个答案:

答案 0 :(得分:1)

我想只选择12个随机数,直到它们的总和落在范围内,然后将它们分成3组。我认为这应该有效。不过,我正努力将其纳入linq声明中。

    int totalNumbers = totalVisits * 3;
    int[] selection = new int[totalNumbers];
    int sum;
    do {
        sum = 0;
        for (int i = 0; i < totalNumbers; ++i) {
            sum += selection[i] = valueNumbers[r.Next(valueNumbers.Length)];
        }
    } while (sum < min || sum > max);
    for (int j = 0; j < selection.Length; j+=3) {
        visitScores.Add(selection[j] + selection[j+1] + selection[j+2]);
    }