# Two-Dimensional Arrays and Nested Loops

Document Sample

```					Two-Dimensional Arrays and Nested
Loops
Barb Ericson
Georgia Institute of Technology
June 2005

Georgia Institute of Technology
Learning Goals
• Understand at a conceptual and practical
level
– What is a two-dimensional array?
– How do you create two-dimensional arrays?
– How do you access data in two-dimensional
arrays?
– How do you use nested loops?

Georgia Institute of Technology
What is a two-dimensional array?
• The pixels in a picture
are really stored in a                   x
two-dimensional array
– Each pixel has a x             y
value (horizontal
location)
– Each pixel has a y
value (vertical location)
– pictureObj.getPixel(x,y)
returns the pixel at that
location

Georgia Institute of Technology
Example Two-Dimensional Arrays
• Maps
– That street is in D-5
• Battleship
– Try I-5
• Hit or miss
• Chairs at a theater or
game
– Row C seat 20

Georgia Institute of Technology
Two-Dimensional Arrays
• To create a 2-d array
– With an x and y dimension
int[][] grid = new int[2][3]; // num rows, num cols
int grid[][] = new int[2][3];
int[][] grid = {{2, 3 1}, {4, 5, 6}}; // two rows, three cols
• How to set values in a 2-d array
grid[0][0] = 3;
grid[1][2] = 5;
• How to get values from a 2-d array
int value = grid[0][0]; // row = 0, col = 0
int value = grid[1][2]; // row = 1, col = 2

Georgia Institute of Technology
2-d Array Exercise
• Try the following in the
interactions pane of
DrJava                                             0   1   2
• Create a 2 row 3 column                   0    1       2   3
2-d array
• Get the values in each                    1    4       5   6
data area
• Put values in each                                 0   1   2
possible data area
• Get the values in each                    0    5       3   1
data area
1    2       4   8
• Try to access outside
valid data areas

Georgia Institute of Technology
An Array of Arrays
• Two-dimensional arrays are really an array
with other arrays inside of it
– Table in a table
• You can get the length of the outside array
– number of rows
– array.length
• You can get the length of the inner array
– number of columns
– array[0].length
Georgia Institute of Technology
Nested Loop
• How would you get all the pixels in a
picture using their x and y values
– From left to right and top to bottom?
– x=0 and y=0, x=1 and y=0, x=2 and y=0, …
– x=0 and y=1, x=1 and y=1, x=2 and y=1, …
– x=0 and y=2, x=1 and y=2, x=2 and y=2, …
• We need to have one loop inside another
– The outer loop counts y from 0 to height - 1
– The inner loop counts x from 0 to width - 1
Georgia Institute of Technology
Alternative Nested Loop
• How would you get all the pixels in a
picture using their x and y values
– From top to bottom and left to right?
– x=0 and y=0, x=0 and y=1, x=0 and y=2, …
– x=1 and y=0, x=1 and y=1, x=1 and y=2, …
– x=2 and y=0, x=2 and y=1, x=2 and y=2, …
• We need to have one loop inside another
– The outer loop counts x to width - 1
– The inner loop counts y from 0 to height - 1
Georgia Institute of Technology
Lighten the Color Algorithm
• Start x at 0 and loop while x < the picture
width (add 1 to x at the end of each loop)
– Start y at 0 and loop while y < the picture
height (add 1 to y at the end of each loop)
•   Get the pixel at this location
•   Get the color at the pixel
•   Lighten (brighten) the color
•   Set the color for the pixel to the lighter color

Georgia Institute of Technology
Lighten the Color with a Nested Loop
public void lighten()
{
Pixel pixelObj = null;
Color colorObj = null;

// loop through the columns (x direction)
for (int x = 0; x < this.getWidth(); x++)
{

// loop through the rows (y direction)
for (int y = 0; y < this.getHeight(); y++)
{                   Georgia Institute of Technology
Lighten - Continued
// get pixel at the x and y location
pixelObj = this.getPixel(x,y);

// get the current color
colorObj = pixelObj.getColor();

// get a lighter color
colorObj = colorObj.brighter();

// set the pixel color to the lighter color
pixelObj.setColor(colorObj);
}
}
}
Georgia Institute of Technology
Trying the Lighten Method
• In the interactions pane:
String file =
“c:/intro-prog-
java/mediasources/caterpillar.jpg”;
Picture p1 = new Picture(file);
p1.explore();
p1.lighten();
p1.explore();

Georgia Institute of Technology
Changing to Nested Loop Exercise
• Change the method
clearBlue() to use a
nested for loop to
loop through all the
pixels
• Run the method again
to check that it still
works
• Check that the blue
values are all 0 using
pictureObj.explore()

Georgia Institute of Technology
Vertical Mirroring
• What if we want to
pretend to place a
mirror in the middle of
the picture
– We would see the left
side of the picture
mirrored on the right
side

Georgia Institute of Technology
Mirror Vertical Algorithm
• Loop through all the rows                1         2      3   4   5
(y starts at 0, increments
by 1, and is less than the
picture height)                          5         4      3   2   1
– Loop with x starting at 1
and x less than the                   1         2      3   4   5
midpoint (mirror point)
value
• Get the left pixel at
midpoint – x                      1         2      3   2   1
• Get the right pixel at
midpoint + x
• Set the color for the right
5         4      3   4   5
pixel to be the color of the
left pixel
1         2      3   2   1

Georgia Institute of Technology
Mirror Vertical Algorithm to Code
• We are going to need the midpoint
int midpoint = getWidth() / 2;
• Loop through the rows (y values)
for (int y = 0; y < getHeight(); y++) {
– Loop through x values (starting at 1)
for (int x = 1; x < midpoint; x++) {
• Set right pixel color to left pixel color
Pixel leftPixel = getPixel(midpoint – x, y);
Pixel rightPixel = getPixel(midpoint + x, y);
rightPixel.setColor(leftPixel.getColor());

Georgia Institute of Technology
Mirror Vertical Method
public void mirrorVertical()
{
int mirrorPoint = (int) (this.getWidth() / 2);
Pixel leftPixel = null;
Pixel rightPixel = null;

// loop through the rows
for (int y = 0; y < this.getHeight(); y++)
{
// loop from 1 to just before the mirror point
for (int x = 1; x < mirrorPoint; x++)
{

Georgia Institute of Technology
Mirror Vertical Method - Continued
leftPixel = this.getPixel((mirrorPoint - x), y);
rightPixel = this.getPixel((mirrorPoint + x), y);
rightPixel.setColor(leftPixel.getColor());
}
}
}

Georgia Institute of Technology
Using Picture.getMediaPath(fileName)
• Gets the full path name for the file with the
passed short name
– redMotorcycle.jpg
• Defaults to using the directory
– c:\intro-prog-java\mediasources\
• Set it to a directory using
– Picture.setMediaPath(“c:/book/media/");

Georgia Institute of Technology
Trying Mirror Vertical
• Create the picture
– Picture p1 = new Picture(
FileChooser.getMediaPath(“caterpillar.jpg”);
• Invoke the method on the picture
– p1.mirrorVertical();
• Show the picture
– p1.show();

Georgia Institute of Technology
Mirror Horizontal
• What about mirroring
around a mirror held
horizontally in the
vertical center of the
picture?
– Like a reflection in a
lake?

Georgia Institute of Technology
Mirror Horizontal Algorithm
• Get the vertical midpoint
– Picture height / 2                            1      2   3
• Loop through all the x                          4      5   6
values
– Loop from y=1 to y <                          7      8   9
vertical midpoint
• Get the top pixel                          1      2   3
– Vertical midpoint - y
• Get the bottom pixel                       4      5   6
– Vertical midpoint + y
• Set the bottom pixel’s color
1      2   3
to the top pixel color

Georgia Institute of Technology
Mirror Horizontal Exercise
• Write the method to
mirror the top half of
the picture to the
bottom half.
– This is a motorcycle
redMotorcycle.jpg
• How about mirroring
bottom to top?

Georgia Institute of Technology
Copying Pixels to a New Picture
• Need to track the
source picture x and y
1        2
– And the target picture
x and y                                 3        4
• We can use a blank
picture
– As the target picture
1          2
• Several blank pictures
3          4
are available
– 640x480.jpg
– 7inX95in.jpg
Georgia Institute of Technology
Copy Picture Algorithm
• Copy a picture to the 7 by 9.5 inch blank
picture
– Create the target picture object
– Invoke the method on the target picture
– Create the source picture object
– Loop through the source picture pixels
• Get the source and target pixels
• Set the color of the target pixel to the color
of the source pixel

Georgia Institute of Technology
Copy Algorithm to Code
• Loop through the source pixels
// loop through the columns
for (int sourceX = 0, targetX = 0;
sourceX < sourcePicture.getWidth();
sourceX++, targetX++)
{

// loop through the rows
for (int sourceY = 0, targetY = 0;
sourceY < sourcePicture.getHeight();
sourceY++, targetY++)
{
Georgia Institute of Technology
Copy Algorithm to Code – Cont
• Get the source and target pixels
sourcePixel =
sourcePicture.getPixel(sourceX,sourceY);
targetPixel = this.getPixel(targetX,targetY);

• Set the color of the target pixel to the
color of the source pixel
targetPixel.setColor(sourcePixel.getColor());

Georgia Institute of Technology
Copy Method
public void copyKatie()
{
String sourceFile =
FileChooser.getMediaPath("KatieFancy.jpg");
Picture sourcePicture = new Picture(sourceFile);
Pixel sourcePixel = null;
Pixel targetPixel = null;

// loop through the columns
for (int sourceX = 0, targetX = 0;
sourceX < sourcePicture.getWidth();
sourceX++, targetX++)
{

Georgia Institute of Technology
Copy Method - Continued
// loop through the rows
for (int sourceY = 0, targetY = 0;
sourceY < sourcePicture.getHeight();
sourceY++, targetY++)
{

// set the target pixel color to the source pixel color
sourcePixel = sourcePicture.getPixel(sourceX,sourceY);
targetPixel = this.getPixel(targetX,targetY);
targetPixel.setColor(sourcePixel.getColor());
}
}
}

Georgia Institute of Technology
Trying the copyKatie Method
• Create a picture object using the 7inX95in.jpg
file in the mediasources directory
– Picture p1 = new
Picture(FileChooser.getMediaPath(“7inX95in.jpg”));
• Show the picture
– p1.show();
• Invoke the method on this picture object
– p1.copyKatie();
• Repaint the picture
– p1.repaint();

Georgia Institute of Technology
Result of copyKatie Method

Georgia Institute of Technology
Copy to an Upper Left Location
• How would you copy                      100, 100
a picture to a location
in another picture (like
100, 100)?
– Specified as the upper
left corner
• You still copy all the
source pixels
– But the target x and y
start at the specified
location

Georgia Institute of Technology
Copy to Position Exercise
• Write a method
copyRobot to copy
– robot.jpg
– To location
• 100, 100 in 7inx95in.jpg
• Test with
String file =
FileChooser.getMediaPath(
“7inx95in.jpg”);
Picture p = new Picture(file);
p.copyRobot();
p.show();

Georgia Institute of Technology
Cropping
• We can copy just part of a picture to a new
picture
– Just change the start and end source x and y
values to the desired values
– Use picture.explore() to find the x and y
values
– What are the x and y values to get the face of
the girl in KatieFancy.jpg?

Georgia Institute of Technology
Copy Face Method
public void copyKatiesFace()
{
String sourceFile =
FileChooser.getMediaPath("KatieFancy.jpg");
Picture sourcePicture = new Picture(sourceFile);
Pixel sourcePixel = null;
Pixel targetPixel = null;

// loop through the columns
for (int sourceX = 70, targetX = 100;
sourceX < 135; sourceX++, targetX++)
{
// loop through the rows
for (int sourceY = 3, targetY = 100;
sourceY < 80; sourceY++, targetY++)
{

Georgia Institute of Technology
Copy Face Method - Continued
// set the target pixel color to the source pixel color
sourcePixel =
sourcePicture.getPixel(sourceX,sourceY);
targetPixel = this.getPixel(targetX,targetY);
targetPixel.setColor(sourcePixel.getColor());
}
}
}

Georgia Institute of Technology
Testing Copy Kaite’s Face
• Create a picture object
– Picture p1 = new
Picture(FileChooser.getMediaPath(
“7inX95in.jpg”));
• Show the picture
– p1.show();
• Invoke the method
– p1.copyKatiesFace();
• Repaint the picture
– p1.repaint();

Georgia Institute of Technology
What makes a Good Method?
• A method should do one and only one thing
– Accomplish some task
– The name should tell you what it does
• A method can call other methods to do some of
the work
– Procedural decomposition
• We shouldn’t copy code between methods
– We should make general methods that are reusable
• A method should be in the class that has the
data the method is working on
Georgia Institute of Technology
Where the last two methods general?
• We specified the file to copy from in the
method
– Meaning we would need to change the
method
– or make another method
– to copy a different picture

Georgia Institute of Technology
General Copy Algorithm
• Create a method that copies pixels from a
passed source picture
– Giving a start x and y and end x and y for the
source picture
• If the start x and y and end x and y cover the entire
picture then the whole picture will be copied
• If the start x and y and end x and y are part of the
picture then cropping will occur
– To the current picture object with a target start
x and target start y
• If the start x and y are 0 then it copies to the upper
left corner
Georgia Institute of Technology
General Copy Algorithm
• Loop through the x values between xStart
and xEnd (inclusive)
– Loop through the y values between yStart and
yEnd (inclusive)
• Get the pixel from the source picture for the current
x and y values
• Get the pixel from the target picture for the
targetStartX + x and targetStartY + y values
• Set the color in the target pixel to the color in the
source pixel

Georgia Institute of Technology
General Copy Method
public void copy(Picture sourcePicture, int startX, int startY,
int endX, int endY, int targetStartX, int targetStartY)
{
Pixel sourcePixel = null;
Pixel targetPixel = null;

// loop through the x values
for (int x = startX, tx = targetStartX;
x < endX && x < sourcePicture.getWidth() &&
tx < this.getWidth();
x++, tx++)
{
// loop through the y values
for (int y = startY, ty = targetStartY;
y < endY && y < sourcePicture.getHeight() &&
ty < this.getHeight();
y++, ty++)
{                        Georgia Institute of Technology
General Copy Method - Continued
// copy the source color to the target color
sourcePixel = sourcePicture.getPixel(x,y);
targetPixel = this.getPixel(tx,ty);
targetPixel.setColor(sourcePixel.getColor());
}
}
}

Georgia Institute of Technology
Rewrite Methods Exercise
• Type the copy
method in
Picture.java
• Rewrite copyKatie()
and copyKatiesFace()
methods to use the
new copy method
• Run the methods to
make sure they still
work

Georgia Institute of Technology
Left Rotation
0           1       2
• To rotate an image
left 90 degrees still                        0
1           2       3
copy all the pixels
1     4           5       6
– But they go to different
locations in the target
• Column values become                                     0           1
row values
• target x = source y                              0   3           6
• target y = source width -
1 – source x                                     1   2           5

2   1           4

Georgia Institute of Technology
Left Rotation Algorithm
•   Create the target picture object
•   Invoke the method on the target picture
•   Create the source picture object
•   Loop through the source x (0-width-1)
– Loop through the source y (0-height-1)
• Get the source pixel at the x and y values
• Get the target pixel with the x equal the source y
value and the y equal the source picture width – 1
minus the source x
• Copy the color from the source pixel to the target
pixel

Georgia Institute of Technology
Left Rotation Method
public void copyKatieLeftRotation()
{
String sourceFile =
FileChooser.getMediaPath("KatieFancy.jpg");
Picture sourcePicture = new Picture(sourceFile);
Pixel sourcePixel = null;
Pixel targetPixel = null;

// loop through the columns
for (int sourceX = 0;
sourceX < sourcePicture.getWidth();
sourceX++)
{
Georgia Institute of Technology
Testing Left Rotation
• String file = FileChooser.getMediaPath(
“7inX95in.jpg”);
•   Picture p = new Picture(file);
•   p.show();
•   p.copyKatieLeftRotation();
•   p.repaint();

Georgia Institute of Technology
Copy Katie Left Rotation
// loop through the rows
for (int sourceY = 0;
sourceY < sourcePicture.getHeight();
sourceY++)
{
// set the target pixel color to the source pixel color
sourcePixel =
sourcePicture.getPixel(sourceX,sourceY);
targetPixel = this.getPixel(sourceY,
sourcePicture.getWidth() - 1 - sourceX);
targetPixel.setColor(sourcePixel.getColor());
}
}
}

Georgia Institute of Technology
Right Rotation
0           1       2
• To rotate an image
right 90 degrees still                       0
1           2       3
copy all the pixels
1     4           5       6
– But they go to different
locations in the target
• Column values become                                     0           1
row values
• target y = source x                              0   4           1
• target x = source height
– 1 – source y                                   1   5           2

2   6           3

Georgia Institute of Technology
Right Rotation Exercise
• Write the method to
rotate the picture of Katie
to the right instead of to
the left
• Try out the method
String file =
FileChooser.getMediaPath(
“7inX95in.jpg”);
Picture p = new Picture(file);
p.show();
p.copyKatieRIghtRotation();
p.repaint();
• Can you make the
method more general?
– To work on any picture?

Georgia Institute of Technology
Scaling
• You can make a picture smaller
– Faster to download on the web
• Increment the source x and y by a number larger
than 1
– Don’t use all the source pixels in target

• You can make a picture larger
• Copy the same source x and y to more than one
target x and y
– Use source pixels more than once in target

Georgia Institute of Technology
Scaling Down the a Picture
• passionFlower.jpg is
640pixels wide and
480 pixels high
• If we copy every other
pixel we will have a
new picture with width 0              1         2    3
(640 / 2 = 320) and                                     0   2
4              5         6    7
height (480 / 2 = 240) 8                                8   10
9         10   11
12             13        14   15

Georgia Institute of Technology
Scaling Down Algorithm
•   Create the target picture
•   Invoke the method on the target picture
•   Create the source picture
•   Loop with source x starting at 0 and target x
starting at 0 as long as < source width
– Increment the source x by 2 each time through the
loop, increment the target x by 1
– Loop with source y starting at 0 and target y starting
at 0 as long as < source height
• Increment the source y by 2 each time through the loop,
increment the target y by 1
– Copy the color from the source to target pixel

Georgia Institute of Technology
Scaling Down Method
public void copyFlowerSmaller()
{
Picture flowerPicture =
new Picture(
FileChooser.getMediaPath(“passionFlower.jpg"));
Pixel sourcePixel = null;
Pixel targetPixel = null;

// loop through the columns
for (int sourceX = 0, targetX=0;
sourceX < flowerPicture.getWidth();
sourceX+=2, targetX++)
{
Georgia Institute of Technology
Scaling Down Method - Continued
// loop through the rows
for (int sourceY=0, targetY=0;
sourceY < flowerPicture.getHeight();
sourceY+=2, targetY++)
{
sourcePixel =
flowerPicture.getPixel(sourceX,sourceY);
targetPixel = this.getPixel(targetX,targetY);
targetPixel.setColor(sourcePixel.getColor());
}
}
}
Georgia Institute of Technology
Trying Copy Flower Smaller
• Create a new picture half the size of the
original picture + 1
– Picture p1 = new Picture(320,240);
• Copy the flower to the new picture
– p1.copyFlowerSmaller();
• Show the result
– p1.show();

Georgia Institute of Technology
Thinking Through Scaling Up
• Copy each pixel in the                               0   1       2
source multiple times to                    0        1   2       3
the target                                  1        4   5       6
–   Source (0,0) Target (0,0)
–   Source (0,0) Target(1,0)                    0    1   2   3       4   5

–   Source (1,0) Target(2,0)            0    1 1 2 2 3 3
–   Source (1,0) Target(3,0)            1    1 1 2 2 3 3
–   Source (2,0) Target(4,0)
–   Source (2,0) Target(5,0)
2    4 4 5 5 6 6
–   Source (0,0) Target(0,1)            3    4 4 5 5 6 6
–   Source (0,0) Target(1,1)
Georgia Institute of Technology
Scaling Up Algorithm
•   Create the target picture
•   Invoke the method on the target picture
•   Create the source picture
•   Loop with source x starting at 0 and target x
starting at 0 as long as < source width
– Increment the source x by 0.5 each time through the
loop, increment the target x by 1
– Loop with source y starting at 0 and target y starting
at 0 as long as < source height
• Increment the source y by 0.5 each time through the loop,
increment the target y by 1
– Copy the color from the source to target pixel

Georgia Institute of Technology
Scaling Up Exercise
• Write a method
(copyFlowerBigger) to
scale up the picture
flower1.jpg when you
copy it to 640x480.jpg
• Save the result to a
file using
– pictureObj.write(“file”);

Georgia Institute of Technology
Create a Collage
• One of the things that
you can do with
pictures is create a
collage
– There are two pictures
of flowers
• flower1.jpg
• flower2.jpg
– Both pictures are 100
pixels wide
The Picture’s bottom
– The target picture is             left is at x = 0 y =
created from file                 height - 5
640x480.jpg
Georgia Institute of Technology
Create Collage Algorithm
• Create the target picture object
– Using the 640x480 file
• Invoke the method on the target picture
• Create the flower picture objects
– using flower1.jpg as source1Picture
– using flower2.jpg as source2Picture
• Set targetStartX to 0
• Set targetBottomY to the targetPicture height – 5
– 5 pixels from bottom of picture

Georgia Institute of Technology
Create Collage Algorithm - Cont
•   Copy from source1Picture to the targetPicture starting at (0,0) ending at
(width-1,height-1) to targetPicture (targetStartX,targetBottomY - height)
•   Add the width of source1Picture to targetStartX
•   Copy from source2Picture to the targetPicture starting at (0,0) ending at
(width-1,height-1) to targetPicture(targetStartX,targetBottomY - height)
•   Add the width of source2Picture to targetStartX
•   Negate source1Picture
•   Copy from source1Picture to the targetPicture starting at (0,0) ending at
(width-1,height-1) to targetPicture(targetStartX,targetBottomY - height)
•   Add the width of source2Picture to targetStartX
•   Clear the blue from source2Picture
•   Copy from source2Picture to the targetPicture starting at (0,0) ending at
(width-1,height-1) to targetPicture(targetStartX,targetBottomY - height)
•   Add the width of source2Picture to targetStartX
•   Copy from source1Picture to the targetPicture starting at (0,0) ending at
(width-1, height-1) to targetPicture(targetStartX,targetBottomY - height)

Georgia Institute of Technology
Create Collage Exercise
• Try creating a collage
– At least 4 copies of an
image in it
– The original image and 3
changes to the original
image
• Scale, rotate, crop,
change colors
– Then mirror the whole
picture horizontally
– Save your collage using
• pictureObj.write(fileName);

Georgia Institute of Technology
Summary
• A two-dimensional array has rows and
columns
• Use nested loops to work with 2-d arrays
– One loop inside of another’s block
• Write methods so that they can be reused
– Do one and only one thing
– Take parameters to make them more
reusable

Georgia Institute of Technology

```
DOCUMENT INFO
Shared By:
Categories:
Stats:
 views: 357 posted: 1/5/2010 language: English pages: 66
How are you planning on using Docstoc?