0

I have a matrix filled with * and -, where * represents a virus and - a free spot for a virus, I have to check in my matrix the neighbours of every virus, a valid neighbour is another virus and not a free spot, in order to establish their number. The neighbours I have to check are [row + 1][col], [row - 1][col], [row][col + 1] and [row][col - 1], in total four neighbours. I made a function to check and cover all the cases, for example if the element that I am checking is one of the corners of the matrix. I came up with a really long 80 lines function that has a lot of if statements. Is there an efficient way(meaning the number of lines) to check all this besides having to write like 20 if statements?

https://pastebin.com/2f7YpreZ Here is the code I've written

Julanu
  • 162
  • 2
  • 5
  • 15
  • 1
    You have a function which does the job but seems inefficient? Try a codereview at the appropriate site. https://codereview.stackexchange.com – Yunnosch Jun 16 '17 at 16:56
  • 1
    If you want somebody here to spot the single most unhelpful design problem in your existing code, then make a [mcve]. – Yunnosch Jun 16 '17 at 16:58
  • `Is there an efficient way to check all this besides having to write like 20 if statements? ` Well - please define `efficient`. In terms of performance? In terms of number of code lines? In terms of maintainability? If you're referring to performance, just trust the compiler. If your requirements isn't met, profile your code and adjust accordingly. – Support Ukraine Jun 16 '17 at 17:02
  • 1
    @MariusJula - post your code so that we can see what you have so far – Support Ukraine Jun 16 '17 at 17:06
  • I would do the 4 corners first, then the 4 edges (except the corners) and then the rest (except the edges). No exceptions need be tested. – Weather Vane Jun 16 '17 at 17:07
  • https://pastebin.com/2f7YpreZ Here is the code – Julanu Jun 16 '17 at 17:13
  • One common method is to define an array 2 cells larger than you need in each direction, and allow the neighbour test to fail when it considers the unused strip around the edge. – Weather Vane Jun 16 '17 at 17:18
  • If this is a 2-dimensional array, you should need no more than 4 `if` statements. If it's 3-d, 8 would be needed... In the general n-dimensional case, you'll need `2^n` edge detection tests. – twalberg Jun 16 '17 at 17:23

1 Answers1

0

What you could do is to merge if statements that lead to the same results. This will lead to shorter (and more readable) code, and can boost performance in certain cases.

So for example if you have:

if([row - 1][col])
    // do A
else if([row][col + 1])
    // do B
else if([row + 1][col])
    // do A

then you could write it as such:

if([row - 1][col] || [row + 1][col])
    // do A
else if([row][col + 1])
    // do B

Do this, and you feel that your code needs further improvements, please post at Code Review.

gsamaras
  • 71,951
  • 46
  • 188
  • 305