/**
* This is a method which will gather the pixels
* of the 8 pixels surrounding a given pixel
* @param thisX is the x of the pixel in case
* @param thisY is the y of the pixel in case
*/
public Pixel[] getNeighbors(int thisX, int thisY)
{
Pixel[] pixels;
pixels = new Pixel[8];
pixels[0] = getPixel(thisX-1,thisY-1);
pixels[1] = getPixel(thisX-1,thisY);
pixels[2] = getPixel(thisX-1,thisY+1);
pixels[3] = getPixel(thisX,thisY+1);
pixels[4] = getPixel(thisX,thisY-1);
pixels[5] = getPixel(thisX+1,thisY+1);
pixels[6] = getPixel(thisX+1,thisY);
pixels[7] = getPixel(thisX+1,thisY+1);
return pixels;
}
Refactorings
No refactoring yet !
Marco Valtas
October 26, 2007, October 26, 2007 13:19, permalink
Here's a simple way. Note that if you ever want to get the 24 neighbors you just need to use "2" where I´m using "1" and expand the array.
/**
* This is a method which will gather the pixels
* of the 8 pixels surrounding a given pixel
* @param thisX is the x of the pixel in case
* @param thisY is the y of the pixel in case
*/
public Pixel[] getNeighbors(int thisX, int thisY)
{
Pixel[] pixels = new Pixel[8];
int index = 0;
for(int i = thisX - 1; i <= thisX + 1; i++)
{
for(int j = thisY - 1; j <= thisY + 1; j++)
{
if(i == thisX && j == thisY) continue;
pixels[index] = getPixel(i,j);
index++;
}
}
return pixels;
}
Marco Valtas
October 26, 2007, October 26, 2007 13:47, permalink
I´m behind a very nasty firewall/network and I´ve made a mistake on the above code, missed "thisY + 1" inside the second for. Since I can´t edit it I will paste here the same code corrected.
// See above code, already fixed.
Vime
November 5, 2007, November 05, 2007 12:48, permalink
Here another version with just one loop :)
/**
* This is a method which will gather the pixels
* of the 8 pixels surrounding a given pixel
* @param thisX is the x of the pixel in case
* @param thisY is the y of the pixel in case
*/
public Pixel[] getNeighbors(int thisX, int thisY)
{
Pixel[] pixels = new Pixel[8];
int index = 0;
for(int i = 0; i < 9; i++)
{
if (i == 4) continue;
pixels[index] = getPixel( thisX - 1 + (i % 3), thisY - 1 + (i / 3) );
index++;
}
return pixels;
}
dreamhost promo code
February 5, 2008, February 05, 2008 19:17, permalink
Thanks, was very useful for my programming assignment :)
I hate written a method to detect the 8 pixels surrounding one I have currently. Any way you can think of to make this smaller?