Search code examples
functionparipari-gp

Is there a comfortable way to generate the combinations k out of n in PARI/GP?


Suppose, I have a vector in PARI/GP with n elements.

I want to generate the combinations k out of n elements.

For example, if the vector is [3,7,11,14,18] and k=3, the output should be

[3,7,11]
[3,7,14]
[3,7,18]
[3,11,14]
[3,11,18]
[3,14,18]
[7,11,14]
[7,11,18]
[7,14,18]
[11,14,18]

Is there a command in PARI/GP doing this, or do I have to program the funtion ?


Solution

  • Unfortunately, PARI has not a built-in command that does all the stuff you need.

    Function forvec (with flag = 2) fits the combinatorial problems very nice. So your function can be as follows:

    subsets(A, k) = {
       my (lst = List());
       forvec(v = vector(k, i, [1, #A]), listput(lst, vecextract(A, v)), 2);
    
       Vec(lst)
    };
    
    subsets([3,7,11,14,18], 3)
    gp> [[3,7,11], [3,7,14], [3,7,18], [3,11,14], [3,11,18], [3,14,18], [7,11,14], [7,11,18],
         [7,14,18], [11,14,18]]