Given a string, I'd like to create the minimum number of sets of substrings where:
- substrings have a length up to x
- if two sets differ when a substring in one set can be composed of smaller substrings in the other set, the second set can be excluded
For example, the substring "abcdef" with max substring length of 3 would result in the following:
[
['abc','def'],
['ab','cde','f'],
['ab','cd','ef'],
['a','bcd','ef'],
]
['abc','de','f'] is not included because of condition (2). eg, 'def' is compsed of 'de','f'
The following recursive allSubstrings() method isn't quite right and doesn't feel like the right approach. Also has the problem of being slow with longer strings.
const allSubstrings = (input,max_len = 3) => {
if( input.length === 1) return [[input]];
let result = [];
const start = input.substring(1);
allSubstrings(start).forEach(function(subresult) {
let tmp = subresult.slice(0);
if( tmp[0].length < max_len ){
tmp[0] = input.charAt(0) + tmp[0];
result.push(tmp);
}
if( subresult.length > 1 ){
if( subresult.slice(0,2).join('').length <= max_len ){
return;
}
if( subresult.slice(subresult.length-2).join('').length <= max_len ){
return;
}
}
tmp = subresult.slice(0);
tmp.unshift(input.charAt(0));
result.push(tmp);
});
return result;
}