automate tuple creation

Stanislav Blinov stanislav.blinov at gmail.com
Thu Jan 20 12:40:09 UTC 2022


On Thursday, 20 January 2022 at 12:15:56 UTC, forkit wrote:

> void createUniqueIDArray(ref int[] idArray, int recordsNeeded)
> {
>     idArray.reserve(recordsNeeded);
>     debug { writefln("idArray.capacity is %s", 
> idArray.capacity); }
>
>     // id needs to be 9 digits, and needs to start with 999
>     // below will contain 1_000_000 records that we can choose 
> from.
>     int[] ids = iota(999_000_000, 1_000_000_000).array; // 
> NOTE: does NOT register with -profile=gc
>
>     int i = 0;
>     int x;
>     while(i != recordsNeeded)
>     {
>        x = ids.choice(rnd);
>
>        // ensure every id added is unique.
>        if (!idArray.canFind(x))
>        {
>            idArray ~= x; // NOTE: does NOT register with 
> -profile=gc
>            i++;
>        }
>     }
> }

Allocating 4 megs to generate 10 numbers??? You can generate a 
random number between 999000000 and 1000000000.

```
immutable(int)[] createUniqueIDArray(int recordsNeeded)
{
     import std.random;
     import std.algorithm.searching : canFind;
     int[] result = new int[recordsNeeded];

     int i = 0;
     int x;
     while(i != recordsNeeded)
     {
         // id needs to be 9 digits, and needs to start with 999
        x = uniform(999*10^^6, 10^^9);

        // ensure every id added is unique.
        if (!result[0 .. i].canFind(x))
            result[i++] = x;
     }
     import std.exception : assumeUnique;
     return result.assumeUnique;
}

void main()
{
     import std.stdio;
     createUniqueIDArray(10).writeln;
}
```

Only one allocation, and it would be tracked with -profile=gc...


More information about the Digitalmars-d-learn mailing list