Главная
>>
Каталог задач
>>
Числа
>>
Случайные числа
>>
Простой генератор случайных чисел
Простой генератор случайных чисел
реализации: C#, количество: 2
Aвтор: this
Дата: 11.02.2004
Просмотров: 119930
Рейтинг:
3/7,4.85(4043)
+
реализации(исходники)
+добавить
Задача генерации множества случайных чисел возникает как правило в задачах на различные тесты, бенчмарки и проч.
Здесь рассмотрим самый простой случай - генерация массива случайных чисел по принципу: "сгенерировать такое-то количество случайных чисел в интервале от и до".
Реализации:
C#(2),
C++(2),
python(1)
+добавить реализацию
1)
RandomGenerator.cs, code #62[автор:this]
using System;
using System.Collections.Generic;
using System.Text;
class RandomGenerator
{
private Random gen;
private int num = 0;
private int[] cache;
public RandomGenerator(int Num)
{
this.gen = new Random(unchecked((int)DateTime.Now.Ticks));
this.num = Num;
this.cache = new int[Num];
}
public int[] Get(int left, int right)
{
for (int i = 0; i < this.num; i++)
{
this.cache[i] = this.gen.Next(left, right);
}
return this.cache;
}
}
2)
Простой генератор случайных чисел и паролей, code #659[аноним:olmovc]
using System;
using System.Security.Cryptography;
namespace GenPassword
{
class Program
{
public static void Main(string[] args)
{
int len = 15;
Console.WriteLine("Password Length:{0}\nRandom Password:{1}",len,GetPassword(len));
Console.WriteLine("RamdomInt Length:{0}\nRandom Int:",len);
foreach (int i in GetRandomInt(len))
Console.Write(i);
Console.Write("\n\nPress any key to continue . . . ");
Console.ReadKey(true);
}
public static string GetPassword(int passwordlen)
{
string password = string.Empty;
if ((passwordlen < 1)||(passwordlen>18))
passwordlen = 8;
byte[] randombyte = new Byte[1];
int count = 0;
RNGCryptoServiceProvider rng;
char ch = '\0';
while (count < passwordlen)
{
//RNGCryptoServiceProvider is an implementation of a random number generator.
rng = new RNGCryptoServiceProvider();
rng.GetBytes(randombyte); // The array is now filled with cryptographically strong random bytes.
ch = Convert.ToChar(randombyte[0]);
if ((ch > '!')&&(ch <= '~'))
{
password += ch.ToString();
count++;
}
}
return password;
}
public static int[] GetRandomInt(int intlen)
{
if ((intlen < 1)||(intlen>18))
intlen = 8;
int[] randomInt = new Int32[intlen];
byte[] randombyte = new Byte[1];
int count = 0;
RNGCryptoServiceProvider rng;
char ch = '\0';
int tempint = 0;
while (count < intlen)
{
//RNGCryptoServiceProvider is an implementation of a random number generator.
rng = new RNGCryptoServiceProvider();
rng.GetBytes(randombyte); // The array is now filled with cryptographically strong random bytes.
ch = Convert.ToChar(randombyte[0]);
if ((ch >= '0')&&(ch <= '9'))
{
if (Int32.TryParse(ch.ToString(),out tempint))
{
randomInt[count] = tempint;
count++;
}
}
}
return randomInt;
}
}
}