Reputation: 3431
I am working with a 2D array and I would like to view the elements to the "top left" "top" and "top right" of the smallest element in the last row. I have a code that works however it displays all of the directions of every element in the row, not just the smallest one. Can anyone help? This is my code:
for (int y = array.length-1; y == array.length-1; y--)
{
for (int x = 0; x < array[y].length; x++)
{
int lowest = array[y][0];
for (x = 0; x < array[y].length; x++)
{
if (array[y][x] <= lowest)
lowest = array[y][x];
//if element is on left
if (x == 0)
{
up = array[y-1][x];
upRight = array[y-1][x+1];
upLeft = 0;
}
//if element is on right
else if (x == array[0].length - 1)
{
upLeft = array[y-1][x-1];
up = array[y-1][x];
upRight = 0;
}
//if element is anywhere else
else
{
upLeft = array[y-1][x-1];
up = array[y-1][x];
upRight = array[y-1][x+1];
}
}
}
}
Upvotes: 0
Views: 462
Reputation: 66263
A couple of observations.
It seems like at the moment you have 2 nested for
loops where you're iterating over the whole array. From your description it sounds like this isn't necessary and you can just search array[array.length - 1]
for the lowest value.
Concentrate on writing a separate step (possibly its own method) that will find the index of the lowest value on the last row.
You pretty much have the logic correct for finding top left, top and top right. You just need it to look at elements from array[array.length - 2]
based on the index of the lowest value from the last row.
Update:
You mentioned in the question that your code "displays all of the directions of every element in the row". You haven't included any of the code that displays the results but from your comment below it sounds like your problem is as follows:
Your code that sets upLeft
, up
and upRight
is inside the loop that is searching for the lowest value. i.e. you have:
for (x = 0; x < array[y].length; x++)
{
if (array[y][x] <= lowest)
lowest = array[y][x];
//if element is on left
if (x == 0)
so this means that it happens for every element in the row.
What you probably want to do is have your loop to find the lowest element, and also remember its index:
for (x = 0; x < array[y].length; x++)
{
if (array[y][x] <= lowest) {
lowest = array[y][x];
indexOfLowest = x;
}
}
and then after that, outside of the inner loop, set upLeft
, up
and upRight
using the index of the lowest element found:
//if element is on left
if (indexOfLowest == 0)
etc.
Upvotes: 1