我需要實現兩種方法,用二維數組工作:swaping和旋轉2D陣列
grayAndFlipLeftToRight
- 該方法將圖像轉換成灰度值的2D陣列,然後將其翻轉左到右。也就是說,面向左的對象現在將面向右。最左列的元素將與最右列的元素交換,依此類推。grayAndRotate90
- 此方法將圖像轉換爲二維灰度值數組,然後順時針旋轉90度(將其放置在右側)。
代碼:
public class PictureUtil
{
/**
* Gets a version of the given Picture in gray scale and flipped left to right
* @param pic the Picture to convert to gray scale and flip
* @return a version of the original Picture in gray scale and flipped
* left to right.
*/
public static Picture grayAndFlipLeftToRight(Picture pic)
{
int[][] pixels = pic.getGrayLevels();
for (int i = 0; i < pixels.length; i++) {
for (int fromStart = 0; fromStart < pixels[0].length; fromStart++) {
int fromEnd = pixels[0].length-1;
while (fromEnd >= 0) {
int saved = pixels[i][fromStart];
pixels[i][fromStart] = pixels[i][fromEnd];
pixels[i][fromEnd] = saved;
fromEnd--;
}
}
}
return new Picture(pixels);
}
/**
* Gets a version of the given Picture in gray scale and rotated 90 degrees clockwise
* @param pic the Picture to convert to gray scale and rotate 90 degrees clockwise
* @return a version of the original Picture in gray scale and rotated 90 degrees clockwise
*/
public static Picture grayAndRotate90(Picture pic)
{
int[][] pixels = pic.getGrayLevels();
int numberOfColums = pixels.length;
int numberOfRows = pixels[0].length;
int[][] rotate = new int[numberOfRows][numberOfColums];
for (int i = 0; i < pixels.length; i++) {
int seek = 0;
for (int j = 0; j < pixels[0].length; j++) {
pixels[i][j] = rotate[seek][numberOfColums - 1];
seek++;
}
}
return new Picture(rotate);
}
}
我的實現不正確兩種方法的工作。
- 如何解決這個問題?