[Issue 7128] Cartesian product of ranges

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Feb 8 04:26:23 PST 2013


http://d.puremagic.com/issues/show_bug.cgi?id=7128



--- Comment #15 from bearophile_hugs at eml.cc 2013-02-08 04:26:20 PST ---
(In reply to comment #14)
> The power must be a compile-time parameter, otherwise it won't compile.

I think it's possible to create a range like this:

auto cartesianPower(R)(R range, in size_t n) { ... }


If you call it with:
int n = 3;
auto result = cartesianPower([0, 1], n).array();


result should be:

[[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1],
[1, 1, 1]]



One use case: generate dstrings (dchar[][]) for a "Bulls and Cows" game, where
they need to be composed of N distinct nonzero digits:


dchar[][] genCases(in size_t nDigits) {
  return cartesianPower("123456789"d.dup, nDigits)
         .filter!(a => a.sort().uniq().walkLength() == nDigits)()
         .array();
}


So genCases(4).writeln() should print:

["4321", "5321", "6321", "7321", "8321", "9321", "3421",
"5421", "6421", "7421", "8421", "9421", "3521", "4521",
"6521", "7521", "8521", "9521", "3621", "4621", "5621",
"7621", "8621", "9621", "3721", "4721", "5721", "6721",
"8721", "9721", "3821", "4821", "5821", "6821", "7821",
"9821", "3921", "4921", "5921", ...]

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list