Do you think is it a good strategy?

Does my opinion matter? You are using a greedy approach for an NP complete problem (knapsack). So you don't get an optimal result (where optimal is, I presume, the use of a minimal number of lines), but you get it pretty quickly. Whether that's good enough, I don't know. Only you, and the enduser (or client), can decide that.

Now, if you have thousands of fragments, with many fragments on each line, you might want to use a segment tree for each of the lines you create, to be able to determine faster whether a new fragment fits a line.

Alternatively, you chould sort the fragments on starting position. Then, do something like:

0. Create a new empty line, and make it the current one. 1. Find the first fragment in the list that fits on the line. 2. If there is no such fragment, goto 0. 3. Add the fragment to the current line, and remove it from the list. 4. If the list is empty, you're done. 5. Goto 1.
This is also greedy; it won't find the optimal packing, but it's reasonbly fast.

In reply to Re: formatting output question (use of recursive subroutine?) by JavaFan
in thread formatting output question (use of recursive subroutine?) by rogerd

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.