Generate array of random values

bearophile bearophileHUGS at lycos.com
Sat Jul 30 08:54:52 PDT 2011


Andrej Mitrovic:

> void main()
> {
>     auto arr2 = array(map!( (int){ return uniform(0, 1024); })(iota(0, 1024)));
> }
> 
> Is there a simpler way to do get an array of random values?

If you want a single expression you are allowed to write a bit shorter code:
auto arr2 = array(map!((int){ return uniform(0, 1024); })(iota(1024)));

Once we get amap/afilter added to Phobos (http://d.puremagic.com/issues/show_bug.cgi?id=5756 ) the code gets a bit simpler:
auto arr2 = amap!((int){ return uniform(0, 1024); })(iota(1024));
amap/afilter are not orthogonal, but this is acceptable for practicality (and done in all the languages I know), because in D arrays are much more commonly useful than lazy ranges.

I have also proposed a N dimensional table() function to be added to Phobos. With it the code gets simple (Mathematica has a similar function):
auto arr2 = table!q{ uniform(0, 1024) }(1024);

In Python3 you use a list (array) comp:
lst = [randrange(1024) for _ in range(1024)]

Unfortunately often the "simpler way" in D is to use an imperative programming style.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list