automate tuple creation

forkit forkit at gmail.com
Thu Jan 20 21:16:46 UTC 2022


On Thursday, 20 January 2022 at 12:40:09 UTC, Stanislav Blinov 
wrote:
>
> Allocating 4 megs to generate 10 numbers??? You can generate a 
> random number between 999000000 and 1000000000.
>
> ...
>         // 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;
> ...

Nice. Thanks. I had to compromise a little though, as assumUnique 
is @system, and all my code is @safe (and trying to avoid the 
need for inline @system wrapper ;-)

//---

void createUniqueIDArray(ref int[] idArray, int recordsNeeded)
{
     idArray.reserve(recordsNeeded);
     debug { writefln("idArray.capacity is %s", idArray.capacity); 
}

     int i = 0;
     int x;
     while(i != recordsNeeded)
     {
        // generate a random 9 digit id that starts with 999
        x = uniform(999*10^^6, 10^^9); // thanks Stanislav!

        // ensure every id added is unique.
        if (!idArray.canFind(x))
        {
            idArray ~= x; // NOTE: does NOT register with 
-profile=gc
            i++;
        }
     }
}

//---


More information about the Digitalmars-d-learn mailing list