Download presentation
Presentation is loading. Please wait.
Published byGeorge Manning Modified over 9 years ago
1
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Patterns with Arrays COMP 102 #22 2013 T2
2
© Xiaoying Gao, Peter Andreae COMP 102 22: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 emailed. Term test 2 will be handed back tomorrow Tutorial: Tuesday, 12-1, VZ103; Friday 3-4 MY107
3
©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
4
©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
5
©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; }
6
©Xiaoying Gao, Peter Andreae COMP 102 22: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- 12345671990 200 length CB+ “C”“C” AA-null “ A+ ” ⋯ nullA+B-null grades.txt 6543210
7
©Xiaoying Gao, Peter Andreae COMP 102 22: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- 123451990 200 length CB+AA- ⋯ null A+B- grades: What's the problem? count: 6 grades.txt
8
© Xiaoying Gao, Peter Andreae COMP 102 22: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); } } 12345500 length: 50 bensalkitann may jandon ⋯ names: n: array passed in as a parameter “ For each ” loop Steps through each item in array
9
© Xiaoying Gao, Peter Andreae COMP 102 22: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
10
© Xiaoying Gao, Peter Andreae COMP 102 22:10 Arrays of objects, more carefully public void printAll(String [ ] names ){ for (String n : names){ n = n + “ Junior”; } } 12345500 length: 50 ⋯ names: count: 6 n: ben sal kit ann may jan don
11
© Xiaoying Gao, Peter Andreae COMP 102 22: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
12
© Xiaoying Gao, Peter Andreae COMP 102 22: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; } } 12345500 length: 50 56184119 27 3024 ⋯ mk:
13
© Xiaoying Gao, Peter Andreae COMP 102 22: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
14
© Xiaoying Gao, Peter Andreae COMP 102 22: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.
15
© Xiaoying Gao, Peter Andreae COMP 102 22: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 516768 79788290 length: 8 compare with next item: stop before length-1 compare with previous item: start at 1 Can’t use for each!
16
© Xiaoying Gao, Peter Andreae COMP 102 22: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?
17
© Xiaoying Gao, Peter Andreae COMP 102 22: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); }
18
© Xiaoying Gao, Peter Andreae COMP 102 22: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 700620460 450380220510480 012345678910 n1n1 n5n5 n8n8 n 10 n7n7 n3n3 n6n6 n4n4 012345678910111213141516 2 9 31 15804100 0123456789 4 89 69091 858687 7 2 85 39214
19
© Xiaoying Gao, Peter Andreae COMP 102 22: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: 012345678910111213141516 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
20
© Xiaoying Gao, Peter Andreae COMP 102 22: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: 012345678910111213141516
21
© Xiaoying Gao, Peter Andreae COMP 102 22: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: 012345678910111213141516
22
© Xiaoying Gao, Peter Andreae COMP 102 22: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: 012345678910111213141516
23
© Xiaoying Gao, Peter Andreae COMP 102 22: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<100000 ){ if (numbersSeen[num] ) System.out.println(num + "is a duplicate"); else numbersSeen[num] = true; } else{ String junk = sc.next(); } Initialised with false
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.