#! /usr/bin/perl # # my @relation_Arr; my @toplevelArr = qw(TOP01 TOP02 TOP03); my @midlevelArr = qw(MID01 MID02 MID03 MID04 MID05 MID06 MID07 MID08 MID09 MID10 MID11 MID12 MID13 MID14 MID15 MID16 MID17 MID18 MID19 MID20 MID21 MID22 MID23 MID24); my %lowlevelH = qw(LOW01 19000 LOW02 19523 LOW03 13456 LOW04 18992 LOW05 19560 LOW06 18945 LOW07 19855 LOW08 12344 LOW09 17400 LOW10 18990 LOW11 14566 LOW12 17896 LOW13 19000 LOW14 1 9523 LOW15 13456 LOW16 18992 LOW17 19560 LOW18 18945 LOW19 19855 LOW20 12344 LOW21 17400 LOW22 16897 LOW23 19877 LOW24 18676 LOW25 13457 LOW26 12345 LOW27 18456); my $tottopSum = 0; my $totmidSum = 0; while (1) { foreach my $lowLevel (sort keys %lowlevelH) { if($tottopSum == 0) { $tottopSum = $tottopCount + $lowlevelH{$lowLevel}; $totmidSum = $totmidSum + $lowlevelH{$lowLevel}; push(@relation_Arr, "$toplevelArr[0]:$tottopSum, $midlevelArr[0]:$totmidSum, $lowLevel, $lowlevelH{$lowLevel}"); ### REmove the first element from the array toplevelArr and midlevelArr next; } if (($tottopSum + $lowlevelH{$lowLevel}) < 650000) { if (($totmidSum + $lowlevelH{$lowLevel}) < 35000) { $tottopSum = $tottopCount + $lowlevelH{$lowLevel}; $totmidSum = $totmidSum + $lowlevelH{$lowLevel}; push(@relation_Arr, "$toplevelArr[0]:$tottopSum, $midlevelArr[0]:$totmidSum, $lowLevel, $lowlevelH{$lowLevel}"); ### Remove the first element from the array midlevelArr } else { #### Go down the list of lowLevel Hash and find a value that can #### added to $totmidSum such that it does not cross 35000 #### IF found add it to the result array relation_Arr #### Else assign it to the next mid level Element. } } else { ### Assign next TOP element of the array } } } print "@relation_Arr\n"; Results should be TOP01:19000 MID01:19000 LOW01 19000 TOP01:32456 MID01:32456 LOW03 13456 TOP01:51979 MID02:19523 LOW02 19523 TOP01:64323 MID02:31867 LOW08 12344 ;; ;; ;; and so on.