How to generate a random number from system clock as seed
drug007
drug2004 at bk.ru
Sat Jun 8 18:25:20 UTC 2024
On 08.06.2024 16:19, Eric P626 wrote:
> I managed to create a random number generator using the following code:
>
> ~~~
> auto rng = Random(42);
> //....
> uniform(0,10,rng);
> ~~~
>
> Now I want to seed the generator using system time. I looked at Date &
> time functions/classes and systime functions/classes. The problem is
> that they all require a time zone. But I don't need a time zone since
> there is no time zone. I just want the number of seconds elapsed since
> jan 1st 1970. In other words, the internal system clock value.
>
```d
import std;
void main()
{
{
auto rng = Random(42);
auto result = generate!(() => uniform(0, 10, rng))().take(7);
// the same random numbers sequence
assert (result.equal([2, 7, 6, 4, 6, 5, 0]));
}
{
const seed = castFrom!long.to!uint(Clock.currStdTime);
auto rng = Random(seed);
auto result = generate!(() => uniform(0, 10, rng))().take(7);
// new random numbers sequence every time
result.writeln;
}
}
```
More information about the Digitalmars-d-learn
mailing list