Hi,

I have a 2-d array, a[i][j] in which I need to compare with another 1-d array, b[k]. For each element in the 2-d array, I compare it with every element in the 1-d array. In the comparison, I find the element in b[k] which gives the minimum value of a[i][j]-b[k] and assign the value of b[k] to a[i][j].

What I did was :

Change the 2-d array to 1-d array

Find the difference between each of the new 1-d array and b[k] and store it in a temporary 2-d array.

Find the minimum value in the temporary 2-d array.

Assign value of b[k] which gives the minimum value in temporary 2-d array to the new 1-d array.

Change the new 1-d array back to 2-d array.

I find this very inefficient. How can I implement it in a more efficient way?

regards,

PY

I have a 2-d array, a[i][j] in which I need to compare with another 1-d array, b[k]. For each element in the 2-d array, I compare it with every element in the 1-d array. In the comparison, I find the element in b[k] which gives the minimum value of a[i][j]-b[k] and assign the value of b[k] to a[i][j].

What I did was :

Change the 2-d array to 1-d array

Find the difference between each of the new 1-d array and b[k] and store it in a temporary 2-d array.

Find the minimum value in the temporary 2-d array.

Assign value of b[k] which gives the minimum value in temporary 2-d array to the new 1-d array.

Change the new 1-d array back to 2-d array.

I find this very inefficient. How can I implement it in a more efficient way?

regards,

PY

But otherwise, I see no purpose in converting the 2-d array to 1-d array.

Do you really mean minimum a[i][j]-b[k] or minimum abs(a[i][j]-b[k])?

If the former, you'd just take the maximum b[k] for all a

Can you explain any more about what you're trying to do?

Not being a single value may not be an obstacle to sorting, but

sorting may not be appropriat of all possible representations of things you may be doing.

At worse, it seems you could just look at each element of a[i][j] in turn,

and evaluate (a[i][j]-b[k]) for all k, keeping track of the minmimum with still no need for any auxilliary array,

Or depending on what (a[i][j]-b[k]) really represets, there may be a way of saving some of the effort of multiple evaluations, but it's hard to guess whether this may be possble without furthur information.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.