use List::Util qw( min ); use List::MoreUtils qw( any ); my $target = 5; my @max = (7, 4); my $time = 0; my @status = (0) x @max; my %seen; for (;;) { die("Unable to solve the problem\n") if $seen{join('|', @status)}++; foreach (0..$#status) { next if $status[$_]; $status[$_] = $max[$_]; print("$time: begin $max[$_]\n"); } last if any { $_ == $target } @status; my $elapsed_time = min(@status); $status[$_] = $status[$_] - $elapsed_time foreach 0..$#status; $time += $elapsed_time; } print("$time: begin cooking\n"); $time += $target; print("$time: end cooking\n");