Rameez Rameez - 5 months ago 10
Perl Question

Logic to evenly distribute an array of time n number of arrays using perl

I need help to create a perl program to distribute array of execution time of program (in seconds) to n number of arrays.

Eg. I have an array which contains previous execution time of programs.

Time_array=(20,80,340,10,90,100,40,450,60)


My aim is to reduce the total execution time by distributing these programs to multiple servers. For eg, if i have 5 servers with me, i need to distribute these programs to 5 servers such way that time to complete is execution of all program is lowest.

Output expected is something like this, this is just an example,

array1=(450)
array2=(340)
array3=(100,20,10)
array4=(90,40)
array5=(80,60)


So that bigger programs are distributed to different servers.

Answer
use strict;
use warnings;
use v5.10;
use Data::Dumper;

my $servers_number = 5;
my @source = (20, 80, 340, 10, 90, 100, 40, 450, 60);
my @result;

@source = sort {$b <=> $a} @source;
my @server_times;

foreach my $time_chunk (@source)
{
    my $server_index = get_less_loaded_server_index();
    $result[$server_index] //= [ ];

    push @{$result[$server_index]}, $time_chunk;
    $server_times[$server_index] += $time_chunk;
}

sub get_less_loaded_server_index
{
    my $lessest_time;
    my $selected_server;

    for (my $i = 0; $i < $servers_number; $i++)
    {
        $server_times[$i] //= 0;

        if (!defined $selected_server || $lessest_time > $server_times[$i])
        {
            $lessest_time = $server_times[$i];
            $selected_server = $i;
        }
    }
    return $selected_server;
}

say Dumper(\@result);