随机填充列表,其中包含四个不同的数字

5
我有一个列表(randomRotationVoidList),需要填入四个不同的数字(90, 180, 270, 360),以随机顺序,例如[270, 180, 180, 90, ...]。目前我所找到的都只能生成在特定范围内的随机数列表。

提前致谢!


https://dev59.com/EnVC5IYBdhLWcg3wfxU8 - jspcal
@jspcal项可能会在此处多次出现 [270,180,180,90,...] 例如 180 - fubo
请查看此链接:https://dev59.com/HGMm5IYBdhLWcg3wivj7 - PM.
从源列表中随机选择索引并删除。 - Icepickle
var rnd = new Random(); randomRotationVoidList = randomRotationVoidList.OrderBy(x => rnd.Next()).ToList() - 最好将 rnd 定义为类级字段,以避免可能的重复值问题。 - Enigmativity
可能是随机排序List<T>的重复问题。 - FoggyFinder
1个回答

9

200个数字的示例

Random _rnd = new Random();
int[] input = { 90, 180, 270, 360 }; // dictionary of available numbers
List<int> result = Enumerable.Range(0, 200).Select(x => input[_rnd.Next(0, input.Length)]).ToList();

如果数字模式固定为x * 90,则另一种方法是:

Random _rnd = new Random();
List<int> result = Enumerable.Range(0, 200).Select(x => 90 * _rnd.Next(1, 5)).ToList();

我会称第二种方法为“更通用”。 - Enigmativity
3
@Enigmativity 不是那样的.. 它是硬编码和计算,所以它不太通用。结果将是 int,而第一个可以得到数组中的任何类型。 - Brett Caswell
我的观点是它不使用硬编码数组。它更通用,因为它使用公式而不是特定的数组。 - Enigmativity
好的,如果你担心越界问题,那么它不会发生。但是请考虑同样的示例代码,但使用不同的数组类型:string[] input = { "90", "180", "270", "360" }。我们指的是 Type 泛型。 - Brett Caswell
1
同样地,public static IEnumerable<T> GetRandomList<T>(Func<T> dictinary, int entries) - Enigmativity
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接