in reply to Creating a sub-list constrained by an average while maintaining maximum number of original elements

That is not so much a Perl-question as one related to finding an algorithm, but still very interesting.

My take on that would be:

  1. Calculate the average of the whole list: if you are near the average, you're done; if not, go to step 2.
  2. Calculate how much bytes you must "gain" or "loose" to reach the average and find a file which is as close as possible to that figure and eliminate that file (to "gain" bytes on your average you must eliminate a file with less bytes than your average, so the average increases). Note: to calculate the "new" average, remember that you now have one less file in your list! After eliminating that file, call the new list your "whole" file and feed it to step 1.

For sure this algorithm is not guaranteed to provide a solution, but provided your list is big enough and the lengths of the files are sufficiently well spread out, it should not be too bad (for various appropriate definitions of "big enough", "sufficiently" and "not too bad").

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

  • Comment on Re: Creating a sub-list constrained by an average while maintaining maximum number of original elements

Replies are listed 'Best First'.
Re^2: Creating a sub-list constrained by an average while maintaining maximum number of original elements
by stevieb (Canon) on Sep 01, 2010 at 06:52 UTC

    CountZero...

    I am truly humbled by your reply to the OP. Your response was quick, and eerily accurate. I understood what he was asking only after you had replied.

    I am dazzled by your ability to so rapidly dissect such a problem into its parts, and then provide an easy-to-understand description of the mathematical formula.

    Steve

      Thank you for this praise, but really it is what I was trained to do.

      Yes, I am a lawyer (not a trained programmer) and as a lawyer we are trained to analyse a problem (most of the time based on incomplete or even wrong data), then synthesize a solution and present this solution using language (the dreaded "legalese").

      It is not that different what a analyst / programmer does!

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James