Is there a function for combinations?

Is there an internal function or library that takes an array and returns a matrix with the combination of the numbers in the array, for example the array (1,2,3,4) return ((1,2),(1,3),(1,4),(2,3),(2,4),(3,4)). I’m working on a collision simulation and need to keep track of the distance between the particles.

1 Like

One of the codes of John Burkardt may have this:

TOMS515 is a FORTRAN90 library which lists the subsets of size K selected from a set of size N, by Bill Buckles, Matthew Lybanon.

combo , a FORTRAN90 code which includes routines for ranking, unranking, enumerating and randomly selecting balanced sequences, cycles, graphs, Gray codes, subsets, partitions, permutations, restricted growth functions, Pruefer codes and trees.

subset , a FORTRAN90 code which enumerates, generates, randomizes, ranks and unranks combinatorial objects including combinations, compositions, Gray codes, index sets, partitions, permutations, polynomials, subsets, and Young tables. Backtracking routines are included to solve some combinatorial problems. Other routines handle continued fractions, Diophantine equations, and Pythagorean triples.

3 Likes

If you require just pairs, it can be done as follows

program main
   implicit none
   integer :: N,M, i,j, counter
   integer, allocatable:: array(:), nc2(:,:)

   array=[5,6,7,8,9]
   N=size(array)
   M=int(N*(N-1)/2)

   allocate(nC2(2,M))

   counter=1
   do i=1,N
      do j=i+1,N
         nc2(1,counter)=i
         nc2(2,counter)=j
         write(*,"(2(I0,x))")array(i),array(j)
         counter=counter+1
      enddo
   enddo

endprogram main