CS 106A, Lecture 18 Practice with 1D and 2D Arrays · 2017-07-27 · 3 Plan for Today •Recap: 2D...

38
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others. CS 106A, Lecture 18 Practice with 1D and 2D Arrays

Transcript of CS 106A, Lecture 18 Practice with 1D and 2D Arrays · 2017-07-27 · 3 Plan for Today •Recap: 2D...

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

CS106A,Lecture18Practicewith1Dand2DArrays

2

Midterm!Arrays

HW5:ImageShop

Wearehere

3

Plan for Today•Recap:2DArraysandImages•Practice:Shrink•Practice:Histogram•Practice:Tic-Tac-Toe

4

Plan for Today•Recap:2DArraysandImages•Practice:Shrink•Practice:Histogram•Practice:Tic-Tac-Toe

5Imageusedunder“fairuse”foreducationalpurposes.Source:https://www.themarysue.com/decoding-the-transgender-matrix-the-matrix-as-a-transgender-coming-out-story/

The Matrix

6

2D Arrays (“Matrices”)

7

2D Arraystype[][] name = new type[rows][columns];

int[][] a = new int[3][5];

0 1 2 3 4

0 a[0][0] a[0][1] a[0][2] a[0][3] a[0][4]

1 a[1][0] a[1][1] a[1][2] a[1][3] a[1][4]

2 a[2][0] a[2][1] a[2][2] a[2][3] a[2][4]

8

2D Arrays = Arrays of Arrays!int[][] a = new int[3][4];int[] firstRow = a[0];

a[0][0] a[0][1] a[0][2] a[0][3]

a[1][0] a[1][1] a[1][2] a[1][3]

a[2][0] a[2][1] a[2][2] a[2][3]

9

Summary: 2D Arrays• Makeanew2Darray

type[][] name = new type[rows][columns];

• Getandsetvaluesusingbracketnotationname[row][col] // get elem at row,colname[row][col] = value; // set elem at row,col

• Getthenumberofrowsandcolumnsarr.length // # rowsarr[0].length // # columns

• Iterateovera2Darrayusingadoublefor-loopfor (int row = 0; row < arr.length; row++) {

for (int col = 0; col < arr[0].length; col++) {// do something with arr[row][col];

}}

10

Limitations of 2D Arrays• Unlike1Darrays,youcannotcompare2DarrayswithArrays.equals.YoumustuseArrays.deepEquals.

int[][] a1 = ...int[][] a2 = ...if (Arrays.deepEquals(a1, a2)) { ... }

• A2Darraydoesnotknowhowtoprintitself:int[][] a = new int[rows][cols];println(a); // [[I@8cf420println(Arrays.toString(a)); // [[I@6b3f44,[I@32c2a8]...

// [[0, 1, 2, 3, 4], [1, 2, ...println(Arrays.deepToString(a));

11

Images

Imagesarejustgrids(2Darrays!)ofpixels!Pixelsarejustintegervaluesfrom0-255.

12

Images as 2D ArraysWecangetaGImage asa2Darrayofpixels.

GImage img = new GImage(“res/daisy.jpg”);int[][] pixels = img.getPixelArray();int pixel = pixels[0][0]; // top-left pixel

13

Example: PointillismPointillismisanartstylewheremanysmalldotsofcolorarecombinedtomakealargerimage.

14

Red, Green and Blue in one int?

Imagesencode theR,G,andBvaluesofapixelintoasingleintegerbetween0and255.YoucanconvertbetweenthispixelvalueandtheindividualRGBvalues.

int[][] pixels = image.getPixelArray();int px = pixels[0][0];int red = GImage.getRed(px);int green = GImage.getGreen(px); int blue = GImage.getBlue(px);

15

Creating New PixelsImagesencode theR,G,andBvaluesofapixelintoasingleintegerbetween0and255.YoucanconvertbetweenthispixelvalueandtheindividualRGBvalues.

YoucanalsocreatepixelswithyourownRGBvalues.

int r = ...int g = ...int b = ...int pixel = GImage.createRGBPixel(r, g, b);

16

Images as 2D ArraysWecangetaGImage asa2Darrayofpixels,andmodifyitanywaywewant.Then,wecancreateanewGImage withthemodifiedpixels.

GImage img = new GImage(“res/daisy.jpg”);int[][] pixels = img.getPixelArray();... (modify pixels)img.setPixelArray(pixels); // update image

// or make a new GImageGImage newImg = new GImage(pixels);

17

Modifying Image Pixels• Therearemanycoolimagealgorithmsbasedaroundmodifyingindividualpixelsinanimage:grayscale,brighten,normalize,removered-eye…

grayscale zoom

18

GImage Pixel MethodsGImage img = new GImage("res/daisy.jpg");

Methodname Descriptionimg.getPixelArray() returnspixelsas2Darrayofints,where

eachintinthearraycontainsall3ofRed,Green,andBluemergedintoasingleinteger

