Download presentation
Presentation is loading. Please wait.
Published byBrycen Wooden Modified over 9 years ago
1
Hip Hip Array! AP Computer Science
2
Remember Strings? Strings are an array of characters An array is a collection of variables all of the same type. Arrays allow you to store several variables of the same type in one place. 375219 8326 012345 0123 index Elements [0] = 3 [1] = 7 [2] = 9 [3] = 2 [4] = 1 [5] = 5 The index starts at 0 The first item is at index 0 The last item is at index (length – 1) Length = 6 Index = 6-1=5 6 elements Index from 0 to 5 Array symbol [ ]
3
what type of data can arrays hold? String [ ] name = new String [ 3]; or String [ ] name = {“Billy”, “Sally”, “Bob”}; boolean [ ] done = new boolean [3]; or boolean [ ] done = {true, false, true}; int [ ] num = new int [5]; int [ ] num = {5, 2, 4, 6, 8}; double [ ] nums = new double [ 5 ]; or double [ ] nums = {2.5, 3.5, 4.5, 5.5, 6.5}; primitives or objects
4
What are limitations of arrays? Fixed in size each cell must hold the same type
5
How to declare an array String [] name; // just declare String [ ] name = new String [ 3]; // initialize to 3 elements name[0] = “Billy”; // use brute force to assign data name[1] = “Sally”; name[2] = “Bob”; Assign the elements when you create the array String [ ] name = {“Billy”, “Sally ”, “Bob”);
6
Arrays are never empty? Array names are a reference to memory address When you use the word new a memory address is created. double [] salesFigure; no memory address null salesFigure = new double [20]; reserves 20 memory locations for 20 doubles Each element in the array is assigned 0 by default. int arrays are filled with ________________ double arrays are filled with ____________ boolean arrays are filled with ___________ object arrays are filled with _____________ (Strings are filled with this) 0 0.0 false null
7
print array You can print individual elements at specific index locations. array[0] if you print the name of the array you get the memory location. System.out.println(array); memorylocation you must loop over the elements and print each one as you go. int [] nums = new int[10]; for(int i = 0; i < nums.length; i = i+2) nums[i] = i; System.out.println(nums[i]); This will fill each index with a value i+2 and print the array Array will print: 0, 2, 4, 6, 8 i print < 10 i = 0 0 yes i = 0+2 2 yes i = 2 + 2 4 yes i = 4 + 2 6 yes i = 6 + 2 8 yes i = 8 + 2 stop no
8
Reassigning elements in an array int[] array = {7,8,10,11,4,3}; array[array[0]/2]=15; array[array[4]+1]=9; array[array.length/2-1]=5; array[1]=array[0]+4; index 3 = 15 index 5 = 9 index 2 = 5 index 1 to be index 4 New Array: 7 4 5 15 4 9 0 1 2 3 4 5
9
Finding how many of a value public boolean findValue(int [] nums, int value) { int count = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] == 4) count++ } return count; }
10
Given an int array length 2, return true if it does not contain a 2 or 3. no23({4, 5}) → true no23({4, 2}) → false no23({3, 5}) → false public boolean no23(int[] nums) { int match = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] == 2 || nums[i] == 3) match++; } if(match > 0) return false; else return true; } }
11
double 23 Given an int array, return true if the array contains 2 twice, or 3 twice. The array will be length 0, 1, or 2. double23({2, 2}) → true double23({3, 3}) → true double23({2, 3}) → false problem solve: We want it to count the number of 2s or 3s in the array. public boolean double23(int[] nums) { int match2 = 0; int match3 = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] == 2){ match2++;} if(nums[i] == 3){ match3++; } } if(match2 ==2 || match3 ==2) return true; else return false; }
12
Java Subset class java.lang.Math – static int abs(int x) – static double abs(double x) – static double pow(double base, double exponent) – static double sqrt(double x) – static double random() // returns a double in the range [0.0, 1.0)
13
Produce random using Math.random Math class double Math.random() Returns a number x in the range, 0.0 <= x < 1.0. int randomIndex = (int)(Math.random()*10); Produce numbers from 0 to 9 N-1 10-1 = 9 Needs to be cast to an int
14
2D Arrays Two-Dimensional Arrays A two-dimensional array is a table/matrix -- with rows and columns -- where each row is an array, and there are several rows in a table. e.g. a two-dimensional array of 3 rows and 4 columns
15
Create 2D Array To create a two-dimensional array, you specify the number of rows (first) and columns (second). int[][] iMat = new int[3][4]; // integer matrix of 3 rows, 4 columns double[][] dMat = new double[5][3]; // double matrix of 5 rows, 3 columns char[][] cMat = new char[3][3]; // char matrix -- 3 rows, 3 columns
16
Direct Initialization To give initial values for the elements in a two- dimensional array, you can of course set up a loop. Another way is to provide the initial values directly in declaration. int[][] iMat = { {12, 48, 69, 7}, {5, 16, 27, 30}, {51, 3, 72, 9} };
17
Access an element in 2D Array Each row is an individual array Column index starts at 0 To access an element in a two- dimensional array, you specify the row index (first) and column index (second). System.out.println(iMat[0][2]); // prints an element at row 0, column 2 (69 in the example above) iMat[2][2] = 5; // assign 5 to row 2, column 1
18
Length 2D array Lengths of a Two-dimensional Array. Arrays can contain different number of column elements at each row. 0 1 2 3 +----+----+----+----+ 0 | 12 | 48 | 69 | 7 | +----+----+----+----+ 1 | 5 | 16 | 27 | | +----+----+----+----+ 2 | 51 | 3 | | +----+----+----+----+ LENGTH OF ROW AND COLUMN The Row length (number of rows in the array) is found by using length. int numRow = mat.length; Array to the side has 3 rows The Column Length is different for each row so you must access the row first then the column length. int columnLength = mat[0].length // equal 4 int columnLength = mat[1].length // equal 3
19
Traversing Over a 2D Array with for loop Then we can utilize those two lengths to traverse over a two-dimensional array -- also by using a nested loop. Two for loops: First specify the row to loop through and then the column. Use Variables row and col to represent the row and column. int row, col; for (row = 0; row < matrix.length; row++) { for (col = 0; col < matrix[row].length; col++) System.out.print[matrix[row][col] + “ “ ); } System.out.println(); } int[][] iMat = { {12, 48, 69, 7}, {5, 16, 27, 30}, {51, 3, 72, 9} };
20
ArrayList implements Java.util.List Implements means that the class that implements another class must also implement (use) its methods. ArrayList implements List so it has all the methods from the List interface class java.util.ArrayList implements java.util.List class java.util.List – int size() – boolean add(E obj) // appends obj to the end of list; returns true – void add(int index, E obj) // inserts obj at position index (0<= index <= size), // moving elements at position index and higher // to the right (adds 1 to their indices) and adjusts size – E get(int index) – E set(int index, E obj) // replaces the element at position index, with obj //returns the element formerly at the specified position – E remove(int index) // removes element from position index, moving elements // at position index + 1 and higher to the left // (subtracts 1 from their indices) and adjusts size // returns the element formerly at the specified position
21
Facts about ArrayList ArrayList can grow and shrink in size. – add, set and remove methods ArrayList use Generics type ArrayList only hold objects – Wrapper class Integer and Double ArrayList uses size() method to find the size (length) of the array). Array class used length variable
22
Creating an ArrayList ArrayList contain elements of type E Generics: the collections classes are generic, with type parameters. The type parameter is replaced by an actual object type. The is replaced with the type of object. ArrayList list = new ArrayList ();
23
Boxing and unboxing Autoboxing is the automatic conversion from a primitive type to its Object type. For example, converting an int to an Integer, a double to a Double If the conversion goes the other way, this is called unboxing. List li = new ArrayList<>(); for (int i = 1; i < 50; i += 2) li.add(i); int x = li.get(i); i is converted to the Integer object type i is converted back to an integer (int)
24
Wrapper Classes class java.lang.Integer – Integer(int value) – int intValue() – Integer.MIN_VALUE // minimum value represented by an int – Integer.MAX_VALUE // maximum value represented by an int class java.lang.Double – Double(double value) – double doubleValue() public int min(int [] nums) { int min = Integer.MAX_VALUE; for(int i = 0; i < nums.length; i++) { if(min > nums[i]) min = nums[i]; } return min; }
25
Example Arraylist list = new ArrayList (); list.add(“one”); list.add(“two”); list.add(“three”); list.remove(0); list.set(1, “one”); System.out.println(list); one two one two three two three two one three two one three
26
What prints? ArrayList words = new ArrayList (); words.add(“Zack”); words.add(“Bobby”); words.add(0, "Billy"); words.add(1, "Sam"); words.add(2, "Jane"); words.add(1, "Johnny"); words.remove(2); words.set(1, "Tammy"); words.add("Sally"); What will print? Figure this out and earn extra points on your ArrayList Quiz
27
Printing ArrayList Printing out an ArrayList For loop for(int i = 0; i < words.size(); i++) System.out.println(words.get(i)); For each loop Create the element for type of ArrayList for(String element : words) { Systemout.println(element); }
28
Iterator Interface Definition of an Iterator: purpose is to traverse over a collection. Iterator Interface: is in the Collection API ListIterator is in the Collection API Iterator has these methods Boolean hasNext() returns true if at leas one more element to be examined. E next(); Returns the next element in the iteration void remove() deletes from the collection the last element that was returned by next.
29
Examples of using Iterator Example of Iterator System.out.println("using iterator"); Iterator itr = words.iterator(); while(itr.hasNext()) System.out.println(itr.next()); Iterator it = words.iterator(); while(it.hasNext()) // true if at least one element { if(it.next().length() == 2) //returns the next element it.remove(); // removes element returned by next } System.out.println(words);
30
Array & ArrayList Free Response tally is the array Contains the frequency the index location occurred. The value 4 occurred 10 times
31
Example of what should be returned. The first is the ArrayList. The second is the index of the modes in the array run Stats [4, 7, 7, 8, 0, 9, 3, 9, 9, 3] [5, 7, 8] > 9 is the mode. It occurred at index locations 5, 7, 8 [1, 9, 8, 2, 2, 0, 2, 9, 10, 7] [8] The mode is 10 so it returns index 8 Both Array and ArrayList solutions use the same algorithm; however, the ArrayList is easier since you do not have to know the size of an ArrayList when you create it. You must use the findMax(tally) method to find the max number before looping through the array. Then as you loop through the array you will see how many times that number is in the array. ArrayList you can directly store the index location into an ArrayList you have created. Array must first count the number of occurrences as you loop through tally. Then create a new array of that size. Loop through the old array (tally) and if index = max store that index in the new array. Don’t forget to increase the index of the new array.
32
Part B You Should create a method called kthDataValue(array or arraylist, int k) This method will take either an array or arraylist depending on the parameter and a number that represents the number of elements. It will return the position of the kth element. kthDataValue(list, 14); Returns: [3, 3, 10, 1, 6, 6, 10, 6, 10, 3] // arraylist 2 // The 14 element is at index 2 Remember the array or arraylist looks like this: 0 0 0 1 1 1 2 2 2 2 2 2 2 2 2 2 3 etc. Hints: You will need a counter variable that will actually accumlate the sum of the indexes. If the sum of the index is greater than k than return that index.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.