Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Patterns with.

Slides:



Advertisements
Similar presentations
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Advertisements

Arrays, A1 COMP 401, Fall 2014 Lecture 4 8/28/2014.
1 Various Methods of Populating Arrays Randomly generated integers.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Arrays COMP 102.
General Computer Science for Engineers CISC 106 Lecture 19 Dr. John Cavazos Computer and Information Sciences 04/06/2009.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Review COMP 102 #
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays COMP 102 # T1.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Conditionals.
Writing Methods Using if, loops, and variables to implement algorithms Copyright © 2012 Pearson Education, Inc.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More 2D arrays COMP 102 #27.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays with meaningful indices.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Call a Method,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArraySet and Binary Search.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues,
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
2011-T1 Lecture 13 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Files COMP 102.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
CompSci Arrays  Aggregate data type  Deal with items of same type  Lists of words  Numbers  Analogies  Mailboxes in post office  CD racks.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays with meaningful indices.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Conditionals.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington More Interfaces.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington “For each” & Patterns with.
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
1 On (computational) simplicity We are trying to teach not just Java, but how to think about problem solving. Computer science has its field called computational.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Exercise, printf,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Classes, Objects, Fields,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Recursion COMP 103 #
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Creating Objects.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Classes and.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on Files COMP 102 # 14.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Fields, Constructors.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on Files COMP 102 # 14.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists COMP 102 # T1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Creating Objects.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More 2D arrays COMP 102 #27.
Introducing Arrays. Too Many Variables?  Remember, a variable is a data structure that can hold a single value at any given time.  What if I want to.
2011-T1 Lecture 12 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 Analysing Costs COMP 103.
2014-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays COMP 102 # T1.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Dealing with Files COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on ArrayLists COMP 102.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Presentation transcript:

Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Patterns with Arrays COMP 102 # T2

© Xiaoying Gao, Peter Andreae COMP :2 Menu For loop: (completing lecture 21) More common patterns with arrays Another form of for. all and any operating on pairs Administration: Assignment 7 only has one question! Due Wed 10am Solutions for exercise questions are ed. Term test 2 will be handed back tomorrow Tutorial: Tuesday, 12-1, VZ103; Friday 3-4 MY107

©Xiaoying Gao, Peter Andreae COMP102 21:3 Using an Array : for loops Standard pattern for processing each element of an array: Int[] data = new int[ ] {5, 7, 3, 6, 10}; int i = 0 ; while (i < data.length ){ UI.println(data[ i ]) ; i = i+1 ; } The for loop is a shorthand: for (int i = 0 ; i < data.length ; i = i+1 ) { UI.println(data[ i ]) ; } or for (int i = 0 ; i < data.length ; i++ ) { UI.println(data[ i ]); } Shorthand: same effect as i = i + 1; but the value is the value of i before incrementing it

©Xiaoying Gao, Peter Andreae COMP102 21:4 For loop For loop puts the initialisation condition increment together, at the front of the loop But the meaning is exactly the same as the while loop for(statement) ;;expressionstatement InitialisationConditionIncrement

©Xiaoying Gao, Peter Andreae COMP102 21:5 Using an Array: using for loops Same as before, but with for loop: ⇒ easier to read Print out all the marks: for (int num = 0 ; num < marks.length ; num++) { UI.printf( “Student %3d got %4.1f”, num, marks[ num ]); } Compute final marks from essay marks and exam marks: for (int i = 0 ; i < marks.length ; i++) { marks[ i ] = essay[ i ]*0.6 + exam[ i ]*0.4; }

