Biggytiny - 1 year ago 51
Java Question

# Compare layers of two dimensional array simultaneously

I am working on a project for an Algorithms class in Java, and I am stuck with this problem I cannot figure out.

I have a two dimensional array of size [m][n], where m and n can fluctuate depending on input. I want to condense the values into a single dimension array based on which value is the lowest out of any vertical column in the two dimensional array. Here are two samples of the array.

Sample 1 input:

``````3.0, 4.0, 2.0, 3.0, 4.0, 2.0, 1.0, 2.0, 0.0, 3.0, 3.0
0.0, 1.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 3.0, 2.0, 2.0
``````

Sample 1 output:

``````0.0, 1.0, 1.0, 2.0, 3.0, 1.0, 1.0, 2.0, 0.0, 2.0, 2.0
``````

Sample 2 input:

``````0.0, 1.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 3.0, 2.0, 2.0
2.0, 3.0, 1.0, 0.0, 1.0, 3.0, 2.0, 3.0, 3.0, 4.0, 2.0
1.0, 2.0, 2.0, 3.0, 4.0, 0.0, 1.0, 2.0, 2.0, 1.0, 3.0
1.0, 2.0, 0.0, 1.0, 2.0, 2.0, 1.0, 2.0, 2.0, 3.0, 1.0
2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 0.0, 1.0, 1.0, 2.0, 2.0
``````

Sample 2 output:

``````0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0
``````

And this is the logic I want to sort is this:

``````loop through the 2-d array
at every vertical index, compare all values within the vertical index,
output lowest value to single dimensional array
``````

I believe this is a somewhat simple problem, but I cannot wrap my head around how to do this properly. Thank you for any advice you can provide!

Answer Source

Imagine that for input[m][n] m would be your rows and n would be your columns, so you have to traverse column wise to get the lowest value in that column:

``````int[] output = new int[n];
for(i = 0; i < n; i++)
output[n] = 0;
for(i = 0; i < n; i++)
for(k = 0; k < m; k++)
if(output[n] > input[m][n])
output[n] = input[m][n];
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download