automate tuple creation
forkit
forkit at gmail.com
Thu Jan 20 04:00:59 UTC 2022
On Thursday, 20 January 2022 at 00:30:44 UTC, H. S. Teoh wrote:
>
> Do the id's have to be unique?
yep...
I'm almost there ;-)
// ---
module test;
import std.stdio : writeln;
import std.range : iota, isForwardRange, hasSlicing, hasLength,
isInfinite;
import std.array : array, Appender;
import std.random : Random, unpredictableSeed, dice, choice;
import std.algorithm : map, uniq;
@safe:
Random rnd;
static this()
{
rnd = Random(unpredictableSeed);
}
void main()
{
int recordsNeeded = 5;
uint[] uniqueIDs;
makeUniqueIDs(uniqueIDs, recordsNeeded);
writeln(uniqueIDs);
uint[][] mArrBool;
// e.g: create a matrix consisting of 5 tuples,
// with each tuple containing 3 random bools (0 or 1)
createBoolMatrix(mArrBool,recordsNeeded, 3);
// process just writeln's it's argument at the moment
process(mArrBool); // [[1, 1, 1], [0, 0, 1], [1, 1, 1], [1,
1, 1], [1, 1, 0]]
// to do (integrate a single value taken from uniqueIDs so
that each tuple looks like this: [999575454:[1, 1, 1]]
// e.g.
// processRecords(records);
// output from above should look like this below:
// [ [999575454:[1, 1, 1]], [999704246:[0, 0, 1]],
[999969331:[1, 1, 1]], [999678591:[1, 1, 1]], [999691754:[1, 1,
0]] ]
}
void createBoolMatrix(ref uint[][] m, size_t numberOfTuples,
size_t numberOfBoolsInTuple)
{
m = iota(numberOfTuples)
.map!(i => iota(numberOfBoolsInTuple)
.map!(numberOfBoolsInTuple => cast(uint)
rnd.dice(0.6, 1.4))
.array).array;
}
void process(T)(const ref T t) if (isForwardRange!T &&
hasSlicing!T && hasLength!T && !isInfinite!T)
{
t.writeln;
}
void processRecords(T)(const ref T t) if (isForwardRange!T &&
hasSlicing!T && hasLength!T && !isInfinite!T)
{
t.writeln;
}
void makeUniqueIDs(ref uint[] arr, size_t sz)
{
// id needs to be 9 digits, and needs to start with 999
int[] a = iota(999_000_000, 1_000_000_000).array; // can
produce a max of 1_000_000 records.
Appender!(uint[]) appndr;
// pre-allocate space to avoid costly reallocations
appndr.reserve(sz+1);
foreach(value; 1..(sz + 1))
appndr ~= cast(uint)a.choice(rnd);
// just interesting to see often this asserts.
//assert(appndr[].array == appndr[].uniq.array);
arr = appndr[].uniq.array;
// function should not return if this asserts (i.e. app will
exit)
assert(arr[].array == arr[].uniq.array);
}
// ---
More information about the Digitalmars-d-learn
mailing list