©Xiaoying Gao, Peter Andreae COMP :6 Reading data from a file into an array Standard pattern: array with an associated count String [ ] grades = new String [200]; int count = 0; try { Scanner sc = new Scanner (new File(“grades.txt”)); while ( sc.hasNext() && count < grades.length) { grades[count] = sc.next(); count++; } catch (IOException e) { UI.printf( “File failure %s\n”, e); } A+ C B+ B- A A length CB+ “C”“C” AA-null “ A+ ” ⋯ nullA+B-null grades.txt

©Xiaoying Gao, Peter Andreae COMP :7 Printing out the number of A's String [ ] grades = new String [200]; try { … …  read grades from the file  … /n", e); } int numAs = 0; for (int i = 0; i<grades.length; i++ ) { if ( grades[ i ].startsWith("A") { numAs++; } UIprintf( "%d A's out of %d grades\n", numAs, grades.length); A+ C B+ B- A A length CB+AA- ⋯ null A+B- grades: What's the problem? count: 6 grades.txt

© Xiaoying Gao, Peter Andreae COMP :8 Acting on each item in array: Step along array, acting on each value eg: array of names: public void printAll(String [ ] names ){ for (int i = 0; i<names.length; i++){ UI.println(names[ i ]); } } public void printAll(String [ ] names ){ for (String n : names){ UI.println(n); } } length: 50 bensalkitann may jandon ⋯ names: n: array passed in as a parameter “ For each ” loop Steps through each item in array

© Xiaoying Gao, Peter Andreae COMP :9 "For each" loop Special form of the for loop: Goes through every element of the array (0 to length-1) The variable is assigned the next element of the array automatically each time round. Can't use it to change the array The variable contains the value in the array, Changing the variable does not change the the array itself. for(  type  { statement :)  array  }  variable 

© Xiaoying Gao, Peter Andreae COMP :10 Arrays of objects, more carefully public void printAll(String [ ] names ){ for (String n : names){ n = n + “ Junior”; } } length: 50 ⋯ names: count: 6 n: ben sal kit ann may jan don

© Xiaoying Gao, Peter Andreae COMP :11 Acting on each item: Same for numbers: private double[ ] marks; public double averageMark(){ double sum = 0; for (int i = 0; i<this.marks.length; i++){ sum = sum + this.marks[ i ]; } return sum / this.marks.length; } public double averageMark(){ double sum = 0; for (double mk : this.marks){ sum = sum + mk; } return sum / this.marks.length; } Field, accessible to all methods in class. Given value in another method

© Xiaoying Gao, Peter Andreae COMP :12 Changing each item: Changing the array: can’t use “for each” loop private double[ ] marks; public void scaleUpMarks(double scale){ for (int i = 0; i<this.marks.length; i++){ this.marks[ i ] = this.marks[ i ] + scale; } } public void scaleUpMarks(double scale){ for (double mk : this.marks){ mk= mk + scale; } } length: ⋯ mk:

© Xiaoying Gao, Peter Andreae COMP :13 "Any" pattern: Finding a value Search array to see if it contains a given value eg: array of names: finding if name is present in any element public boolean containsName(String name, String[] names){ boolean ans = false; for (String n : names){ if ( n!=null && n.equals(name) ) { ans = true; } } return ans; } public boolean containsName(String name, String[] names){ for (String n : names){ if ( n!=null && n.equals(name) ) { return true; } } return false; } default answer if no such element s0s0 s 11 s5s5 s8s8 s2s2 s4s4 s 10 names: the answer if you find one no else clause! why not? s1s1 s3s3 s6s6 s7s7 s9s9 s 12 default answer: if no element was equal

© Xiaoying Gao, Peter Andreae COMP :14 "All" pattern: Check valid Check that all values in an array satisfy some condition eg: field containing an array of marks: check all between 0 and 100 public boolean checkValidMarks(){ boolean ans = true; for (int i = 0; i < this.marks.length ; i++){ if ( this.marks[i] 100 ) { ans = false; } } return ans; } public boolean checkValidMarks(){ for (int mk : this.marks){ if ( !( mk >= 0 && mk <= 100) ) { return false; } } return true; } Reversed condition maybe easier to understand default: answer if all pass the answer if one fails.

© Xiaoying Gao, Peter Andreae COMP :15 Doing something to each adjacent pair Given an array with a list of numbers, check if in order: public boolean checkOrdered(int[ ] data){ for (int i = 0; i<data.length-1; i++){ if ( data[ i ] > data[ i+1 ] ){ return false; } } return true; } public boolean checkOrdered(int[ ] data){ for (int i = 1; i<data.length; i++){ if ( data[ i-1 ] > data[ i ] ){ return false; } } return true; } data: Working on multiple items at once length: 8 compare with next item: stop before length-1 compare with previous item: start at 1 Can’t use for each!

© Xiaoying Gao, Peter Andreae COMP :16 Acting on every pair of values Given array with BouncingBalls check if any two BouncingBalls are colliding with each other: (assume BouncingBalls have a method called isTouching) for (int i=0;i<balls.length; i++){ for (int j=0; j<ball.length; j++){ if (balls[ i ].isTouching(balls[ j ]) ){ //do something } } } for (int i=0; i<balls.length-1; i++){ for (int j=i+1; j<balls.length; j++){ if (balls[ i ].isTouching(balls[ j ])){ //do something } } } b1b1 b5b5 b3b3 b8b8 b2b2 b6b6 b4b4 balls: What ’ s the problem?

© Xiaoying Gao, Peter Andreae COMP :17 Bouncing Ball Class: colliding public class BouncingBall{ private int radius; private int centerX, centerY; private Color color; /** Returns true if this ball is touching the other ball, and false otherwise */ public boolean isTouching(BouncingBall other){ double dx = other.centerX - this.centerX; double dy = other.centerY - this.centerY; double dist = other.radius + this.radius; return (Math.hypot(dx, dy) <= dist); }

© Xiaoying Gao, Peter Andreae COMP :18 Arrays with Meaningful Indices Sometimes, the index represents meaningful information ⇒ May need to be have “empty” cells. array of guest names for hotel rooms (numbered 1 to MaxRoom) house info for each house on street count of occurrences of each number image n1n1 n5n5 n8n8 n 10 n7n7 n3n3 n6n6 n4n

© Xiaoying Gao, Peter Andreae COMP :19 Hotel Register initialise empty private String[ ] guests = new String[MaxRoom+1]; // gives indexes from 0 to MaxRoom, ignore index 0 assign to room public void assignGuest(String name; int room){ this.guests[room] = name; } look up to see if empty public boolean isEmpty(int room){ return (this.guests[room]==null); } n1n1 n5n5 n8n8 n 10 n7n7 n3n3 n6n6 n4n4 guests: Don ’ t need to step through array! null: the “not-a-real-object” value. Can always be assigned to a place of an object type

© Xiaoying Gao, Peter Andreae COMP :20 Hotel Register: remove Checkout guest from room /* returns true if name was checked out of room successfully, false otherwise */ public boolean checkout(String name, int room){ if ( this.guests[room].equals(name) ){ this.guests[room] = null; return true; } return false; } if ( this.guests[room] != null && this.guests[room].equals(name) ) … if ( name.equals(this.guests[room]) ) … What ’ s the problem? How do we fix it? n1n1 n5n5 n8n8 n 10 n7n7 n3n3 n6n6 n4n4 guests:

© Xiaoying Gao, Peter Andreae COMP :21 Alternative Checkout guest: search and remove: /* returns true if name was checked out successfully, false otherwise */ public boolean checkout(String name){ for (int rm=1; rm<this.guests.length; rm++){ // or <=MaxRoom if (this.guests[rm] != null && this.guests[rm].equals(name) ) { this.guests[rm] = null; return true; } return false; } n1n1 n5n5 n8n8 n 10 n7n7 n3n3 n6n6 n4n4 guests:

© Xiaoying Gao, Peter Andreae COMP :22 Find an empty room Find the index of an empty room (return -1 if no empty rooms) public int findEmpty(int room){ for (int rm=1; rm<this.guests.length; rm++){// or <=MaxRoom if (this.guests[rm]==null) { return rm; } } return -1; } Check a guest into an empty room (return room number) public void checkIn(String name){ this.guests[ this.findEmpty() ] = name; } public boolean checkIn(String name){ int rm = this.findEmpty(); if (rm < 0) { return false; } this.guests[rm] = name; return true; } What ’ s the problem? How do we fix it? n1n1 n5n5 n8n8 n 10 n7n7 n3n3 n6n6 n4n4 guests:

© Xiaoying Gao, Peter Andreae COMP :23 Arrays of Booleans To keep track of numbers we have seen, efficiently Eg: looking for duplicates: read file, check and set Scanner sc = new Scanner(new File(FileDialog.open("file to check"))); boolean[ ] numbersSeen = new boolean[100000]; while ( sc.hasNext() ){ if ( sc.hasNextInt() ){ int num = sc.nextInt(); if ( num>=0 && num< ){ if (numbersSeen[num] ) System.out.println(num + "is a duplicate"); else numbersSeen[num] = true; } else{ String junk = sc.next(); } Initialised with false