Loading ...
Sorry, an error occurred while loading the content.
 

Re: generating combinations

Expand Messages
  • b_harnish
    Unless you can find an algorithm to do just find combinations, you can find the combinations from the permutations: my @orig = (1,2,3); #Get permutations len=2
    Message 1 of 2 , Jan 3, 2002
      Unless you can find an algorithm to do just find combinations, you
      can find the combinations from the permutations:

      my @orig = (1,2,3);
      #Get permutations len=2 from @orig
      my @perms = getperms(2, @orig);
      # @perms = ([1,2],[1,3],[2,1],[2,3],[3,1],[3,2])

      # Get a sorted version of the permutations
      my @sorted1 = map { [sort @{$_}]; } (@perms);
      # Remove duplicates.
      my %nodupes = map { join(',',@{$_}), [@{$_}] } (@sorted1);

      my @combinations = values %nodupes;

      - Brian

      --- In perl-beginner@y..., "corgard10" <corgard10@y...> wrote:
      > Hello,
      >
      > I would like to generate all *combinations* for an "n choose k"
      > scenario. For example, if I have a set of 4 numbers (1,2,3,4) and I
      > want to chose 3 at a time, the combinations (NOT *permutations*)
      > would be:
      >
      > 1,2,3
      > 1,2,4
      > 2,3,4
      >
      > 4 chosen 2 at a time would be:
      >
      > 1,2
      > 1,3
      > 1,4
      > 2,3
      > 2,4
      > 3,4
      >
      > Does anyone have a combinations algorithm for "n choose k" of any
      list
      > length n? I've found algorithms for permutations; however, I am
      > looking for *combinations*.
      >
      > Thanks so much for your help.
      >
      > Sincerely,
      >
      > SJG
    Your message has been successfully submitted and would be delivered to recipients shortly.