CS 112 Introduction to Programming Reference Semantics 2


![Recap: Arrays q Declare an array, e. g. , int[] numbers = new int[10]; Recap: Arrays q Declare an array, e. g. , int[] numbers = new int[10];](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-3.jpg)

![Array Return (declare) public static <type>[] <method>(<parameters>) { q Example: // Returns a new Array Return (declare) public static <type>[] <method>(<parameters>) { q Example: // Returns a new](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-5.jpg)
![Array Return (call) <type>[] <name> = <method>(<parameters>); q Example: public class My. Program { Array Return (call) <type>[] <name> = <method>(<parameters>); q Example: public class My. Program {](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-6.jpg)






![Motivation: Primitive swap public static void main(String[] args) { int a = 1; int Motivation: Primitive swap public static void main(String[] args) { int a = 1; int](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-13.jpg)
![Motivation: Array Reversal public static void main(String[] args) { int[] a = {1, 2}; Motivation: Array Reversal public static void main(String[] args) { int[] a = {1, 2};](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-14.jpg)







![Array Passed as Parameter public static void main(String[] args) { int[] iq = {120, Array Passed as Parameter public static void main(String[] args) { int[] iq = {120,](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-22.jpg)




![Why it does not work? Init. public static void main(String[] args) { int[] a Why it does not work? Init. public static void main(String[] args) { int[] a](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-27.jpg)
![Why it does not work? Invoke public static void main(String[] args) { int[] a Why it does not work? Invoke public static void main(String[] args) { int[] a](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-28.jpg)
![Why it does not work? Invoke public static void main(String[] args) { int[] a Why it does not work? Invoke public static void main(String[] args) { int[] a](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-29.jpg)
![Why it does not work? Swap (temp = a 1) public static void main(String[] Why it does not work? Swap (temp = a 1) public static void main(String[]](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-30.jpg)

![Why it does not work? Swap (a 2 = temp) public static void main(String[] Why it does not work? Swap (a 2 = temp) public static void main(String[]](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-32.jpg)
![Why it does not work? After swap. All public static void main(String[] args) { Why it does not work? After swap. All public static void main(String[] args) {](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-33.jpg)

![Understanding Two Dimensional Array: An Array of Arrays int[][] table = new int[3][4]; for Understanding Two Dimensional Array: An Array of Arrays int[][] table = new int[3][4]; for](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-35.jpg)
![Irregular Two-Dimensional Array int[][] table = { {1, 2, 3, 4}, {5, 6, 7}, Irregular Two-Dimensional Array int[][] table = { {1, 2, 3, 4}, {5, 6, 7},](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-36.jpg)
![Initializer: Example public class Test 2 DArray { public static void main(String[] args) { Initializer: Example public class Test 2 DArray { public static void main(String[] args) {](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-37.jpg)









![Exercise: Excel Style q Buckets specified in an array m [59, 75, 85, 90] Exercise: Excel Style q Buckets specified in an array m [59, 75, 85, 90]](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-47.jpg)


![Array Elements as Counters r Count the number of characters in a line: int[] Array Elements as Counters r Count the number of characters in a line: int[]](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-50.jpg)
![Array Index to Display public static void histogram(int[] counts) { int max = max(counts); Array Index to Display public static void histogram(int[] counts) { int max = max(counts);](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-51.jpg)





![Coupon-Collector Problem public class Coupon. Collector { public static void main(String[] args) { int Coupon-Collector Problem public class Coupon. Collector { public static void main(String[] args) { int](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-57.jpg)





![Array Variables are Reference Variables int[] a 1 = {4, 15, 8}; int[] a Array Variables are Reference Variables int[] a 1 = {4, 15, 8}; int[] a](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-63.jpg)
![Recap: Page. Rank [Sergey Brin and Larry Page, 1998] q Problem: many Web pages Recap: Page. Rank [Sergey Brin and Larry Page, 1998] q Problem: many Web pages](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-64.jpg)






![Page. Rank: Compute Rank double[] pr = new double[N]; pr[0] = 1; // initialize Page. Rank: Compute Rank double[] pr = new double[N]; pr[0] = 1; // initialize](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-71.jpg)
- Slides: 71

CS 112 Introduction to Programming Reference Semantics; 2 D Arrays; Array as State Yang (Richard) Yang Computer Science Department Yale University 308 A Watson, Phone: 432 -6400 Email: yry@cs. yale. edu

Admin q Exam 1 m Max: 50 m Avg/median: 32 q Overall course grade 2
![Recap Arrays q Declare an array e g int numbers new int10 Recap: Arrays q Declare an array, e. g. , int[] numbers = new int[10];](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-3.jpg)
Recap: Arrays q Declare an array, e. g. , int[] numbers = new int[10]; int[][] grid = new int[3][4]; char[] letter. Grades = {'A', 'B', 'C', 'D', 'F'}; q Access array elements, e. g. , numbers[1] = 3; numbers[2] = 2; numbers[2] ] = 42; Grid[1][2] = 3; q Pass arrays as parameters, e. g. , public static double average(int[] numbers) 3

Arrays class q Provides many useful methods that take an array as a parameter, e. g, m to. String(my. Array) // print array http: //download. oracle. com/javase/1. 5. 0/docs/api/java/util/Arrays. html 4
![Array Return declare public static type methodparameters q Example Returns a new Array Return (declare) public static <type>[] <method>(<parameters>) { q Example: // Returns a new](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-5.jpg)
Array Return (declare) public static <type>[] <method>(<parameters>) { q Example: // Returns a new array with two copies of each value. // Example: [1, 4, 0, 7] -> [1, 1, 4, 4, 0, 0, 7, 7] public static int[] stutter(int[] numbers) { int[] result = new int[2 * numbers. length]; for (int i = 0; i < numbers. length; i++) { result[2 * i] = numbers[i]; result[2 * i + 1] = numbers[i]; } return result; }
![Array Return call type name methodparameters q Example public class My Program Array Return (call) <type>[] <name> = <method>(<parameters>); q Example: public class My. Program {](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-6.jpg)
Array Return (call) <type>[] <name> = <method>(<parameters>); q Example: public class My. Program { public static void main(String[] args) { int[] iq = {126, 84, 149, 167, 95}; int[] stuttered = stutter(iq); System. out. print( Arrays. to. String( stuttered ) ); q Output: [126, 84, 149, 167, 95, 95]

Array Merge Question q Write a method merge that accepts two arrays of integers and returns a new array containing all elements of the first array followed by all elements of the second. int[] a 1 = {12, 34, 56}; int[] a 2 = {7, 8, 9, 10}; int[] a 3 = merge(a 1, a 2); System. out. println( Arrays. to. String(a 3) ); // [12, 34, 56, 7, 8, 9, 10]

Array Merge // Returns a new array containing all elements of a 1 // followed by all elements of a 2. public static int[] merge(int[] a 1, int[] a 2) { int[] result = new int[a 1. length + a 2. length]; for (int i = 0; i < a 1. length; i++) { result[i] = a 1[i]; } for (int i = 0; i < a 2. length; i++) { result[a 1. length + i] = a 2[i]; } return result; }

Array Merge 3 Question q Write a method merge 3 that merges 3 arrays similarly. int[] a 1 = {12, 34, 56}; int[] a 2 = {7, 8, 9, 10}; int[] a 3 = {444, 222, -1}; int[] a 4 = merge 3(a 1, a 2, a 3); System. out. println( Arrays. to. String(a 4) ); // [12, 34, 56, 7, 8, 9, 10, 444, 222, -1]

Array Merge 3 // Returns a new array containing all elements of a 1, a 2, a 3. public static int[] merge 3(int[] a 1, int[] a 2, int[] a 3) { int[] a 4 = new int[a 1. length + a 2. length + a 3. length]; for (int i = 0; i < a 1. length; a 4[i] = a 1[i]; } for (int i = 0; i < a 2. length; a 4[a 1. length + i] = a 2[i]; } for (int i = 0; i < a 3. length; a 4[a 1. length + a 2. length + } } i++) { i] = a 3[i]; return a 4; // Shorter version that calls merge. public static int[] merge 3(int[] a 1, int[] a 2, int[] a 3) { return merge(a 1, a 2), a 3); } Discussion: Which version do you use?

Complexity Analysis q V 1 m Creation of array (static complexity) • One array of size N 1 + N 2 + N 3 m Copy values (dynamic) • N 1 + N 2 + N 3 values q V 2 m Creation of array • First size N 1 + N 2; second size (N 1 + N 2) + N 3 m Copy values • First N 1 + N 2 • Then N 1 + N 2 + N 3

Value vs Reference Semantics
![Motivation Primitive swap public static void mainString args int a 1 int Motivation: Primitive swap public static void main(String[] args) { int a = 1; int](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-13.jpg)
Motivation: Primitive swap public static void main(String[] args) { int a = 1; int b = 2; System. out. println(a + " " + b); // ? swap(a, b); System. out. println(a + " " + b); // ? } public static void swap(int a, int b) { int temp = a; a = b; b = temp; System. out. println(a + " " + b); // ? }
![Motivation Array Reversal public static void mainString args int a 1 2 Motivation: Array Reversal public static void main(String[] args) { int[] a = {1, 2};](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-14.jpg)
Motivation: Array Reversal public static void main(String[] args) { int[] a = {1, 2}; System. out. println( Arrays. to. String(a) ); reverse(a); System. out. println( Arrays. to. String(a) ); } public static void reverse(int[] a) { for (int i = 0; i < a. length / 2; i++) { int temp = a[i]; a[i] = a[a. length-1 -i]; a[a. length-1 -i] = temp; }

Value Semantics and Reference Semantics q Primitive data types use value semantics: variable stores value int x = 5; x 5 q Non primitive data types (e. g. , arrays and objects) use reference semantics: variable stores reference address int[] a = {1, 2, 3}; 1 q See print. Variable() of Basic. Arrays. java 2 a Address of an array 3 15

References q Why reference variables m Efficiency. Copying large objects/arrays slows down a program m Sharing. It's useful to share an object/array's data among methods

Value/Reference Semantics and Assignment q When variable a is assigned to variable b: b = a the content of a is always copied to b m if a value type, then it is the value that is copied m if a reference type, then it is the reference that is copied, b becomes an alias of a 17

Value/Reference Semantics and Parameter Passing q Each time a method is called, the actual argument in the invocation is copied into the corresponding formal argument if a value type, then it is the value that is copied m if a reference type, then it is the reference that is copied m • The actual argument and the formal argument now refer to the same object • Modification in the method will affect the original object. 8 18

Example: Value Semantics q Modifying the value of one value variable does not affect others. int y = x = 5; y = x; 17; 8; // x = 5, y = 5 // x = 5, y = 17 // x = 8, y = 17 x 5 8 y 17 5

Example: Reference Semantics q Modifying an object/array through one reference variable changes the object/array and hence all references to the same object/array see the changes. int[] a 1 = {1, 2, 3}; int[] a 2 = a 1; // same array a 1 Address of array object 1 Content copied, but content is address 1 2 3 a 2 Address of array object 1 a 2[1] = 4;

Example: Reference Semantics q Modifying an object/array through one reference variable changes the object/array and hence all references to the same object/array see the changes. int[] a 1 = {1, 2, 3}; int[] a 2 = a 1; // same array a 1 Address of array object 1 Content copied, but content is address 1 4 3 a 2 Address of array object 1 a 2[1] = 4;
![Array Passed as Parameter public static void mainString args int iq 120 Array Passed as Parameter public static void main(String[] args) { int[] iq = {120,](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-22.jpg)
Array Passed as Parameter public static void main(String[] args) { int[] iq = {120, 160, 95}; double. Array(iq); System. out. println(Arrays. to. String(iq)); } iq 240 120 160 320 190 95 static void double. Array (int[] iqp) { for (int i = 0; i < iqp. length; i++) iqp[i] *= 2; iqp i } 22

Array Parameter Question q Write a method swap that accepts an array of integers and two indexes and swaps the elements at those indexes. int[] a 1 = {12, 34, 56}; swap(a 1, 1, 2); System. out. println(Arrays. to. String(a 1)); // [12, 56, 34]

Array Parameter // Swaps the values at the given two indexes. public static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; }

Array Parameter Question q Write a method swap. All that accepts two same-size arrays of integers as parameters and swaps their entire contents. Assume that the two arrays are the same length. int[] a 1 = {10, 11, 12}; int[] a 2 = {20, 21, 22}; swap. All(a 1, a 2); System. out. println(Arrays. to. String(a 1)); System. out. println(Arrays. to. String(a 2)); // [20, 21, 22] // [10, 11, 12]

Attempt 1 // Does this method swap the entire contents of // a 1 with those of a 2? public static void swap. All 1(int[] a 1, int[] a 2) { int[] temp = a 1; a 1 = a 2; a 2 = temp; } Array. Swap. java
![Why it does not work Init public static void mainString args int a Why it does not work? Init. public static void main(String[] args) { int[] a](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-27.jpg)
Why it does not work? Init. public static void main(String[] args) { int[] a 1 = {10, 11, 12}; int[] a 2 = {20, 21, 22}; a 1 } a 2 120 10 160 11 95 12 120 20 160 21 95 22 27
![Why it does not work Invoke public static void mainString args int a Why it does not work? Invoke public static void main(String[] args) { int[] a](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-28.jpg)
Why it does not work? Invoke public static void main(String[] args) { int[] a 1 = {10, 11, 12}; int[] a 2 = {20, 21, 22}; a 1 swap. All (a 1, a 2); } a 2 120 10 160 11 95 12 120 20 160 21 95 22 28
![Why it does not work Invoke public static void mainString args int a Why it does not work? Invoke public static void main(String[] args) { int[] a](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-29.jpg)
Why it does not work? Invoke public static void main(String[] args) { int[] a 1 = {10, 11, 12}; int[] a 2 = {20, 21, 22}; a 1 swap. All (a 1, a 2); } a 2 120 10 160 11 95 12 120 20 160 21 95 22 static void swap. All(int[] a 1, int[] a 2) { a 1 } a 2 29
![Why it does not work Swap temp a 1 public static void mainString Why it does not work? Swap (temp = a 1) public static void main(String[]](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-30.jpg)
Why it does not work? Swap (temp = a 1) public static void main(String[] args) { int[] a 1 = {10, 11, 12}; int[] a 2 = {20, 21, 22}; a 1 swap. All (a 1, a 2); } a 2 120 10 160 11 95 12 120 20 160 21 95 22 static void swap. All(int[] a 1, int[] a 2) { int[] temp = a 1; a 1 temp } a 2 30

Why it does not work? Swap (a 1 = a 2) public static void main(String[] args) { int[] a 1 = {10, 11, 12}; int[] a 2 = {20, 21, 22}; a 1 swap. All (a 1, a 2); } a 2 120 10 160 11 95 12 120 20 160 21 95 22 static void swap. All(int[] a 1, int[] a 2) { int[] temp = a 1; a 1 = a 2; } a 1 temp a 2 31
![Why it does not work Swap a 2 temp public static void mainString Why it does not work? Swap (a 2 = temp) public static void main(String[]](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-32.jpg)
Why it does not work? Swap (a 2 = temp) public static void main(String[] args) { int[] a 1 = {10, 11, 12}; int[] a 2 = {20, 21, 22}; a 1 swap. All (a 1, a 2); } a 2 120 10 160 11 95 12 120 20 160 21 95 22 static void swap. All(int[] a 1, int[] a 2) { int[] temp = a 1; a 1 = a 2; a 2 = temp; } a 1 temp a 2 32
![Why it does not work After swap All public static void mainString args Why it does not work? After swap. All public static void main(String[] args) {](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-33.jpg)
Why it does not work? After swap. All public static void main(String[] args) { int[] a 1 = {10, 11, 12}; int[] a 2 = {20, 21, 22}; a 1 swap. All (a 1, a 2); } a 2 120 10 160 11 95 12 120 20 160 21 95 22 33

Solution // Swaps the entire contents of a 1 with those of a 2. public static void swap. All(int[] a 1, int[] a 2) { for (int i = 0; i < a 1. length; i++) { int temp = a 1[i]; a 1[i] = a 2[i]; a 2[i] = temp; } }
![Understanding Two Dimensional Array An Array of Arrays int table new int34 for Understanding Two Dimensional Array: An Array of Arrays int[][] table = new int[3][4]; for](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-35.jpg)
Understanding Two Dimensional Array: An Array of Arrays int[][] table = new int[3][4]; for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) table[i][j] = i + j; table[ 0 ] ref to array 0 table[ 1 ] ref to array 1 table[ 2 ] ref to array 2 table 35
![Irregular TwoDimensional Array int table 1 2 3 4 5 6 7 Irregular Two-Dimensional Array int[][] table = { {1, 2, 3, 4}, {5, 6, 7},](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-36.jpg)
Irregular Two-Dimensional Array int[][] table = { {1, 2, 3, 4}, {5, 6, 7}, {8, 9}, {0} }; 1 2 3 4 table[ 0 ] ref to array 0 table[ 1 ] ref to array 1 5 table[ 2 ] ref to array 2 6 table[ 3 ] ref to array 3 7 8 9 0 36
![Initializer Example public class Test 2 DArray public static void mainString args Initializer: Example public class Test 2 DArray { public static void main(String[] args) {](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-37.jpg)
Initializer: Example public class Test 2 DArray { public static void main(String[] args) { int[][] days = { {1, 2, 3, 4}, {5, 6, 7}, {8, 9}, {0} }; for (int i = 0; i < days. length; i++) { for (int j = 0; j < days[i]. length; j++) System. out. print( days[i][j] ); System. out. println (); } } } 37

Roadmap: Arrays q Motivation, declaration, initialization, access q Reference semantics: arrays as objects q Example usage of arrays: m As counter (please read outside class) m As state 38

Using Array as Counters/Accumulators m Create an array equal to the size of the number of categories m Loop over each input • map input’s value to array index • increase the array element at index m Display result • Map each array index back to input to display 39

Grade Histogram Question q Given a file of integer exam scores, where a score is between 0 and 100, e. g. , 82 66 79 63 83 Write a program that will print a histogram of stars indicating the number of students who earned each unique exam score. 85: 86: 87: 88: 91: ************ * ****

Using Array as Counters/Accumulators q Create an array equal to the size of the number of categories m Q: how many categories? int[] counters = new int[101]; q Loop over each input m map input’s value to array index grade -> counters[grade] m increase the array element at index q Display result m Map each array index back to input to display 41

Grade Histogram // Reads a file of test scores and shows a histogram of the score distribution. import java. io. *; import java. util. *; public class Histogram { public static void main(String[] args) throws File. Not. Found. Exception { Scanner input = new Scanner(new File("midterm. txt")); int[] counts = new int[101]; // counters of test scores 0 - 100 while (input. has. Next. Int()) { int grade= input. next. Int(); counts[grade]++; } // read file into counts array // if gradeis 87, then counts[87]++ for (int i = 0; i < counts. length; i++) { // print star histogram if (counts[i] > 0) { System. out. printf( “%3 d: ”, i); for (int j = 0; j < counts[i]; j++) { System. out. print("*"); } System. out. println(); } }

Revision q How about a bucket for every 5 points: m 00 -04: m 05 -09: m. . m 90 -94: m 95 -99: m 100: 43

Using Array as Counters/Accumulators q Create an array equal to the size of the number of categories m Q: how many categories? int[] counters = new int[100/5+1]; q Loop over each input m map input’s value to array index grade -> counters[grade/5] m increase the array element at index q Display result m Map each array index back to input to display [index * 5, index*5+4] 44

Revision q How about the following buckets: m 00 -59: m 60 -64: m 65 -69: m 70 -74: m… m 90 -94: m 95 -99: m 100: 45

Using Array as Counters/Accumulators q Create an array equal to the size of the number of categories m Q: how many categories? int[] counters = new int[1+(100 -60)/5+1]; q Loop over each input m map input’s value to array index if (grade < 60) index = 0; else index = (grade-60) / 5 + 1; m increase the array element at index q Display result m Map each array index back to input to display 46
![Exercise Excel Style q Buckets specified in an array m 59 75 85 90 Exercise: Excel Style q Buckets specified in an array m [59, 75, 85, 90]](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-47.jpg)
Exercise: Excel Style q Buckets specified in an array m [59, 75, 85, 90] => • • • 0 – 59 bucket 1 60 – 75 bucket 2 76 – 85 bucket 3 86 – 90 bucket 4 91 and above bucket 5 47

Letter Frequency Counting r Objective: Count the frequency of letters a to z, ignoring case, in a text file. q The inventor of Morse code, Samuel Morse (1791 -1872), counted letter frequencies to assign the simpler codes to the more frequently used letters. The counters he obtained: • • • E: 12000 T: 9000 A: 8000 … X: 400 Z: 200 48

Using Array as Counters/Accumulators q Create an array equal to the size of the number of categories m Q: how many categories? int[] counters = new int[26]; q Loop over each input m map input’s value to array index ch -> counters[ch-’a’] ch -> counters[ch-’A’] m increase the array element at index q Display result m Map each array index back to input to display index -> (char)(‘a’+ index) 49
![Array Elements as Counters r Count the number of characters in a line int Array Elements as Counters r Count the number of characters in a line: int[]](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-50.jpg)
Array Elements as Counters r Count the number of characters in a line: int[] counts = new int[26]; String line = scan. next. Line(); for (int i = 0; i < line. length(); i++) { char ch = line. char. At(i); Mapping data to Mapping data index to index if (‘a’ <= ch && ch <= ‘z’) { counts[ch-’a’]++; } else if (‘A’ <= ch && ch <= ‘Z’) { counts[ch-’A’]++; } } 50
![Array Index to Display public static void histogramint counts int max maxcounts Array Index to Display public static void histogram(int[] counts) { int max = max(counts);](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-51.jpg)
Array Index to Display public static void histogram(int[] counts) { int max = max(counts); for (int i = 0; i < counts. length; i++) { if (counts[i] > 0) { System. out. print( (char)('a' + i) + ": "); int h = counts[i]; for (int j = 0; j < h; j++) { System. out. print("*"); } System. out. println(); } } Mapping index } // end of histogram to data Letter. Histogram. java 51

Roadmap: Arrays q Motivation, declaration, initialization, access q Reference semantics: arrays as objects q Example usage of arrays: m As counter (please read outside class) m As state 52

Coupon-Collector Problem q Given N different types of chocolates, and you get one random type each day. Simulate how many days you need in order to have (at least) one of each type. 53

Coupon-Collector Problem: Pseudo Code How? // assume items are numbered 0 to N - 1 repeat when not collected all distinct items pick a random item if item is new record new item 54

Coupon-Collector Problem: Pseudo Code // assume items are numbered 0 to N – 1 int distinct = 0; while distinct < N How? pick a random item if item is new record new item distinct ++; 55

Coupon-Collector Problem: Pseudo Code // assume items are numbered 0 to N – 1 int distinct = 0; boolean[] has = new boolean[N]; while distinct < N pick a random item if item is new has[item] = true; // record new item distinct ++; 56
![CouponCollector Problem public class Coupon Collector public static void mainString args int Coupon-Collector Problem public class Coupon. Collector { public static void main(String[] args) { int](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-57.jpg)
Coupon-Collector Problem public class Coupon. Collector { public static void main(String[] args) { int N = Integer. parse. Int(args[0]); int cnt = 0; // number of received collected int distinct. Cnt = 0; // number of distinct boolean[] has = new boolean[N]; // keep state while (distinct. Cnt < N) { int val = rand(0, N-1); cnt++; if (!has[val]) { distinct. Cnt++; has[val] = true; // update state } } // all N distinct cards found System. out. println(cnt); } } 57

For Those Who are Curious q # 1: m pick a new one with prob. 1 q#2 m pick a new one with prob. (N-1)/N, and hence needs ~N/(N-1) for a new one q#3 m pick a new one with prob. (N-2)/N, and hence needs N/(N-2) => N (1 + 1/2 + 1/3 + … + 1/N) ~ N ln N. q N = 30 chocolate types. Expect to wait 120 days. 58

Simulate Self-Avoiding Walk q Model. m N-by-N lattice. m Start in the middle. m Each step randomly moves to a neighboring intersection, if a previously moved intersections, no move. m Two possible outcomes: • dead end and escape. q Applications. Polymers (http: //en. wikipedia. org/wiki/Polymer), statistical mechanics, etc. 59

Self-Avoiding Random Walk // read in lattice size N as command-line argument. // read in number of trials T as command-line argument. // repeat T times: // initialize (x, y) to center of N-by-N grid. // repeat as long as (x, y) is not escape or trap // mark (x, y) as visited. // take a random step, updating (x, y). how to implement? // if not escape increase #dead. Ends // print fraction of dead ends. 60

% java Self. Avoiding. Walks 10 100000 5% dead ends % java Self. Avoiding. Walks 20 100000 32% dead ends % java Self. Avoiding. Walks 30 100000 58% dead ends … % java Self. Avoiding. Walks 100000 99% dead ends 61 61

Backup Slides
![Array Variables are Reference Variables int a 1 4 15 8 int a Array Variables are Reference Variables int[] a 1 = {4, 15, 8}; int[] a](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-63.jpg)
Array Variables are Reference Variables int[] a 1 = {4, 15, 8}; int[] a 2 = a 1; // refer to same array as a 1 a 2[0] = 7; System. out. println(Arrays. to. String(a 1)); a 1 index 0 1 2 value 7 4 15 8 // [7, 15, 8] a 2 63
![Recap Page Rank Sergey Brin and Larry Page 1998 q Problem many Web pages Recap: Page. Rank [Sergey Brin and Larry Page, 1998] q Problem: many Web pages](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-64.jpg)
Recap: Page. Rank [Sergey Brin and Larry Page, 1998] q Problem: many Web pages may contain the searched key word (e. g. , Yale), how to rank the pages when displaying search results? q Basic Page. Rank™ idea m 10 -90 rule • 10% of the time surfer types a random page • 90% of the time surfer clicks random link on a given page m Page. Rank ranks pages according frequencies surfers visit Web pages 64

Page. Rank 65

Computing Page. Rank: Setup q Number pages 0 to N – 1 q Obtain page links among pages 66

Computing Page. Rank q Initialize arbitrary page ranks q Iterative algorithm m Assume current round page rank of page p i is PRc(pi) m Update next round by distributing the frequencies of the previous round 45=100*. 9/2 100 45 p 1 60 60=200*. 9/3 200 p 2 60 … pn x

Computing Page. Rank p 1 x p 2 … pn

Input format 5 1 22334 … page 0 has 1 outgoing link to page 1 has four 5 outgoing links to pages 2, 2, 3, 3, 4 Outgoing adjacency List 69

Page. Rank: Reading Graph Scanner input = new Scanner(new File("tiny-web. txt")); // First read N, the number of pages int N = Integer. parse. Int(input. next. Line()); // An irregular 2 D array to keep track of outgoing links int[][] outgoing. Links = new int[N][]; // read in graph one line at a time for (int i = 0; i < N; i++) { String line = input. next. Line(); // read outgoing links of i String[] links = line. split(" "); outgoing. Links[i] = new int[links. length]; for (int j = 0; j < links. length; j++) { outgoing. Links[i][j] = Integer. parse. Int(links[j]); } } 70
![Page Rank Compute Rank double pr new doubleN pr0 1 initialize Page. Rank: Compute Rank double[] pr = new double[N]; pr[0] = 1; // initialize](https://slidetodoc.com/presentation_image/01c40dad0cff5364e40dd5cf8ad661d2/image-71.jpg)
Page. Rank: Compute Rank double[] pr = new double[N]; pr[0] = 1; // initialize to assume start at web page 0 // or Arrays. fill(pr, 1. 0 / N); for (int t = 0; t < 20; t++) { double[] newpr = new double[N]; // init newpr Arrays. fill(newpr, 0. 1 / N); // loop over the node to redistribute the frequencies for (int i = 0; i < N; i++) { // redistribute node i for (int j = 0; j < outgoing. Links[i]. length; j++) { int to = outgoing. Links[i][j]; newpr[to] += 0. 9 * pr[i] / outgoing. Links[i]. length; } } pr = newpr; // swap newpr to be pr System. out. printf("pr[%2 d] = %sn", t, Arrays. to. String(pr) ); } 71