Download presentation
Presentation is loading. Please wait.
Published byClaude McCoy Modified over 9 years ago
1
Lecture 9: Technique
2
Exercise Create a method called duplicates that returns a boolean value. The method takes, as its argument, an array of strings and returns true if the array contains any duplicates. The method returns false otherwise.
3
Solution public static boolean duplicates(String[] s) { for (int i = 0; i < s.length() – 1; i++) { for (j = i + 1; j < s.length(); j++) { if (s[i].equals(s[j])) return (true); } return (false); }
4
Solution import java.util.Arrays; public static boolean duplicates(String[] s) { Arrays.sort(s); for (int i = 0; i < s.length() – 1; i++) { if (s[i].equals(s[i+1])) return (true); } return (false); }
5
Subtypes (Ch. 8) We can extend types (e.g., classes) by adding stuff to them to create subtypes The subtype/subclass has everything the supertype/superclass (its parent) has, but it has extra methods and data Two important concepts 1. Implementation Inheritance: A subclass inherits and can use all the methods and data fields of its parent 2. Inclusion Polymorphism: An instance of a subclass can be used anywhere an instance of the parent (superclass) can be used
6
Interfaces (Ch. 8) We can name an interface and save it in a Java file Other classes can implement the interface Provides programmers with knowledge of the methods that the class will provide Makes ADTs more formal public interface printable {... } public class photograph implements printable {... }
7
Binary Search (11.2) Requires sorted data Check the middle item if (key > middle) – know it is in upper half so discard lower half if (key < middle) – know it is in lower half so discard upper if (key == middle) – well, we found it, we're done Repeat on the half we have left until we find it or there is nothing left! If we do this to completion, we will take at most log 2 (data.length) comparisons at most
8
Binary Search – Implemented public static int bsearch (int[] data, int val) { int lo = 0, hi = data.length – 1, mid; while (lo <= hi) { mid = (lo + hi) / 2; if (val < data[mid]) { hi = mid - 1; } else if (val > data[mid]) { lo = mid + 1; } else { return (mid); } return (-1) ; } // end bsearch()
9
Recursion (Ch. 11) Recursion is an advanced technique that can be used to make programs simpler Simply put, recursion is when a method that calls itself Recursion can be used, mostly in place of complex loops, for problems in that can be broken down into Identical sub-problems for which the data is simpler/smaller Binary search is a good example Not tested – OK not to know this the bonus on the final will use recursion
10
Examples String equality: -- first characters the same -- rest of the strings are the same Summing an array -- add the first value to the sum of the rest of the array Palindrome -- the first character == the last character -- the rest of the string is a palindrome
11
Principles There must be a way to create a smaller identical sub- problem There must be some way to solve the part we removed and combine its solution with that of the subproblem There must be some sort of base-case, a most simple situation where there are no more subproblems and the process can stop
12
Example public boolean palindrome (String s) { if (s.length() < 2) return true; else return ( (s.charAt(0) == s.charAt(s.length()-1)) && palindrome (s.substring(1,s.length()-1)) ); }
13
General Approach 1. Identify the “Base Case”: When we can stop recursing 2. For the other cases: a) Simply b) Solve sub-problems c) Combine solutions to sub-problems Note: Recursive solutions can be very short and elegant, but can also (sometimes) be very inefficient
14
Example 2 public boolean reverse (String s) { if (s.length() < 2) return s; else return ( s.charAt(s.length()-1)) + reverse (s.substring(0, s.length()-1)) ); } Idea: Add the last character to the front of the rest of the string when its reversed
15
Binary Search – Recursive public int bsearch (int key, int[] data, int lo, int hi) { int mid = lo + (hi - lo) / 2; if (lo > hi) return (-1); else if (key < data[mid]) return (bsearch(key, data, lo, mid-1)); else if (key > data[mid]) return (bsearch(key, data, mid+1, hi)); return (mid); // were equal } // end bsearch()
16
Exercise We have seen the Fibonacci numbers before. They are: 1, 1, 2, 3, 5, 8, 13, 21,... By definition, fib(1) = 1 fib(2) = 1 fib(n) = fib(n-1) + fib(n-2) Write a recursive method to find the i th Fibonacci number. public static int fib(int i) {...}
17
Solution public static int fib(int i) { // base cases, i = 1 or 2 if (i < 3) return (1); // recursive case return (fib(i-1) + fib(i-2)); } Note: This is one of the instances where recursion is very elegant but sadly is also very inefficient
18
Inefficiency fib(5) = fib(4) + fib(3) = (fib(3) + fib(2)) + (fib(2) + fib(1)) = ((fib(2) + fib(1)) + fib(2)) + (fib(2) + fib(1)) = 1 + 1 + 1 + 1 + 1 = 5 Problem: fib(3) is calculated more than once fib(9) = fib(8) + fib(7) = fib(7) + fib(6) + fib(6) + fib(5) = fib(6) + fib(5) + fib(5) + fib(4) + fib(5) + fib(4) + fib(4) + fib(3) Some, not all, recursion is inefficient
19
TESTING The LAST LINE OF DEFENSE! Relying on testing is dangerous and leads to low-quality products Be Proactive NOT Reactive Good design and planning prevents faults and is far better than relying on testing # of Faults # LOC Faults are often clustered: Where there is one, there is usually another Fixing faults frequently introduces new faults, or reveals previously undetectable faults Faults frequently NOT fixed because the actual problem has not been identified
20
Approaches There are lots of testing methodologies We are going to look at two 1. Code Coverage – focuses on control flow 2. Data Driven – focuses on data values Both can (and should) be used Neither is 100% effective
21
Code Coverage Your test data should be such that every line of code is executed at least once in the test process Every method is called Every branch of every if statement is used Every loop executes at least once More difficult than it sounds for complex programs with things nested many times Only works when you can examine the code, won't work for library code
22
Data Driven Your test suite should contain data that 1. Matches an average/typical use 2. Is an extreme e.g., maximum int, minimum int, largest array, empty array 3. Is a critical value that could cause different behaviour e.g., 0 is special in a lot of math Difficult to find these values, requires a lot of insight and experience
23
Example public static boolean compare(String s1, String s2) {} Data to test s1 is "" or nul l, s2 is "" or null, and all combos of this s1 = s2, s1 ≠ s2 s1 is a prefix, suffix, substring of s2 (and same for s2 with respect to s1 ) Strings are 1 character, 10 chars (average), thousands of characters (long) Now, create data that does this for EVERY method in the program... as you should see, testing is very time consuming and difficult
24
System Testing Sanity Checks (by Programmers)Functional Tests Non-Functional Tests (Performance) Acceptance & Installation TestsSYSTEM IN USE! (Live)
25
Functional Testing Does the software do what its supposed? Try to minimise the number of tests while still testing the software fully Optimal (complete) testing is unfeasible! Too many paths Too many different input combinations (including bad data) Often uses half of software development time and budget Writing the program is half the job, ensuring its right is the other half
26
Non-Functional Testing (Performance) Stress – max users, requests, devices Volume – max data Configuration – all hardware combinations Compatibility – with other systems Regression – with system being replaced Security – is it safe Timing – performance, efficiency, response speed Environmental – use site (heat, humidity, vibration) Quality – MTF, MTBF Recovery – equipment failure, data loss Maintenance – diagnostic tools and procedures work Documentation – sufficient/correct documentation exists Human factors – “usability”
27
Regression Testing Tests applied when a working version is changed Verifies it functions in the same manner as the previous version Should be used in iterative/incremental development When we add code: 1. Regression test – does it do what it used to do? 2. Functional testing – does it do the new stuff right? 3. Performance testing – is it fast enough, secure, and usable?
28
Acceptance Testing Convince the customer it works Generally involves the requirements team Benchmark Test: Typical Cases representative of use Pilot Test: Use on an experimental basis Alpha Testing: Testing of installed software by development organisation (e.g., programmers or professional testers) Beta Testing: Testing of installed software by client organisation (e.g., users) Parallel Testing: New system run in parallel with existing system and results compared
29
Fault Reports A. Admin – tester, test #, site, equipment, date B. Location – where did it occur C. Timing – any details possible, sequencing D. Symptom – how you knew it was a fault E. End-result – failure caused, consequences F. Mechanism – how to make it happen again G. Cause – type of error that caused it H. Severity – with respect to performance and application domain I. Cost – to fix and its impact on application domain Not all of these can be clearly answered Components often overlap REPRODUCIBILITY is the key!
30
Fault (Bug) Trackers Also known as issue trackers Large number exist Generally an interface to a DB system Wide variety of features May be integrated with other systems (RCS, IDE) http://en.wikipedia.org/wiki/Comparison_of_issue-tracking_systems
31
Thoughts Testing cannot remove all faults Safety, reliability, and security are NOT the same thing Assume users will make every mistake possible (and then some) Review, review, and then review again Short-term costs should not overshadow long-term risks and costs
32
Exercise The median of a data set is the middle value when the values are sorted. If there is an even number, it is the average of the two middle values. Write a method called median() that finds the median of an array of doubles.
33
Solution public static double median(double[] data) { int len = data.length, half = len / 2; double[] d = new double[len]; for (int i = 0; i < len; i++) { d[i] = data[i]; } Arrays.sort(d); if ((len % 2) == 0) { return ((d[half-1]+d[half])/2.0); } else { return (d[half]); }
34
Cutting a Problem in Half The concept of binary search is based on the idea of cutting a problem in half Each time we check a value, we can get rid of half the remaining data The same principle can be used in other place Once place where it can be used is to solve almost any math equation using a technique called bisection
35
Bisection Need a range, (lo..hi), that we know the answer must be in Thus: lo < answer < hi Then we solve the equation just like binary search Test midpoint of the range If too low, then raise lo to mid If too high, then lower hi to mid Otherwise we found the answer
36
Finding a Cube Root We want to implement cubeRoot(x) No provided Math function for this We can random try different answers, say y if (y * y * y) > x, y is too big if (y * y * y) < x, y is too small if (y * y * y) == x, then we know y is the cubeRoot of x We know y must be between 0 and x (ignore negative roots for this example) So, we apply bisection to get an answer
37
Implementation public static double cubeRoot (double x) { double lo = 0, hi = x, mid, midCubed; while (true) { mid = (hi + lo) / 2.0; midCubed = mid * mid * mid; if (Math.abs(x-midCubed) <.00001) return (mid); else if (midCubed > x) hi = mid; else // ans < x otherwise lo = mid; } // end while } // end cubeRoot()
38
Getting Close We can almost never get the exact right answer Floating point math is never precise E.g., (1.0 / 3.0) * 3.0 ≠ 1.0 Thus, we only ever try to get close if ((desired – found) <.00001)... desired might be smaller than found if ((found - desired) <.00001)... We generally combine the two tests if (Math.abs(found-desired) <.00001)... Can use a much smaller tolerance than.00001 if we want more accuracy
39
Generalising Bisection public static double solve () { // solves: x^2 + 4 = 100 double lo = -1000.0, hi = 1000.0, mid, found; while (true) { mid = (hi + lo) / 2.0; found = (mid * mid) + 4.0; // Equation we are solving if (Math.abs(found – 100.0) <.00001) //.00001 is the tolerance return (mid); else if (found > x) hi = mid; else // found < x otherwise lo = mid; } // end while } // end solve() ONLY THE COLOURED STUFF CHANGES!
40
Testing Bisection How do we test this method? Code coverage – ensure every line is executed HARD – depends on factors we can't easily predict What inputs will cause all branches to be taken? Data driven 0 : interesting to multiply 1 : all roots are always 1 7, 8, 9 : values a known cube, 2.007,.008,.009 : values a known cube,.2
41
Returning Multiple Values If we want a method to return more than one value we have several options 1. If they are the same type (e.g., both int) we could use an array 2. Sometimes we can combine them, return them, and then them apart e.g., concatenate two strings with a symbol between them so we know where to break them into two strings later 3. We can create a new object that stores the values and returns that (no limitations, always works)
42
Example 1 public static String[] getNames1() { String[] names = new String[2]; Scanner s = new Scanner (System.in); System.out.print("First name: "); names[0] = s.next(); System.out.print("Last name: "); names[1] = s.next(); return (names); }
43
Application 1 String[] names = getNames1(); System.out.printf("%s %s\n", names[0], names[1]); Requires the user of getNames1() to know that the first name is in index 0 and the last name is in index 1
44
Example 2 public static String getNames2() { Scanner s = new Scanner (System.in); System.out.print("First name: "); String n1 = s.next(); System.out.print("Last name: "); String n2 = s.next(); return (n1 + "&" + n2); }
45
Application 2 String names = getNames2(); int marker = names.indexOf("&"); System.out.printf("%s %s\n", names.substring(0,marker), names.substring(marker+1)); Requires the user of getNames2() to know that the names are separated by the character &
46
Example 3 public class fullname { String first, last; } public static fullname getNames3() { fullname n = new fullname(); Scanner s = new Scanner (System.in); System.out.print("First name: "); n.first = s.next(); System.out.print("Last name: "); n.last = s.next(); return (n); }
47
Application 3 fullname n = getNames3(); System.out.printf("%s %s\n", n.first, n.last); Requires the user of getNames3() to know that the details of the class fullname
48
Queues A Queue is an ADT that functions like a bank line-up. Where a stack was FILO (first in, last out), a queue is FIFO (first in, first out) Instead of push and pop, the interface methods are enqueue and dequeue We usually implement a queue using a "circular array" That is, when we hit the back of the array, we wrap around to the front of the array.
49
Exercise Implement a queue given the following interface: public interface FIFO { public void enqueue(int val) throws Exception; public int dequeue() throws Exception; public int count(); } count returns the number of items currently in the queue. Add a constructor that initialises an empty queue to a provided size. (Note, interfaces in Java can't contain constructors).
50
Solution public class queue implements FIFO { private int numItems, head, tail; private int[] data; public queue (int size) { data = new int[size]; head = 0; tail = 0; numItems = 0; } public void enqueue(int val) throws Exception { if (numItems == data.length) throw Exception ("Overflow"); data[tail++] = val; numItems += 1; tail = tail % data.length; } public int dequeue() throws Exception { int v; if (numItems == 0) throw new Exception ("Underflow"); v = data[head++]; head = head % data.length; numItems -= 1; return (v); } public int count() { return (n); } }
52
To Do Read Chapter 11 on Recursion (optional) Assignment solutions are in the process of being posted online Start preparing for the final exam Program, Program, Program Do Assignment 9 in the lab today CHANGE: You may bring as many pages as you want of HANDWRITTEN notes to the final exam! No 2 page limit now exists. Make all the notes you want
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.