Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// "Each with each other" random range
- module eerange.randomrange;
- import std.traits;
- import std.stdio; //FIXME: remove
- @safe:
- //@nogc: //FIXME: enable
- ///
- struct EachWithEachOtherRandomAccessRange(R)
- {
- private R srcRange;
- const size_t squareWidth;
- ///
- this(R r)
- {
- srcRange = r;
- squareWidth = srcRange.length + 1;
- }
- ///
- size_t length() const
- {
- const len = srcRange.length;
- return (len * len - len) / 2;
- }
- private static struct Coords
- {
- size_t x;
- size_t y;
- }
- private Coords coordsInSquare(size_t idx)
- {
- Coords ret;
- ret.x = idx % squareWidth;
- ret.y = idx / squareWidth;
- return ret;
- }
- private auto getElemBySquareCoords(Coords c)
- {
- // elements shifted relative to entire square
- c.x -= 1; // elements shifted relative to entire square
- //~ c.y -= 1; // elements shifted relative to entire square
- writeln(c);
- return [srcRange[c.x], srcRange[c.y]]; // TODO: replace by static array?
- }
- ///
- auto opIndex(const size_t idx)
- {
- assert(idx < length);
- Coords coords = coordsInSquare(idx);
- if(coords.x <= coords.y) // under diagonal line?
- {
- const latestIdx = srcRange.length;
- // Mirroring coords
- coords.x = latestIdx - coords.x;
- coords.y = latestIdx - coords.y - 1; // shifted above diagonal
- }
- return getElemBySquareCoords(coords);
- }
- }
- ///
- auto eeRandomRange(T)(T inputRange)
- {
- return EachWithEachOtherRandomAccessRange!(T)(inputRange);
- }
- unittest
- {
- import std.range.primitives;
- //~ static assert(isRandomAccessRange!(EachWithEachOtherRandomAccessRange!(int[])));
- }
- unittest
- {
- import std.parallelism;
- import std.algorithm.searching: count;
- int[] arr = [0, 1, 2, 3];
- auto r = arr.eeRandomRange;
- size_t cnt;
- foreach(i; 0 .. r.length)
- {
- writeln("i=", i);
- auto unused = r[i];
- cnt++;
- }
- //~ auto mapped = taskPool.amap!((a){ return a; } )(r);
- assert(cnt == 6);
- assert(arr.eeRandomRange.length == 6);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement