Generate random combinations from large set in GAP

combinatoricsgap

I need to generate random combinations (unordered tuples without duplication).
This code works fine for relatively small $n$ but I need much larger n $n>200$ for example

n:=20; # fails for n=200
enum:=EnumeratorOfCombinations([1..n]);
for k in [1..10] do
 b:=enum[Random([1..2^n])];
 Print(b,"\n");
od;

# result :
[ 1, 2, 3, 5, 9, 11, 14, 15, 17, 18, 20 ]
[ 1, 5, 6, 7, 9, 11, 12, 14, 17, 18 ]
[ 2, 4, 5, 6, 10, 13, 14, 18, 19 ]
[ 2, 7, 9, 10, 11, 12, 14, 17, 18 ]
[ 3, 9, 10, 11, 13, 14, 15, 17, 18 ]
[ 3, 5, 7, 8, 9, 11, 14, 17, 18, 19, 20 ]
[ 1, 2, 3, 6, 7, 10, 15, 16, 19 ]
[ 1, 2, 4, 7, 8, 10, 12, 13, 17, 19, 20 ]
[ 1, 2, 3, 7, 8, 13, 14, 17 ]
[ 2, 3, 4, 6, 8, 16, 17, 18, 19 ]

Are there other options for doing this in GAP?

Best Answer

Do you really want to produce random combinations of any size (instead of some fixed size)? So, if for example $n=3$, you want to pick uniformly at random from the 8 combinations [], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]? That's an incredibly convoluted way of saying you want to pick a random subset of the $n$ elements, with all $2^n$ subsets equally probable. I'm sure you can find easier ways of doing that. (For each of the $n$ elements, you just want to include it in the subset with probability $0.5$.)

That having been said, your interesting solution does almost work. For large $n$ it fails because Random([1..2^n]) tries to build a Range with a huge upper limit:

gap> n:=200;; [1..2^n];
Error, Range: <last> must be a small integer (not a large positive integer)

You can instead call a version of Random that does not require a range. Just give it the lower and upper limits as integers.

gap> enum:=EnumeratorOfCombinations([1..200]);;
gap> n := 200;; b := Random(1, 2^n); enum[b];
435499391128194516091289418442286066942494750160332640859166
[ 1, 3, 4, 5, 11, 13, 14, 16, 17, 19, 20, 21, 23, 25, 27, 28, 29, 30, 31, 35, 39, 42, 43, 44, 45, 46, 48, 49, 52, 54,
  55, 57, 61, 62, 64, 65, 70, 74, 75, 76, 77, 78, 79, 80, 81, 87, 88, 89, 90, 93, 94, 96, 97, 98, 99, 103, 104, 107,
  108, 110, 111, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 129, 130, 131, 133, 134, 135, 136, 137,
  140, 141, 143, 144, 146, 148, 149, 150, 151, 153, 154, 159, 160, 161, 162, 163, 164, 165, 167, 168, 169, 170, 172,
  175, 176, 177, 180, 185, 190, 191, 193, 195, 199 ]