img.setPixelArray(array); updatespixelsusingthegiven2Darrayofints

GImage.createRGBPixel(r, g, b) returnsanintthatmergesthegivenamountsofred,greenandblue(each0-255)

GImage.getRed(px)GImage.getGreen(px)GImage.getBlue(px)

returnstheredness,greenness,orbluenessofthegivenpixelasanintegerfrom0-255

19

Recap: Modifying Pixels• Extract pixelRGBcolorswithGImage.getRed/Blue/Green.

int red = GImage.getRed(pixels[0][0]); // 0-255int green = GImage.getGreen(pixels[0][0]); // 0-255int blue = GImage.getBlue(pixels[0][0]); // 0-255

• Modify thecolorcomponentsforagivenpixel.red = 0; // remove redness

• Combine theRGBbacktogetherintoasingleint.pixels[0][0] = GImage.createRGBPixel(red, green, blue);

• Update theimagewithyourmodifiedpixelswhenfinished.image.setPixelArray(pixels);

20

Plan for Today•Recap:2DArraysandImages•Practice:Shrink•Practice:Histogram•Practice:Tic-Tac-Toe

21

ShrinkLet’swriteaprogramthatcanshrink animageto½itsoriginalsize.

22

Shrink

23

Shrink

24

ShrinkGivenapixel(x,y)inoursmallerimage,howdoweknowwhichpixelinourlargerimageshouldgothere?

25

Shrink

(0 ,0) (0,2)

(2,0) (2,2)

(0,0) (0, 1)

(1,0) (1, 1)

Givenapixel(x,y)inoursmallerimage,howdoweknowwhichpixelinourlargerimageshouldgothere?

26

ShrinkGivenapixel(x,y)inoursmallerimage,howdoweknowwhichpixelinourlargerimageshouldgothere?

27

Shrinkint[][] pixels = image.getPixelArray();int[][] result =

new int[pixels.length/2][pixels[0].length/2];

for (int r = 0; r < result.length; r++) {for (int c = 0; c < result[0].length; c++) {

result[r][c] = pixels[r*2][c*2];}

}

image.setPixelArray(result);

28

Shrinkint[][] pixels = image.getPixelArray();int[][] result =

new int[pixels.length/2][pixels[0].length/2];

for (int r = 0; r < result.length; r++) {for (int c = 0; c < result[0].length; c++) {

result[r][c] = pixels[r*2][c*2];}

}

image.setPixelArray(result);

29

Shrinkint[][] pixels = image.getPixelArray();int[][] result =

new int[pixels.length/2][pixels[0].length/2];

for (int r = 0; r < result.length; r++) {for (int c = 0; c < result[0].length; c++) {

result[r][c] = pixels[r*2][c*2];}

}

image.setPixelArray(result);

30

Shrinkint[][] pixels = image.getPixelArray();int[][] result =

new int[pixels.length/2][pixels[0].length/2];

for (int r = 0; r < result.length; r++) {for (int c = 0; c < result[0].length; c++) {

result[r][c] = pixels[r*2][c*2];}

}

image.setPixelArray(result);

31

Shrinkint[][] pixels = image.getPixelArray();int[][] result =

new int[pixels.length/2][pixels[0].length/2];

for (int r = 0; r < result.length; r++) {for (int c = 0; c < result[0].length; c++) {

result[r][c] = pixels[r*2][c*2];}

}

image.setPixelArray(result);

32

Shrinkint[][] pixels = image.getPixelArray();int[][] result =

new int[pixels.length/2][pixels[0].length/2];

for (int r = 0; r < result.length; r++) {for (int c = 0; c < result[0].length; c++) {

result[r][c] = pixels[r*2][c*2];}

}

image.setPixelArray(result);

33

Plan for Today•Recap:2DArraysandImages•Practice:Shrink•Practice:Histogram•Practice:Tic-Tac-Toe

34

Givenafileoftemperatures(int),suchas:8266796383

WriteaHistogram programthatwillprintahistogramofstarsindicatingthe#ofdayswitheachuniquetemperature.

85: *****86: ************87: ***88: *

Weather Histogram

35

Idea: Array of Counters• Forproblemslikethis,wherewewanttokeepcountofmanythings,afrequencytable(ortallyarray)canbeacleversolution.– Idea: Theelementatindexi willstoreacounterforthedigitvaluei.

– example:countoftemperatures:

index … 55 56 57 58 59 60 61 62 …

value 1 0 4 1 0 0 1 1

36

Plan for Today•Recap:2DArraysandImages•Practice:Shrink•Practice:Histogram•Practice:Tic-Tac-Toe

37

Tic-Tac-ToeLet’suse2DarraystocreateaConsoleProgram versionofTic-Tac-Toe.

38

Recap•Recap:2DArraysandImages•Practice:Shrink•Practice:Histogram•Practice:Tic-Tac-Toe

NextTime:Moredatastructures