• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 146
  • Last Modified:


I need help writing a program which will compare numbers in an array. The comparison would be to the number right, left (if possible), diagonal(if possible), up(if possible), down(if possible). For example in the given data below

70       12       78
10       35       45
15      20       29

I would like to be able to compare 70 with 12, 10, 35. If 70 is larger than any one of these values I would like to output 70. Then 12 be compared with 70, 78, 10, 35, 45. If 12 is the largest among all of them then I would like to be able to print 12. So on so forth. I am using Visual C++. Any help will be greatly appreaciated. Thanks.
1 Solution
Break down your problem into the two main parts, which are

1. Find all neighboring values in your 2D array
2. Find the maximum in these and compare it to your current value

The 2ns part is trivial. The 1st part is the interesting one, you should create a function that takes the matrix dimensions and returns the indices of all neghbors, then you can grab the values for the comparison.

Since that sounds a bit like homework - which part is it that you are having difficulties with?
jess_82Author Commented:
Hello Jkr,
I m using an another method I thought about. I am padding some zeros in the array and then comparing each value with eight neighbors. Thanks.
Onve you have the neighboring values, just add them to a valarray and call 'max()', e.g. like

#include <valarray>
using namespace std;

valarray<int> va;


for (int i = 0; i < num_neighbors; ++i) va[i] = nerighbor[i];

int max_neighbor = va.max();
Nguyen Huu PhuocSenior ManagerCommented:
Your solution is not good enough. I think it is worst performance solution. Let us think again. When 70 is printed (i.e 70 is largest among its neighbors) you should skip its neighbors (12,10,35), you do not have to pay attention to it. With this hueristic, you will increase the performance significantly.

>>>> If 12 is the largest among all of them then I would like to be able to print 12.

You know, 12 isn't largest among { 12, 70, 78, 10, 35, 45 }. Would you like to print nothing in that case or the largest *neighbor* ? And how looks the output? Like that?

  70      78      78
  70      78      45
  35      45      45

Regards, Alex

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now