Given an arbitrary string of text, the task is to group the text into separate sections of a template. Each section has different min length and max length parameters. A solution can be considered optimal for a section as long as it falls within those bounds. A greedy solution might result in some sections not meeting their minimums, which means the solution as a whole is not acceptable.
I’m having trouble efficiently constructing an algorithm to do this. It seems that a dynamic programming approach might help, but thus far, I haven’t been able to couch it in dynamic programming terms. Does anyone have any leads on solving this problem?
function groupText(str, template)
Inputs:
str: a string of text
template: array of JavaScript objects.
One object per section that describes the min/max amount of text allowed
Output:
array: each element corresponds to one section.
The value of the element is the text that is in the section.
As an example, let’s define a string str that is equal to “This is a test.” We also have a template t. t consists of several sections. Each section s has a minimum and maximum amount of characters allowed. Let’s say for this example there are only two sections: s1 and s2. s1 has a minimum of 1 character and a maximum of 100. s2 has a minimum of 10 characters and a maximum of 15. We pass our string str and our template t to a function groupText. groupText must return an array, with each element i corresponding to a section. For example, element 0 will correspond to s1. The value of the element will be the text that has been assigned to the section.
In this example, a solution might be.
s1text = “This “
s2text = “is a test.”
If I understood the problem correctly there’s no need of any search… just subtract from the total length the sum of the minimum lengths and what remains is the amount to be distributed. Then distribute this amount to each element up to its maximum until nothing is left… in code