Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Generator of integer partitionts of n

by eric256 (Parson)
on Aug 28, 2004 at 02:42 UTC ( [id://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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-04-25 20:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found