vendredi 8 mai 2015

if-clause seems not to be executed under certain arbitrary conditions

I am trying to divide a triangular matrix into parts, which hold approximatetely the same amount of elements.

I wrote the following code, which works nicely for the most combinations of inputs and segments my matrix into the given number of parts from 0 to $length. However, there are input combinations like $length = 2003 and $number_of_segments = 50, where the last segment is missing in the output. I tested the values of $threshold and $total, but they seem to be correct even in those odd cases.

Do you have any ideas, where the bug is?

#!/usr/bin/perl

use strict;         #should always be used
use warnings;       #that one too
use autodie;        #just in case I forgot to check anything

my $length = shift or die "ERROR: Not enough arguments!\n";         #number of rows in the matrix
my $number_of_segments = shift or die "ERROR: Not enough arguments!\n";     #number of segments we want to get

my @segments = ÷         #array of segment-limits
print "$_\n" foreach @segments;

sub divide {
    my @segments = (0);         #the first segment starts at 0
    my $number_of_pairs = ($length*($length+1))/2;          #number of elements in matrix
    my $total = 0;          #counter for the elements we already visited
    my $segment_counter = 1;        #we are in the first segment

    for (my $i=0; $i<$length; $i++){        #going over the rows of the matrix
        $total += $length-$i;           #counting the elements in each row
        my $threshold = ($number_of_pairs/$number_of_segments)*$segment_counter;        #threshold for the next segment
        if ($total >= $threshold){          #if our current segment is large enough
            push @segments, $i+1;              #save the limit
            $segment_counter++;            #and open the next segment
        }
    }

    return @segments;
}

Aucun commentaire:

Enregistrer un commentaire