Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

(tye)Re: (Golf as well): List of Partitions

by tye (Sage)
on May 07, 2001 at 19:12 UTC ( #78526=note: print w/replies, xml ) Need Help??


in reply to (Golf as well): List of Partitions

Rule #7 for sociopathic obsessive compulsives is "If you can't win, change the rules".

So here is a context-free iterator that produces all unique partitionings along with a golfed version of it:

#!/usr/bin/perl -w use strict; sub ipart { my( @a, $n )= @_; while( $n++, 0 == --$a[$#a] ){ $n += pop @a; return if ! @a; } do { push @a, @a && $a[$#a] < $n ? $a[$#a] : $n; $n -= $a[$#a]; } while( 0 < $n ); return @a; } sub ip { my(@a,$n)=@_;$n+=shift@a while$n++,@a&&!--$a[0]; {@a||last;@a=($a[0]<$n?$a[0]:$n,@a);($n-=$a[0])&&redo}@a } for( @ARGV ) { print "$_:\n"; my @p= $_; do { print " [",join(",",@p),"]\n"; } while( @p= ipart( @p ) ); print "$_:\n"; @p= $_; do { print " [",join(",",@p),"]\n"; } while( @p= ip( @p ) ); }
The advantage of a "context-free iterator" is that you can compute all possible partitions for really large numbers without running out of memory. They also tend to be pretty fast.

An iterator returns partitionings one at a time. "Context-free" means that all you have to pass subsequent calls to the iterator is the previously returned iterator.

Normally the first call to the iterator is a special case that initializes it and returns the first solution. In this case I cheat a little since ipart($n) looks like an initialization but can also be considered as passing in the first solution, I just start by returning the second solution.

Anyway, feel free to golf that down from the 104-character version I came up with (since the newline is not required).

        - tye (but my friends call me "Tye")

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://78526]
help
Chatterbox?
[1nickt]: my $x = $aohoaoh->[0]->{' foo'}->[0]->{'bar' }; should work
[thepkd]: not indexing
[thepkd]: getting data out of the ds
[choroba]: it depends. Give more details, please
[thepkd]: i used a series of {}'s but it dont work
[choroba]: You need square brackets for arrays
[GotToBTru]: you can certainly construct a single expression to access any part of the data structure, without using temp variables. but you might make it easier on yourself and any other poor soul who has to understand your code if you do
[thepkd]: to dereference i mean
LanX .oO( oh tempz, oh moretz)
[thepkd]: @GotToBTru Sure. But.

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (13)
As of 2016-12-06 13:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (104 votes). Check out past polls.