0

I'm writing a function which concatenates different numbers of strings depending on their length.

Here is some c++ like pseudo code of what I'm currently doing:

string foo(size_t maxLength)
{
    string a, b, c, d, e, ret;

    //...assign them

    if(a.size() + b.size() + c.size() + d.size() + e.size() <= maxLength)
    {
        ret = a + b + c + d + e;
    }
    else if(a.size() + c.size() + d.size() + e.size() <= maxLength)
    {
        LOG << "B was removed.";
        ret = a + c + d + e;
    }
    else if(a.size() + b.size() + c.size() + d.size() <= maxLength)
    {
        LOG << "E was removed"l
        ret = a + b + c + d;
    }
    //... a large amount of code like the above

    return ret;    
}

Is there a nice way to clean this up?

Thanks.

8
  • 1
    How do you decide which one gets removed when it doesn't fit maxLength? Aug 11, 2010 at 0:22
  • @quantumSoup: It's based on arbitrary rules that I can't control and which may change in the future
    – Jon
    Aug 11, 2010 at 0:26
  • Also note that this looks a bit like the Knapsack problem, which is NP-complete (in other words, the solution will be inefficient) Aug 11, 2010 at 0:28
  • @Jon And they are just random; there's no pattern that can be programatically detected or defined? Aug 11, 2010 at 0:28
  • For what purpose your function is concatenating strings like this? What do you need to achieve with it? Aug 11, 2010 at 0:30

3 Answers 3

0

To begin with, I'd convert it to array of strings. Then loop through your options and see which permutation actually fits your maxLength.

As quantumSoup commented - you did not mention your criteria for elimination, but once you have this defined, it is easy to iterate the options by eliminating the specific array indices, according to your priority criterion.

0

If you were just looking to clean it up visually, something like:

    string a, b, c, d, e, ret, temp;

    //...assign them

    temp = a + b + c + d + e;
    if(temp.length <= maxLength) {
        LOG << "none removed";
        ret = temp;
    }

    temp = a + b + c + d;
    if(temp.length <= maxLength) {
        LOG << "e removed";
        ret = temp;
    }    

    temp = a + b + c + e;
    if(temp.length <= maxLength) {
        LOG << "d removed";
        ret = temp;
    }

    //... etc

    return ret;

As ysap mentioned, you can optimise it with loops if you have elimination criteria.

0

If the order for omitting strings is arbitrary, I'd try to construct a list of some kind ordered by the priority. Then I'd work my way through the list until I'd filled up the output buffer. If as you say the priorities are externally defined and arbitrary, you could probably drive it with constant table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.