Algorithm-Bucketizer

 view release on metacpan or  search on metacpan

Bucketizer.pm  view on Meta::CPAN

##################################################
package Algorithm::Bucketizer;
##################################################
# Documentation attached as POD below
##################################################

use 5.006;
use strict;
use warnings;

our $VERSION = '0.13';

##################################################
sub new {
##################################################
    my($class, @options) = @_;

    my $self = {     # Overwritable parameters
                 bucketsize      => 100,
                 algorithm       => "simple",
                 add_buckets     => 1,

                 @options,
           
                     # Internal stuff

                   # index (0-..) of bucket we're currently 
                   # inserting items into
                 cur_bucket_idx  => 0,

                 buckets         => [],
               };

    bless $self, $class;
}

##################################################
sub add_item {
##################################################
    my($self, $item, $size) = @_;

      # in 'simple' mode, we continue with the bucket we
      # inserted the last item into
    my $first = $self->{cur_bucket_idx};

      # retry tries all buckets
    $first = 0 if $self->{algorithm} eq 'retry';

        # Check if it fits in any existing bucket.
    for(my $idx = $first; exists $self->{buckets}->[$idx]; $idx++) {

        my $bucket = $self->{buckets}->[$idx];

        if($bucket->probe_item($item, $size)) {
            $bucket->add_item($item, $size);
            $self->{ cur_bucket_idx } = $idx;
            return $bucket;
        }
    }

        # It didn't fit anywhere. Create a new bucket.
    return undef unless $self->{add_buckets};
    my $bucket = $self->add_bucket();



( run in 0.475 second using v1.01-cache-2.11-cpan-e1769b4cff6 )