hip hip array!

32
Hip Hip Array! AP Computer Science

Upload: adelle

Post on 12-Jan-2016

58 views

Category:

Documents


0 download

DESCRIPTION

Hip Hip Array!. AP Computer Science. What is an array?. 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. The index starts at 0 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Hip Hip Array!

Hip Hip Array!

AP Computer Science

Page 2: Hip Hip Array!

Remember Strings? Strings are an array of charactersAn 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.

3 7 5 2 1 9

8 3 2 6

0 1 2 3 4 5

0 1 2 3

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 = 6Index = 6-1=5

6 elements Index from 0 to 5

Array symbol [ ]

Page 3: Hip Hip Array!

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

Page 4: Hip Hip Array!

What are limitations of arrays?

• Fixed in size• each cell must hold the same type

Page 5: Hip Hip Array!

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”);

Page 6: Hip Hip Array!

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

Page 7: Hip Hip Array!

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 < 10i = 0 0 yesi = 0+2 2 yesi = 2 + 2 4 yesi = 4 + 2 6 yesi = 6 + 2 8 yesi = 8 + 2 stop no

Page 8: Hip Hip Array!

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

Page 9: Hip Hip Array!

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; }

Page 10: Hip Hip Array!

Given an int array length 2, return true if it does not contain a 2 or 3.

no23({4, 5}) → trueno23({4, 2}) → falseno23({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; } }

Page 11: Hip Hip Array!

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}) → truedouble23({3, 3}) → truedouble23({2, 3}) → falseproblem 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; }

Page 12: Hip Hip Array!

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)

Page 13: Hip Hip Array!

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

Page 14: Hip Hip Array!

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

Declare a 2D array

int [][] table = new int [3][4];

0 1 2 3 +----+----+----+----+ 0 | 12 | 48 | 69 | 7 | +----+----+----+----+ 1 | 5 | 16 | 27 | 30 | +----+----+----+----+ 2 | 51 | 3 | 72 | 9 |

+----+----+----+----+

Page 15: Hip Hip Array!

Create 2D ArrayTo 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

Page 16: Hip Hip Array!

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} };

Page 17: Hip Hip Array!

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

0 1 2 3 +----+----+----+----+ 0 | 12 | 48 | 69 | 7 | +----+----+----+----+ 1 | 5 | 16 | 27 | | +----+----+----+----+ 2 | 51 | 3 | | +----+----+----+----+

Page 18: Hip Hip Array!

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  

Page 19: Hip Hip Array!

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} };

0 1 2 3 +----+----+----+----+ 0 | 12 | 48 | 69 | 7 | +----+----+----+----+ 1 | 5 | 16 | 27 | | +----+----+----+----+ 2 | 51 | 3 | | +----+----+----+----+

Page 20: Hip Hip Array!

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<E>– 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

Page 21: Hip Hip Array!

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

Page 22: Hip Hip Array!

Creating an ArrayList

ArrayList<E> 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 <E> is replaced with the type of object. ArrayList<Integer> list = new ArrayList<Integer>();

Page 23: Hip Hip Array!

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<Integer> 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)

Page 24: Hip Hip Array!

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; }

Page 25: Hip Hip Array!

Example

Arraylist<String> list = new ArrayList <String>();list.add(“one”);list.add(“two”);list.add(“three”);list.remove(0);list.set(1, “one”); System.out.println(list);

oneonetwo

onetwothree

twothree

twoonethree

twoonethree

Page 26: Hip Hip Array!

What prints? ArrayList<String> words = new ArrayList<String>(); 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

Page 27: Hip Hip Array!

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); }

Page 28: Hip Hip Array!

Iterator<E> Interface Definition of an Iterator: purpose is to traverse over a collection. Iterator<E> Interface: is in the Collection API ListIterator is in the Collection API Iterator<E> 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.

Page 29: Hip Hip Array!

Examples of using IteratorExample of Iterator

System.out.println("using iterator"); Iterator<String> itr = words.iterator(); while(itr.hasNext()) System.out.println(itr.next()); Iterator<String> 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);

Page 30: Hip Hip Array!

• Array & ArrayList Free Response

tally is the arrayContains the frequency the index location occurred.

The value 4 occurred 10 times

Page 31: Hip Hip Array!

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.

Page 32: Hip Hip Array!

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] // arraylist2 // 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.