CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2008
    Posts
    12

    Lightbulb How to write this algorithm in C++?

    I'm kind of stumped as to how to write this in C++, seeing as I need some way of making the out of range array references = 0.

    Source, filter and output arrays:
    Code:
    S [7] = { 1,2,3,4,5,6,7 };
    Filter [3] = { a0,a1,a2 };
    out [x];
    out[0] = a0.V[0] + a1.V[X]+ a2.V[X]
    out[1] = a0.V[1] + a1.V[0] + a2.V[X]
    out[2] = a0.V[2] + a1.V[1] + a2.V[0]
    out[3] = a0.V[3] + a1.V[2] + a2.V[1]
    out[4] = a0.V[4] + a1.V[3] + a2.V[2]
    out[5] = a0.V[5] + a1.V[4] + a2.V[3]
    out[6] = a0.V[6] + a1.V[5] + a2.V[4]
    out[7] = a0.V[X] + a1.V[6] + a2.V[5]
    out[8] = a0.V[X] + a1.V[X] + a2.V[6]

    The only way I can see to do it would be to include an 'if' statement; e.g. "if (i<0) i=0;", but that seems horribly inefficient.

    Has anyone got a better idea?

    Any help would be greatly appreciated!

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: How to write this algorithm in C++?

    An if statement shouldn't be that bad, as branch prediction is pretty good about things that only happen near array edges. However, if you want, you can do the inner portion of the filter first and then the ends as special cases.

  3. #3
    Join Date
    Dec 2008
    Posts
    12

    Re: How to write this algorithm in C++?

    Well if that's the case, then I guess it's ok.
    I only ask as it's for a coursework that's assessed on the code being 'nice'...

    thanks

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: How to write this algorithm in C++?

    If you have a choice between readability and efficiency, choose readability unless you have a compelling reason to do otherwise.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured