automate tuple creation

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Jan 19 22:24:34 UTC 2022


On Wed, Jan 19, 2022 at 09:59:15PM +0000, forkit via Digitalmars-d-learn wrote:
> so I have this code below, that creates an array of tuples.
> 
> but instead of hardcoding 5 tuples (or hardcoding any amount of
> tuples), what I really want to do is automate the creation of
> how-ever-many tuples I ask for:
> 
> i.e.
> 
> instead of calling this: createBoolMatrix(mArrBool);
> I would call something like this: createBoolMatrix(mArrBool,5); //
> create an array of 5 typles.

Why can't you just use a loop to initialize it?

	uint[][] createBoolMatrix(size_t n) {
		auto result = new uint[][n]; // allocate outer array
		foreach (ref row; result) {
			row = new uint[n]; // allocate inner array
			foreach (ref cell; row) {
				cell = cast(uint) rnd.dice(0.6, 1.4);
			}
		}
		return result;
	}

Or, if you wanna use those new-fangled range-based idioms:

	uint[][] createBoolMatrix(size_t n) {
		return iota(n)
			.map!(i => iota(n)
				.map!(j => cast(uint) rnd.dice(0.6, 1.4))
				.array)
			.array;
	}


T

-- 
Verbing weirds language. -- Calvin (& Hobbes)


More information about the Digitalmars-d-learn mailing list