Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Generator of integer partitionts of n

by eric256 (Parson)
on Aug 28, 2004 at 02:42 UTC ( #386541=note: print w/ replies, xml ) Need Help??


in reply to Generator of integer partitionts of n

I started with the assumption that the partition of 1 was [ [ 1 ] ] and that the partion of each larger one was each sub partion with 1 added to the end, and with one added to each element. Hmm that was more confusing than in my head. Well here, the partition of 2 is [ [ 1 + 1] , [1 , 2]][ [ 1 + 1] , [1 , 1]] and the partition of 3 is [ [ 2 + 1], [1 + 1, 2], [1, 2 + 1], [1 , 2 , 1]]. Well if that hasn't made any sense here is the code.

use strict; use warnings; use Data::Dumper; sub partition { my $num = shift || 1; my $temp = [ [1] ]; # updated 0 to 2 in the following, # since we start with one, the first add_one gets us to two. $temp = add_one($temp) for (2 .. $num); return $temp; } sub add_one { my $combinations = shift; my $temp; foreach my $combination (@$combinations) { foreach my $element (@$combination) { $element++; push @$temp, [ @$combination ]; $element--; } push @$temp, [ @$combination, 1 ]; } my $hash; foreach my $combination (@$temp) { $hash->{ join("-", sort @$combination) }++; } return [ map { [ split "-", $_ ] } keys %$hash ]; } print Dumper(partition(10) );

Oh and I added in some code to stop it from accumulating duplicates.

Updates: Thanks blockhead for noticeing some errors there


___________
Eric Hodges


Comment on Re: Generator of integer partitionts of n
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (14)
As of 2015-07-03 12:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (53 votes), past polls