Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Combinations with variable length

by davido (Cardinal)
on May 10, 2021 at 22:07 UTC ( #11132356=note: print w/replies, xml ) Need Help??


in reply to Combinations with variable length

Your intuition to use Algorithm::Combinatorics is correct, but your choice of functions within that module was incorrect. The correct function exists, and is documented in the POD: variations_with_repetition.

use Algorithm::Combinatorics qw(variations_with_repetition); my @data = (1,2); my $at_a_time = 3; my $variations_iterator = variations_with_repetition(\@data, $at_a_tim +e); while (my $variant = $variations_iterator->next) { print "@$variant\n"; }

This produces:

1 1 1 1 1 2 1 2 1 1 2 2 2 1 1 2 1 2 2 2 1 2 2 2

You were so close!

In the future, please post the sample code. In this case I would have used it to verify that you were using the module correctly, aside from using the incorrect function.

Also, a lesson from high school math, and from the POD: There are n^k variations with repetition. So in your case the input set size is 2, and you're taking 3 at a time. 2**3=8. So we can validate that we got the correct number of variations by checking that we got 8, and that there are no repeats.


Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11132356]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2021-07-23 20:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?