Arrays Chris Piech CS 106 A Stanford University
- Slides: 40
Arrays Chris Piech CS 106 A, Stanford University
What does this say? 53‡‡† 305))6*; 4826)4‡ • )4‡); 806*; 48† 8¶ 60))85; 1‡(; : ‡*8† 83(88)5*†; 46(; 88*96* ? ; 8)*‡(; 485); 5*† 2: *‡(; 4956*2(5*– 4)8¶ 8*; 4069285); )6† 8)4‡‡; 1(‡ 9; 48081; 8: 8‡ 1; 48† 85; 4)485† 528806*81(‡ 9; 48; (88; 4( ‡? 34; 48)4‡; 161; : 188; ‡? ; Puzzle in Gold Bug by Edgar Allan Poe Piech, CS 106 A, Stanford University
Changing Variable Types int to double? int to String? int x = 5; double x. Dbl = x; int x = 5; String x. Str = “” + x String to int? String to double? String x. Str = “ 5”; int x = Integer. parse. Int(x); String x. Str = “ 5. 6”; double x = Double. parse. Double(x. Str); Casting double to int double x = 5. 2; int y = (int)x; GObject to GRect GObject obj = get. Element. At(5, 2); GRect obj. Rect = (GRect)obj; int to char int diff = 'C'-'A'; char next = (char)'a' + diff; Piech, CS 106 A, Stanford University
Changing Variable Types Piech, CS 106 A, Stanford University
Number Translation Piech, CS 106 A, Stanford University
Where are we? • • Karel the Robot Java Console Programs Graphics Programs Text Processing Data Structures Defining our own Variable Types GUIs Piech, CS 106 A, Stanford University
Arrays #majorkey of the day A new variable type that is an object that represents an ordered, homogeneous list of data. – Arrays have many elements that you can access using indices index 0 1 2 3 4 5 6 7 8 9 value 12 49 -2 26 5 17 -6 84 72 3 element 0 element 4 element 9 length = 10
Many flavors of arrays Arrays Of Other Types You can create arrays of any variable type. For example: double[] results = new double[5]; String[] names = new String[3]; boolean[] switches = new boolean[4]; GRect[] rects = new GRect[5]; • Java initializes each element of a new array to its default value, which is 0 for int and double, ‘ ’ for char, false for boolean, and null for objects. Piech, CS 106 A, Stanford University
Many flavors of arrays Arrays Of Other Types You can create arrays of any variable type. For example: char[] old. School. String = new char[5]; • Java initializes each element of a new array to its default value, which is 0 for int and double, ‘ ’ for char, false for boolean, and null for objects. Piech, CS 106 A, Stanford University
Data Structures Operation Strings Make a new one String str = “abc”; Get length? str. length() Get element? str. char. At(i) Set element? Not allowed Loop? for(int i = 0; i < str. length(); i++) Piech, CS 106 A, Stanford University Arrays
Data Structures Operation Strings Arrays Make a new one String str = “abc”; int arr = new int[5]; Get length? str. length() arr. length Get element? str. char. At(i) arr[i] Set element? Not allowed arr[i] = 5; for(int i = 0; i < str. length(); i++) for(int i = 0; i < arr. length; i++) Loop? CS 106 A, Stanforda. University * note: Piech, there was previously typo here
Creating Arrays Creating an Array type[] name = new type[length]; int[] numbers = new int[5]; index 0 1 2 3 4 value 0 0 0 Java automatically initializes elements to 0.
Getting values Accessing Data In An Array name[index] // get element at index • Like Strings, indices go from 0 to the array's length - 1. for (int i = 0; i < 7; i++) { println(numbers[i]); } println(numbers[9]); // exception println(numbers[-1]); // exception index 0 1 2 3 4 5 6 value 0 1 2 3 4 5 6
Setting values Putting Data In An Array name[index] = value; // set element at index
Setting values Putting Data In An Array name[index] = value; // set element at index • Like Strings, indices go from 0 to the array's length - 1. int[] numbers = new int[7]; for (int i = 0; i < 7; i++) { numbers[i] = i; } numbers[8] = 2; // exception numbers[-1] = 5; // exception index 0 1 2 3 4 5 6 value 0 1 2 3 4 5 6
Practice array. Elements 1 Q: What are the contents of numbers after executing this code? int[] numbers = new int[8]; numbers[1] = 3; numbers[4] = 7; numbers[6] = 5; int x = numbers[1]; numbers[x] = 2; numbers[4]] = 9; // A. B. C. D. 0 {0, {3, {0, 1 3, 3, 2 0, 0, 5, 0, 3 2, 0, 2, 2, 4 7, 7, 5 0, 0, 4, 6, 6 5, 5, 5, 4, 7 9} 0} 0} 4}
Getting “length” Array Length Similar to a String, you can get the length of an array by saying my. Array. length Note that there are no parentheses at the end! Practice: • What is the index of the last element of an array in terms of its length? • What is the index of the middle element of an array in terms of its length?
Arrays ❤� loops Just like with Strings, we can use an array’s length, along with its indices, to perform cool operations.
Arrays ❤� loops Just like with Strings, we can use an array’s length, along with its indices, to perform cool operations. For instance, we can efficiently initialize arrays. int[] numbers = new int[8]; for (int i = 0; i < numbers. length; i++) { numbers[i] = 2 * i; } index 0 1 2 3 4 5 6 7 value 0 2 4 6 8 10 12 14
Arrays ❤� loops Just like with Strings, we can use an array’s length, along with its indices, to perform cool operations. For instance, we can read in numbers from the user: int length = read. Int("# of numbers? "); int[] numbers = new int[length]; for (int i = 0; i < numbers. length; i++) { numbers[i] = read. Int("Elem " + i + ": "); }
Arrays ❤� loops Just like with Strings, we can use an array’s length, along with its indices, to perform cool operations. Try it out! sum up all of an array’s elements. // assume that the user has created int[] numbers int sum = 0; for (int i = 0; i < numbers. length; i++) { sum += numbers[i]; } println(sum);
Annoying initialization Brief Aside: Creating Arrays Sometimes, we want to hardcode the elements of an array. int numbers = new int[7]; numbers[0] = 5; numbers[1] = 32; numbers[3] = 12; . . . // This is tedious!
Fancy initialization Brief Aside: Creating Arrays Sometimes, we want to hardcode the elements of an array. Luckily, Java has a special syntax for initializing arrays to hardcoded numbers. type[] name = { elements }; // Java infers the array length int[] numbers = {5, 32, 12, 2, 1, -1, 9};
Limitations of Arrays • An array’s length is fixed. You cannot resize an existing array: int[] a = new int[4]; a. length = 10; // error • You cannot compare arrays with == or equals : int[] a 1 = {42, -7, 1, 15}; int[] a 2 = {42, -7, 1, 15}; if (a 1 == a 2) {. . . } if (a 1. equals(a 2)) {. . . } // false! • An array does not know how to print itself: println(a 1); // [I@98 f 8 c 4]
Array Methods to the Rescue! Arrays Methods To The Rescue! • The class Arrays in package java. util has useful methods for manipulating arrays: Method name Description Arrays. binary. Search(array, value) returns the index of the given value in a sorted array (or < 0 if not found) Arrays. copy. Of(array, length) returns a new copy of array of given length Arrays. equals(array 1, array 2) returns true if the two arrays contain same elements in the same order Arrays. fill(array, value); sets every element to the given value Arrays. sort(array); arranges the elements into sorted order Arrays. to. String(array) returns a string representing the array, such as "[10, 30, -25, 17]"
Array Methods to the Rescue! Arrays. to. String accepts an array as a parameter and returns a string representation of its elements. int[] e = {0, 2, 4, 6, 8}; e[1] = e[3] + e[4]; println("e is " + Arrays. to. String(e)); Output: e is [0, 14, 4, 6, 8]
Arrays as Parameters Passing Arrays Between Methods • Arrays are just another variable type, so methods can take arrays as parameters and return an array. private int sum. Array(int[] numbers) {. . . } private int[] make. Special. Array(. . . ) {. . . return my. Array; } Piech, CS 106 A, Stanford University 27
Passing Arrays Between Methods • Arrays are just another variable type, so methods can take arrays as parameters and return an array. • However, arrays are objects, so per A Variable Origin Story, an array variable box actually stores its location. • This means changes to an array passed as a parameter affect the original array! Piech, CS 106 A, Stanford University 28
Arrays: Pass By Reference public void run() { int[] numbers = new int[7]; fill. Array(numbers); println(Arrays. to. String(numbers)); } private void fill. Array(int[] arr) { for (int i = 0; i < arr. length; i++) { arr[i] = 2 * i; } } Piech, CS 106 A, Stanford University 29
Practice: Swapping Elements Let’s write a method called swap. Elements that swaps two elements of an array. How can we do this? What parameters should it take (if any)? What should it return (if anything)? private ? ? ? swap. Elements(? ? ? ) {. . . } Piech, CS 106 A, Stanford University 30
Swapping: Take 1 Swap: Take 1 public void run() { int[] array = new int[5]; . . . swap. Elements(array[0], array[1]); . . . } private void swap. Elements(int x, int y) { int temp = x; x = y; y = temp; } Piech, CS 106 A, Stanford University 31
Swapping: Take 1 Swap: Take 1 public void run() { int[] array = new int[5]; Ints. . . are primitives, so they are passed by value! Their variable boxes store their actual values. So swap. Elements(array[0], array[1]); changes to the parameter do not affect the. . . original. } private void swap. Elements(int x, int y) { int temp = x; x = y; y = temp; } Piech, CS 106 A, Stanford University 32
Swapping: Take 2 Swap: Take 2 public void run() { int[] array = new int[5]; . . . swap. Elements(array, 0, 1); . . . } private void swap. Elements(int[] arr, int pos 1, int pos 2) { int temp = arr[pos 1]; arr[pos 1] = arr[pos 2]; arr[pos 2] = temp; } Piech, CS 106 A, Stanford University 33
Swapping: Take 2 Swap: Take 2 public void run() { int[] array = new int[5]; . . . Arrays are objects, so they are passed by swap. Elements(array, 0, 1); boxes store their reference! Their variable. . . location. So changes to the parameter do affect } the original. private void swap. Elements(int[] arr, int pos 1, int pos 2) { int temp = arr[pos 1]; arr[pos 1] = arr[pos 2]; arr[pos 2] = temp; } Piech, CS 106 A, Stanford University 34
Example: Reverse Array Program public void run() { int n = read. Int("Enter number of elements: "); String array. To. String(int[] array) private void int[]reverse. Array(int[] create. Index. Array(int array) n) {{ { int[] int. Array = create. Index. Array(n); String str int[] for (int array i = ==""; 0; new i < int[n]; array. length / 2; i++) { println("Forward: " + array. To. String(int. Array)); private void swap. Elements(int[] array, p 1, int p 2) { for (int i++)int { forswap. Elements(array, ( intii==0; 0; ii<<array. length; n; i, i++ array. length ) { - i - 1); reverse. Array(int. Array); int temp array[p 1]; (i > =0) } if array[i] = str i; += ", "; println("Reverse: " + array. To. String(int. Array)); array[p 1] = array[p 2]; str += array[i]; } } n int. Array } array[p 2] = temp; } return array; in array i array } return "[" + str + "]"; 10 temp p 1 p 2 array } } 5 4 3 2 1 0 10 01 9 8 7 6 5 4 3 2 str i 109 array 0 0 0, 0, 1, 3 4, 1 2, 4 5, 5 6, 6 7, 2 3, 7 8, 8 9 10 0123456789 90 180 270 603 504 540 630 720 810 09 0 1 2 3 4 5 6 7 8 9 Reverse. Array Enter number of elements: 10 Forward: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Reverse: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] Piech, CS 106 A, Stanford University skip simulation
Cryptogram • A cryptogram is a puzzle in which a message is encoded by replacing each letter in the original text with some other letter. The substitution pattern remains the same throughout the message. Your job in solving a cryptogram is to figure out this correspondence. • One of the most famous cryptograms was written by Edgar Allan Poe in his short story “The Gold Bug. ” • In this story, Poe describes the technique of assuming that the most common letters in the coded message correspond to the most common letters in English, which are E, T, A, O, I, N, S, H, R, D, L, and U. Edgar Allan Poe (1809 -1849) Piech, CS 106 A, Stanford University
Letter Frequency By Peter Norvig Head of Google Research Former CS 221 Instructor Based on 3. 8 trillion letters Piech, CS 106 A, Stanford University
Poe’s Cryptographic Puzzle 53‡‡† 305))6*; 4826)4‡ • )4‡); 806*; 48† 8¶ 60))85; 1‡(; : ‡*8† 83(88)5*†; 46(; 88*96* ? ; 8)*‡(; 485); 5*† 2: *‡(; 4956*2(5*– 4)8¶ 8*; 4069285); )6† 8)4‡‡; 1(‡ 9; 48081; 8: 8‡ 1; 48† 85; 4)485† 528806*81(‡ 9; 48; (88; 4( ‡? 34; 48)4‡; 161; : 188; ‡? ; AG 5 3 O ‡O ‡D †G 3 L 0 A 5 S )S )I 6 N *T ; H 4 E 8 B 2 I 6 S )H 4 O ‡P • S )H 4 O ‡S )T ; E 8 L 0 I 6 N *T ; H 4 E 8 D †E 8 V ¶ 6 L I 0 S )S )E 8 A 5 T ; F 1 O ‡R (T ; Y : O ‡N *E 8 D †E 8 G 3 R (E 8 E 8 S )A 5 N *D †T ; H 4 I 6 R (T ; E 8 E 8 N *M 9 I 6 N * ? T U ; E 8 S )N *O ‡R (T ; H 4 E 8 A 5 S )T ; A 5 N *D †B 2 Y : N *O ‡R (T ; H 4 M 9 A 5 I 6 N *B 2 R (A 5 N *C –H 4 S )E 8 V ¶ 8 N E *T ; H 4 L 0 I 6 M 9 B 2 E 8 A 5 S )T ; S )I 6 D †E 8 S )H 4 O ‡O ‡T ; F 1 R (O ‡M 9 T ; H 4 E 8 L 0 E 8 F 1 T ; E 8 Y : E 8 O ‡ 1 T F ; H 4 E 8 D †E 8 A 5 T ; H 4 S )H 4 E 8 A 5 D †A 5 B 2 E 8 E 8 L 0 I 6 N *E 8 F 1 R (O ‡M 9 T ; H 4 E 8 T ; R (E 8 E 8 T ; H 4 R ( ‡U O ? G 3 H 4 T ; H 4 E 8 S )H 4 O ‡T ; F 1 I 6 F 1 T ; Y : F 1 E 8 E 8 T ; O ‡U ? T ; Piech, CS 106 A, Stanford University 8 ; 4 ‡ ) * 5 6 ( † 1 0 9 2 : 3 ? ¶ – • 33 26 19 16 16 13 12 11 10 8 8 6 5 5 4 4 3 2 1 1
Implementation Strategy The basic idea behind the program to count letter frequencies is to use an array with 26 elements to keep track of how many times each letter appears. As the program reads the text, it increments the array element that corresponds to each letter. T W A S B RI L L I G 0 1 1 0 0 0 10 0 2 0 0 0 1 1 0 0 0 1 2 0 10 10 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Piech, CS 106 A, Stanford University
Putting Data In An Array To the code!
- Chris piech stanford
- Chris piech
- Karolina piech
- Karolina piech
- Stanford university cio
- Stanford continuing studies certificate
- Stanford university
- Steve jobs stanford commencement address
- Dan boneh stanford
- Dr. ash from stanford university
- Silicon valley stanford university
- Cs223 stanford
- Stanford university
- Stanford university philosophy department
- Parallel arrays in c
- Array of arrays c++
- Parallel arrays
- Partially filled arrays
- C++ parallel arrays
- Why do we need arrays?
- Dynamic arrays and amortized analysis
- Suma de arreglos unidimensionales en c
- Arreglos bidimensionales java
- Mips array example
- Polynomial representation using array in c
- Array of strings assembly
- Global arrays in c
- Computer science arrays
- Searching and sorting arrays in c++
- Arrays visual basic
- Python find index of max
- Disadvantages of array
- I wonder is it possible
- 2d array pascal
- Declare array in mips
- Creating arrays matlab
- Adt of array
- Partially filled arrays
- Redundant arrays of independent disks
- Python list of arrays
- Arrays