【发布时间】:2015-12-18 20:45:42
【问题描述】:
如何将数字添加到数组中,以使每个新数字都是随机且不重复的?
试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
const int NUM_ROWS = 5;
const int NUM_COLS = 7;
static void Main(string[] args)
{
List<List<int>> matrix = new List<List<int>>();
RandInt randNumbers = new RandInt(NUM_ROWS * NUM_COLS);
int count = 0;
for (int row = 0; row < NUM_ROWS; row++)
{
List<int> newRow = new List<int>();
matrix.Add(newRow);
for (int col = 0; col < NUM_COLS; col++)
{
newRow.Add(RandInt.numbers[count++].number);
}
}
}
public class RandInt
{
public static List<RandInt> numbers = new List<RandInt>();
public int number { get; set; }
public int rand { get; set; }
public RandInt() { }
public RandInt(int SIZE)
{
Random r = new Random();
for (int i = 0; i < SIZE; i++)
{
numbers.Add(new RandInt() { number = i, rand = r.Next()});
}
numbers = numbers.OrderBy(x => x.rand).ToList();
}
}
}
}
【问题讨论】:
-
...问题是?...
-
你的意思肯定不是The Matrix?
-
要获得非重复数字,请创建一个 1 到 100 的数组。然后随机化该数组。最简单的方法是创建一个包含两个对象的类 1) int number 2) int randNumber。添加第二个对象的随机数,然后按随机数随机化类。第一个对象编号将随机化。
-
随机 r = new Random(); int number = rnd.Next(1, 100); // 创建一个介于 1 和 100 之间的数字
-
帖子的第一行看起来不错。现在请添加您尝试过的内容以及您在实现代码时遇到的问题。您还可以考虑使用您选择的搜索引擎来查找类似的帖子。 IE。 bing.com/search?q=C%23+unique+random+array(到目前为止,帖子中显示的大量研究和努力可能会招来反对票)
标签: c#