我正在尝试创建具有唯一随机数的二叉搜索树。我使用 SortedSet 来表示我的树,然后将其放入数组中,然后使用 Contains 来查看树中是否存在某个数字。我的问题是我无法弄清楚如何以简单的方式获得所有不同的随机数。我使用了 Unik 和 Nålen_Unik 方法,但在这段代码中,它只为数组生成 1 个数字
Random random = new Random();
Program Tal = new Program();
string nål = Tal.Nålen_Unik();
string TalIArray = Tal.Unik();
bool found = false;
SortedSet<string> Tree = new SortedSet<string>();
for (int x = 0; x < 50000; x++)
{
Tree.Add(TalIArray);
}
int y = 0;
string[] TreeArray = Tree.ToArray<string>();
while (y < TreeArray.Length)
{
Console.WriteLine(TreeArray[y]);
y = y + 1;
}
private string Unik()
{
int maxSize = 4;
char[] chars = new char[10000];
string a;
a = "0123456789";
chars = a.ToCharArray();
int size = maxSize;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
size = maxSize;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length - 1)]);
}
return result.ToString();
}
private string Nålen_Unik()
{
int maxSize = 1;
char[] chars = new char[62];
string a;
a = "0123456789";
chars = a.ToCharArray();
int size = maxSize;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
size = maxSize;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length - 1)]);
}
return result.ToString();