生成一组随机整数,其和落在一个范围内
本文关键字:一个 范围内 整数 一组 随机 | 更新日期: 2023-09-27 18:12:02
我有一个列表"VisitScores",在这个例子中需要包含4个随机整数分数,4个分数的总和落在"min"answers"max"之间,为了生成一个分数,我必须从"valueNumbers"中取3个随机整数,所以选择19,15,21会给我一个55的分数,我知道如何生成随机的单个分数,但要解决剩下的问题让我很头疼
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
--------------------------- 我的LINQ的解决方案 ----------------------
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();
我想只是选择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]);
}