0
\$\begingroup\$

My function takes the values of the profit (function declared as fieldProfit) and the field score (function declared as fieldScore). If both are above 10, then you earn a badge, hence, innerbadge = 1.

But, there's also another condition that must be met: the field or (x, y) coordinates have to fall in the area depicted as the shaded in box that has a hole in the middle. Here's the image:

enter image description here

I've written the code for it, and I just wanted to make sure that my logic/syntax is correct.

 int badgeInnerCircle(int x, int y) {
       double fprofit, fscore;
       int innerbadge;

       if ((x >= 1 && x <= 20) && (y >= 1 && y <= 20)) {
          if (((x == 7 || x == 8) && (y >= 7 && y <= 14)) || ((x == 13 || x == 14)
             && (y >= 7 && y <= 14)) || ((x >= 7 && x <= 14) && (y == 7 || y == 8))
                || ((x >= 7 && x <= 14) && (y == 13 || y == 14))) {
             fprofit = fieldProfit(x, y);
             fscore = fieldScore(x, y);
             if (fprofit >= 10 && fscore >= 10) {
                innerbadge = 1;
             }
             else {
                innerbadge = 0;
             }
          }
       }
       else {
          innerbadge = -1;
       }
       return innerbadge;
    }
\$\endgroup\$
1
  • \$\begingroup\$ Needs documentation! \$\endgroup\$ Oct 24 '13 at 12:12
2
\$\begingroup\$

I think we can all agree that that code is hard to read. Rather than treating the dark shaded zone as the union of four rectangles, you would be better off treating it as a square with the centre excluded.

I've used a macro to reduce the verbosity.

In your code, when (x, y) falls in either of the white zones, you return an uninitialized value for innerbadge. In those cases, the behaviour is undefined.

#define XY_IN_SQUARE(min, max) (((min) <= x && x <= (max)) && \
                                ((min) <= y && y <= (max)))

int badgeInnerCircle(int x, int y) {
    if (XY_IN_SQUARE(9, 12)) {          /* In innermost white zone */
        return /* what? */;
    } else if (XY_IN_SQUARE(7, 14)) {   /* In dark grey zone */
        double fprofit = fieldProfit(x, y);
        double fscore = fieldScore(x, y);

        /* The following value will be either 1 or 0 */
        return fprofit >= 10 && fscore >= 10;
    } else if (XY_IN_SQUARE(2, 19)) {   /* In outer white zone */
        return /* what? */;
    } else if (XY_IN_SQUARE(1, 20)) {   /* On yellow border */
        return /* what? */;
    } else {                            /* Outside yellow border */
        return -1;
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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