automate tuple creation

forkit forkit at gmail.com
Sat Jan 22 07:19:29 UTC 2022


On Saturday, 22 January 2022 at 01:33:16 UTC, Steven 
Schveighoffer wrote:
>

so I why watching this video by Andrei:

https://www.youtube.com/watch?v=mCrVYYlFTrA

In it, he talked about writing the simplest design that could 
possibly work....

Which got me thinking....

// ----

module test;
@safe:

import std.stdio : write, writef, writeln, writefln;
import std.range : iota, enumerate;
import std.array : array, byPair, Appender, appender;
import std.random : Random, unpredictableSeed, dice, randomCover;
import std.algorithm : map;
import std.conv : to;
import std.format;
import std.stdio : File;
import std.file : exists;
import std.exception : enforce;
import std.meta : Alias;

debug { import std; }

Random rnd;
static this() {  rnd = Random(unpredictableSeed); }

void main(string[] args)
{
     int recordsNeeded, valuesPerRecord;

     string fname;

     if(args.length < 4) // then set defaults
     {
         recordsNeeded = 10;
         valuesPerRecord= 8;

         version(Windows) { fname = "D:/rnd_records.txt"; }
         version(linux) { fname = "./rnd_records.txt"; }
     }
     else
     {
         // assumes valid values being passed in ;-)
         recordsNeeded = to!int(args[1]);
         valuesPerRecord = to!int(args[2]);
         fname = args[3];
     }

     debug
         { writefln("%s records (where a record is: id and %s 
values), will be written to file: %s", recordsNeeded, 
valuesPerRecord, fname); }
     else
         {
             enforce(!exists(fname), "Oops! That file already 
exists!");
             enforce(recordsNeeded <= 1_000_000_000, "C'mon! 
That's too many records!");
         }

     CreateDataFile(recordsNeeded, valuesPerRecord, fname);

     writefln("All done. Check if records written to %s", fname);
}

void CreateDataFile(const(int) recordsNeeded, const(int) 
valuesPerRecord, const(string) fname)
{
     auto file = File(fname, "w");
     scope(exit) file.close;

     Appender!string bigString = appender!string;
     bigString.reserve(recordsNeeded);

     const int iotaStartNum = 100_000_001;

     foreach(i, id; iota(iotaStartNum, iotaStartNum + 
recordsNeeded).enumerate)
     {
         bigString
             ~= id.to!string
             ~ ","
             ~ valuesPerRecord.iota.map!(valuesPerRecord => 
cast(int)rnd.dice(0.6, 1.4)).format!"%(%s,%)"
             ~ "\n";
     }

     file.write(bigString[]);
}

// ----


More information about the Digitalmars-d-learn mailing list