This solution uses the same base idea as Roy Johnson's (summing the original stats), but uses an approach that won't give negative stats and doesn't suffer from rounding error. (It does this by quickly trying every possible combination of initial stats.)

use strict; use warnings; use List::Util qw( max sum ); my @stats = qw( hp mana spells ); my %rates = ( hp => 12, mana => 17, spells => 7 ); my %stats = ( hp => 60, mana => 80, spells => 31 ); my %needed = ( hp => 51, mana => 107, spells => 38 ); { my $avail = sum @stats{@stats}; our @parts; ('.' x $avail) =~ / ^ (.*) (?(?{ length($1) > $needed{$stats[0]} })(?!)) (.*) (?(?{ length($2) > $needed{$stats[1]} })(?!)) (.*) (?(?{ length($3) > $needed{$stats[2]} })(?!)) \z (??{ push @parts, { $stats[0] => length($1), $stats[1] => length($2), $stats[2] => length($3), }; }) (?!) /x; my ($result) = sort { $a->[1] <=> $b->[1] } map { my $part = $_; my $time = max map { ( $needed{$_} - $part->{$_} ) + / $rates{$_} } @stats; [ $_, $time ] } @parts; print(join("\t", @stats, 'hours'), "\n"); printf(join("\t", ("%d")x@stats, "%.2f") . "\n", @{$result->[0]}{@stats}, $result->[1], ); }
hp mana spells hours 43 95 33 0.71

There's surely a better way of finding the partitions, but I don't know it off the top of my head, the method I used works, and the method I used is fast.


In reply to Re: Calculate easiest way to 'level results' by ikegami
in thread Calculate easiest way to 'level results' by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.