Here's an interesting little puzzle. I have a set of files named after book ISBNs. These can be from five to nine characters long. There are thousands of these, and I don't want to put them all in one directory because that will hurt file system performance. I was planning to split them all up by zero-padding them all to nine characters and then slicing their numbers into directory names. For example, 123456789.gif would be stored at /12/34/56/123456789.gif.

Now, if I make too many directories I'll be hurting file system performance rather than helping. So, the challenge is to come up with a short algorithm for determining the optimal way to break up these files so that we have no more than n (probably 100) files or subdirectories in any one directory, and the minimum number of directories in total. This would be simple if the data was a uniform distribution, but in this case it isn't. It's possible for 99% of the data to have the same first five digits.

I was attacking this through brute force by simulating the directories with hashes and counting the number of files that fell into each one, but I feel like there must be some simple mathematical solution for this that I'm not seeing. Also, my approach makes it a pain to experiment with alternatives like /12345/67/12345689.gif, which might be the best solution with a given set of data.

I know this is kind of dumb to obsess over, and I could just stop fooling around and split them up on every two digits, but it turned into kind of an interesting brainteaser. Anyone?


In reply to brainteaser: splitting up a namespace evenly by perrin

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.