随机化整数数组

编程入门 行业动态 更新时间:2024-10-28 15:29:07
本文介绍了随机化整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

您能帮我找到一种方法,随机数组?例如:

Can you help me to find a way to randomize arrays? E.g.:

int[] arrayInt = { 1, 2, 3, 4, 5, 6, 7 };

随机后,结果应该被存储在另一个阵列

after randomizing, the result should be stored in another array.

当你再次随机它应该与存储在第二数组中的值进行比较,如果该值存在程序必须重新随机。

And when you randomize again it should be compared with the values stored in the second array, if that value exist the program must randomize again.

推荐答案

下面是使用方法的 Enumerable.OrderBy 以输入阵列具有的随机变量。生成新的序列后,它会与 SequenceEqual :

Here's an approach using Enumerable.OrderBy to order the input-array with a random variable. After the new sequence is generated it'll be compared with the input array with SequenceEqual:

public static T[] UniqueRandomArray<T>(T[] input, Random rnd) { if (input.Length <= 1) throw new ArgumentException("Input array must have at least two elements, otherwise the output would be the same.", "input"); IEnumerable<T> rndSeq; while (input.SequenceEqual(rndSeq = input.OrderBy(x => rnd.Next()))); return rndSeq.ToArray(); }

此例 - code产生一个​​被添加到列表10新阵列。它确保了新阵列对previous 1不同:

This example-code generates 10 new arrays which are added to a List. It is ensured that the new array is different to the previous one:

Random rnd = new Random(); List<int[]> randomArrays = new List<int[]>(); int[] arrayInt1 = { 1, 2, 3, 4, 5, 6, 7 }; randomArrays.Add(arrayInt1); for (int i = 0; i < 10; i++) { int[] lastArray = randomArrays[randomArrays.Count - 1]; int[] randomArray = UniqueRandomArray(lastArray, rnd); randomArrays.Add(randomArray); }

演示

更多推荐

随机化整数数组

本文发布于:2023-11-30 11:16:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649782.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   数组   随机化

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!