in reply to Challenge: Generate fixed size combination across groups without duplicates

If I correctly understand what you want then the following does the trick:

#!/usr/lib/perl use strict; use warnings; my @groups; my $size; while (<DATA>) { chomp; my ($type, $value) = split /\s*=\s*/, $_, 2; next if ! defined $value; if ($type eq 'fixed_size') { $size = $value; next; } push @groups, [split (/ /, $value), undef]; } pickem ($size, [], @groups); sub pickem { my ($needed, $givenList, @options) = @_; my $list = shift @options; for my $item (@$list) { if (! defined $item) { pickem ($needed, $givenList, @options); next; } if ($needed == 1) { print "@$givenList $item\n"; next; } pickem ($needed - 1, [@$givenList, $item], @options); } } __DATA__ group_1 = A B C group_2 = 1 2 3 4 group_3 = yellow blue green group_4 = tiny small medium large gigantic fixed_size = 2
True laziness is hard work
  • Comment on Re: Challenge: Generate fixed size combination across groups without duplicates
  • Download Code

Replies are listed 'Best First'.
Re^2: Challenge: Generate fixed size combination across groups without duplicates
by Limbic~Region (Chancellor) on Nov 16, 2011 at 04:30 UTC
    GrandFather,
    Ah yes, recursion - that thing my brain finds so confusing. Thanks - this appears to be perfect.

    Cheers - L~R

      The real trick is adding the "no-op" entry to each group.

      True laziness is hard work
        GrandFather,
        No, I assure you that my brain does not think recursively. I have never encountered any other programmer or a math aficionado with this affliction. That makes it amazingly frustrating when people say - it is simple, just think of it as repeating a simple process until a termination condition is met. Of course I understand that and I don't usually having a problem understanding someone else's recursive solution. My problem is that my brain just doesn't think that way - I don't know how else to explain.

        On the bright side, as soon as I stopped thinking about the problem thanks to your solution, I discovered how to do it iteratively using a variation on Arbitrarily Nested Loops (odometer model). If I get a chance to code it up I will but the key was to have a set of empty slots representing the combination that you copied values from as you rotate wheels on the dial. It becomes a very simple process at that point.

        Cheers - L~R