ITI 1120 Lab #12 Contents: 2004 exam, and how to solve it!

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Introduction to C Programming
Introduction to arrays
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Searching Kruse and Ryba Ch and 9.6. Problem: Search We are given a list of records. Each record has an associated key. Give efficient algorithm.
True or false A variable of type char can hold the value 301. ( F )
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Java Syntax Primitive data types Operators Control statements.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Chapter Eight: Arrays 1.Terms and what they mean 2.Types of arrays -One Dimensional arrays -Two Dimensional arrays -ragged arrays -Parallel arrays 3. Methods.
Loops Chapter 4. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while” structures.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Midterm Test Overview CS221 – 3/23/09. Test Curve Current median is a 71 or C- Median will be adjusted to an 81 or B- All test scores will be +10 on.
More Arrays Length, constants, and arrays of arrays By Greg Butler.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Chapter 9 Searching and Sorting
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
CSC 211 Data Structures Lecture 13
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Introduction to Java Java Translation Program Structure
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Question 1a) What is printed by the following Java program? int s; int r; int i; int [] x = {4, 8, 2, -9, 6}; s = 1; r = 0; i = x.length - 1; while (i.
ITI 1120 Lab #5 Contributors: S. Boyd, R. Plesa, A. Felty, D. Inkpen, A. Williams, D. Amyot.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
ITI 1120 Lab #11 Contributors: Diana Inkpen, Daniel Amyot, Sylvia Boyd, Amy Felty, Romelia Plesa, Alan Williams.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
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];
Data Structures Arrays and Lists Part 2 More List Operations.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
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.
CSCI 51 Introduction to Programming March 10, 2009.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
ITI 1120 Lab #10 Objects and Classes Slides by: Romelia Plesa, Sylvia Boyd, Alan Williams, Diana InkPen, Daniel Amyot, Gilbert Arbez, Mohamad Eid.
Midterm preview.
Information and Computer Sciences University of Hawaii, Manoa
CprE 185: Intro to Problem Solving (using C)
Yanal Alahmad Java Workshop Yanal Alahmad
Multiple variables can be created in one declaration
Searching.
ITI Introduction to Computing II Lab-12
CSC 1051 – Data Structures and Algorithms I
Question 1a) What is printed by the following Java program? int s;
Just Enough Java 17-May-19.
Presentation transcript:

ITI 1120 Lab #12 Contents: 2004 exam, and how to solve it!

Question 1A[4] Environment Canada will report a humidex value as part of a weather forecast if the temperature (T) is greater than or equal to 30 degrees, if the temperature is greater than or equal to 25 degrees and the humidity (H) is greater than 35%, or the temperature is greater than or equal to 20 degrees and the humidity is greater than or equal to 65%. Write a Boolean expression that is true if Environment Canada will report a humidex value, and false otherwise.

Question 1A Environment Canada will report a humidex value as part of a weather forecast if the temperature (T) is greater than or equal to 30 degrees, if the temperature is greater than or equal to 25 degrees and the humidity (H) is greater than 35%, or the temperature is greater than or equal to 20 degrees and the humidity is greater than or equal to 65%. Answer: T ≥ 30 OR (T ≥ 25 AND H > 35) OR (T ≥ 20 AND H ≥ 65)

Question 1B[4] Consider the following Java program : MyClass[] obj; int index; obj = new MyClass[2]; index = 15; while( index > 2 ) { obj[index % 2] = new MyClass( ); index = index / 2; } // Line X How many instances of MyClass are created during the execution of this program? [2] How many instances of MyClass are still accessible at Line X ? [2]

Question 1B objindex# objects Initial values ?? obj = new MyClass[2]; index = 15; 15 while( index > 2 ) : true obj[index % 2] = new MyClass( ); 1 index = index / 2; 7 while( index > 2 ) : true  

Question 1B objindex# objects From previous page 71 obj[index % 2] = new MyClass( ); 2 index = index / 2; 3 while( index > 2 ) : true obj[index % 2] = new MyClass( ); 3 index = index / 2; 1 while( index > 2 ) : false    Number of objects created: 3Number still accessible: 1

Question 1C [4] class Foo { private int x1; public static int x2; public static Bar x3; public Foo(int x4) {... } class Bar { public int x5; public static int x6() {... } public Foo x7() {... } Suppose that the following instructions are used in the main() method in a class Test. Each choice should be considered independently – as it if were in its own main() method. Circle the letter of the statement which causes a compilation error. (a) Foo[] a = new Foo[5];d) int k = Foo.x3.x5; a[4] = new Foo(-1); (b) Foo f = Bar.x7();e) Bar b = new Bar(); (c) Foo.x2 = Bar.x6(); Foo f = b.x7();

Question 1C class Foo { private int x1; public static int x2; public static Bar x3; public Foo(int x4) {... } class Bar { public int x5; public static int x6() {... } public Foo x7() {... } a) OK Foo[] a = new Foo[5]; a[4] = new Foo(-1); Declare and create an array of 5 Foo object references. The references are all null. There is a public Foo constructor with 1 integer parameter.

Question 1C class Foo { private int x1; public static int x2; public static Bar x3; public Foo(int x4) {... } class Bar { public int x5; public static int x6() {... } public Foo x7() {... } b) Compile error Foo f = Bar.x7(); The method x7() in the Bar class does not have the keyword static, so it is an instance method. Instance methods cannot be called using the class name.

Question 1C class Foo { private int x1; public static int x2; public static Bar x3; public Foo(int x4) {... } class Bar { public int x5; public static int x6() {... } public Foo x7() {... } c) OK Foo.x2 = Bar.x6(); The method x6() in the Bar class is public, static, and returns a value of type int. Because of the static keyword, the method can be called via the class name. The value x2 in the Foo class is public, static, and of type int. Since the value is static, it is a class variable, and since it is public, it can be accessed outside the class.

Question 1C class Foo { private int x1; public static int x2; public static Bar x3; public Foo(int x4) {... } class Bar { public int x5; public static int x6() {... } public Foo x7() {... } d) OK int k = Foo.x3.x5 The value x3 in the Foo class is public, static, and of type Bar. Because the value is public, x3 can be accessed outside the class, and because it is static, it can be accessed via the class name. In the class Ba r, the value x5 is public and of type int. Therefore, x5 can be accessed from outside of the class, and assigned to a variable of type int.

Question 1C class Foo { private int x1; public static int x2; public static Bar x3; public Foo(int x4) {... } class Bar { public int x5; public static int x6() {... } public Foo x7() {... } e) OK Bar b = new Bar(); Foo f = b.x7(); Declare and create a new Bar() object. The invisible default constructor is used, since no constructors are defined. Method x7() is a public instance method, so it can be called on a Bar object. It returns an object of type Foo, which can be assigned to f.

Question 2[8] class Football { public static void main(String[ ] args) { char[] t = {'G', 'e', 'e', '-', 'G', 'e', 'e'}; Rec(t, t.length - 1); } public static void Rec(char[] var, int i) { if (i < 0) { ; // do nothing } else { if ( (var[i] > 'A') && (var[i] < 'Z') ) { System.out.print( (char) (var[i] - 'A' + 'a') ); } else { if ( (var[i] > 'a') && (var[i] < 'z') ) { System.out.print( (char) (var[i] - 'a' + 'A') ); } else { ; // do nothing } Rec(var, i - 1); } Here is a program that uses recursion. What is printed by this program?

Question 2 Let’s look at various parts of the program: if ( (var[i] > 'A') && (var[i] < 'Z') ) { System.out.print( (char) (var[i] - 'A' + 'a') ); } The above will take any upper case letter (except for ′A′ and ′Z′ ) at index i in the array var, convert it to lower case, and display the character on the console.

Question 2 if ( (var[i] > 'a') && (var[i] < 'z') ) { System.out.print( (char) (var[i] - 'a' + 'A') ); } The above will take any lower case letter (except for ′a′ and ′z′ ) at index i in the array var, convert it to upper case, and display the character on the console.

Question 2 class Football { public static void main(String[ ] args) { char[] t = {'G', 'e', 'e', '-', 'G', 'e', 'e'}; Rec(t, t.length - 1); } public static void Rec(char[] var, int i) { if (i < 0) { ; // do nothing } else { // if var[i] is upper case, convert to lower case and print it // else if var[i] is lower case, convert to upper case and print it // else do nothing Rec(var, i - 1); }

Question 2 public static void Rec(char[] var, int i) { if (i < 0)// Recursion base case { ; // do nothing } else { // do stuff with var[i] Rec(var, i - 1);// Recursive call } The above will go through the array var in the backwards direction; that is, the index i will be decreasing down to 0.

Question 2 public static void main(String[ ] args) { char[] t = {'G', 'e', 'e', '-', 'G', 'e', 'e'}; Rec(t, t.length - 1); } The method Rec will start from the end of the array t, change the case of each letter (ignoring non-letter characters), and print it. The result: EEgEEg

Question 3[15] Translate the following algorithm to a Java method: GIVENS: Base: (a logarithm base, known to be > 0) Operand:(an array of integers for which to find the integer logarithm) N(the number of values in array Operand) RESULT: IntLog:(an array of N integer logarithms for the values in array Operand; a value of -1 is returned if the logarithm does not exist) INTERMEDIATES: Index(array index) Value(used for repeated divisions) Count(counts number of times an operand can be divided by base) HEADER:IntLog  Logarithms( Base, Operand, N )

Question 3 BODY: Index < N ? Value ≥ Base Value ← Value / Base Count ← Count + 1 Value ← Operand[Index] Count ← 0 IntLog[Index] ← Count Operand[Index] > 0 ? IntLog[Index] ← – 1 Index ← 0 IntLog ← CreateNewArray(N) true false Index ← Index + 1

Question 3 public static int[] logarithms( int base, int[] operand, int n) { int intlog;// RESULT: An array of logarithms for the values in operand int index; int value; int count; index = 0; intlog = new int[n]; while ( index < n ) { if ( operand[index] > 0 ) { value = operand[index]; count = 0; while ( value >= base ) { value = value / base; count = count + 1; } intlog[index] = count; } else { intlog[index] = -1; } index + index = 1; } return intlog; }

Question 4[15] Olympic 10 metre platform diving events are scored as follows. Each judge watches an athlete's dive, and then submits a score for the dive (out of 10). The dive is also previously assigned a "degree of difficulty" (DD) based on the complexity of the particular dive (example: forward 2 1/2 somersault in the tuck position has DD = 2.7). The highest and lowest scores are discarded, and the remaining scores are added together and then multiplied by the degree of difficulty to determine the total dive score. Write an algorithm that will compute an athlete's total dive score from an array of scores submitted by N judges, for a dive of degree of difficulty DD.

Question 4 GIVENS: Scores(An array of judges’ scores) N(The length of array Scores) DD(Dive’s degree of difficulty) RESULT: Final(The diver’s final score) INTERMEDIATES: Index(Index for array Scores) Sum(Sum of values in array Scores) Max(Maximum score) Min(Minimum score) HEADER: Final ← DetermineFinalScore( Scores, N, DD )

Question 4 BODY: Index < N Scores[Index] > Max Max ← Scores[Index] Sum ← Sum + Scores[Index] Index ← Index + 1  true Max ← Scores[0] Min ← Scores[0] Sum ← Scores[0] Index ← 1 true false Final ← DD × ( Sum – Max – Min ) Scores[Index] < Min Min ← Scores[Index]  false true false

Question 5[15] The lower right sub-matrix of a matrix is formed by selecting one element position (row and column) and excluding all elements that are to the left or above the selected element. For example, in the matrix M below, if we select M 11 = 5, the matrix S is the lower right sub- matrix. Write a Java method that will take a matrix of integers M, and a row and column index, and returns a new matrix that is the lower right sub-matrix of M formed from that position. The header of the method is as follows: public static int[][] subMatrix( int[][] m, int theRow, int theCol )

Question 5 public static int[][] submatrix( int[][] m, int theRow, int theCol ) { int[][] s; // RESULT: the submatrix of matrix m int sRows; // INTERMEDIATE : number of rows in s int sCols; // INTERMEDIATE : number of columns in s int row; // INTERMEDIATE: index for row position in s int col; // INTERMEDIATE: index for column position in s sRows = m.length - theRow; sCols = m[0].length - theCol; s = new int[sRows][sCols]; for ( row = 0; row < sRows; row = row + 1 ) { for ( col = 0; col < sCols; col = col + 1 ) { s[row][col] = m[row + theRow][col + theCol] ; } return s; }

Question 6[25] In this question, you will create a class Experiment that represents a record of some sort of scientific experiment. In order to verify that the results of an experiment are repeatable, there is a class Trial that contains the results from one run of an experiment. An experiment will then include a number of Trial objects.

Question 6 The class Trial stores a result that was measured during an experiment, and the duration that the experiment took, measured in milliseconds. The class Trial has already been implemented. A UML class diagram for the class Trial is as follows: Trial - result : double - duration: int + Trial( theResult : double, theDuration : double ) + getResult( ) : double + getDuration( ) : int

Question 6 In the rest of this question, you will fill in the methods for Experiment. Your Experiment class should provide four public methods and/or constructors that would permit the following class TestExperiment to execute: class TestExperiment { public static void main (String[] args) { Experiment anExperiment; anExperiment = new Experiment( 2 ); anExperiment.addTrial( new Trial( 99.1, ) ); anExperiment.addTrial( new Trial( 97.1, ) ); anExperiment.addTrial( new Trial( 94.1, ) ); Experiment.setPredictedResult( 98.6 ); anExperiment.print(); } Executing main() would result in the following being printed on the screen : No more trials can be added to the experiment. Trial 0: Result 99.1, duration (within 0.5 of prediction) Trial 1: Result 97.1, duration (within 1.5 of prediction)

Question 6 class Experiment { // FIELD DECLARATION(S): (4 marks) // CONSTRUCTOR: (5 marks) // Takes one integer parameter representing the maximum // number of trials that can be put into the experiment

Question 6 class Experiment { // FIELD DECLARATION(S): (4 marks) private Trial[] trials; private int numTrials; private static double prediction; // CONSTRUCTOR: (5 marks) // Takes one integer parameter representing the maximum // number of trials that can be put into the experiment public Experiment( int maxTrials ) { trials = new Trial[maxTrials]; numTrials = 0; }

Question 6 // METHOD setPredictedResult: (4 marks) // Method parameters: a double that is the predicted result // of the experiment. // RESULT: none

Question 6 // METHOD setPredictedResult: (4 marks) // Method parameters: a double that is the predicted result // of the experiment. // RESULT: none public static void setPredictedResult( double newPrediction ) { prediction = newPrediction; }

Question 6 // MODIFIER METHOD addTrial: (6 marks) // Method parameters: a Trial object that should be added to the Experiment. // Results: will print a message if the experiment has no room to store // additional trials (see sample output for message format) // Modified: the Experiment object

Question 6 // MODIFIER METHOD addTrial: (6 marks) // Method parameters: a Trial object that should be added to the Experiment. // Results: will print a message if the experiment has no room to store // additional trials (see sample output for message format) // Modified: the Experiment object public void addTrial( Trial newTrial ) { if ( numTrials >= trials.length ) { System.out.println("No more trials can be added to the experiment."); } else { trials[numTrials] = newTrial; numTrials = numTrials + 1; }

Question 6 // METHOD print: (6 marks) // Method parameters: (none) // Returns: (none) // This method prints the result and duration of each trial, along with // the absolute value of the difference from the predicted result. // See the TestExperiment sample output for exact format.

Question 6 // METHOD print: (6 marks) // Method parameters: (none) // Returns: (none) // This method prints the result and duration of each trial, along with // the absolute value of the difference from the predicted result. // See the TestExperiment sample output for exact format. public void print() { int index; double aResult; double difference; for ( index = 0; index < numTrials; index = index + 1 ) { aResult = trials[index].getResult(); difference = Math.abs( aResult – prediction ); System.out.print("Trial " + index + ": " ); System.out.print("Result " + aResult + ", " ); System.out.print("Duration " + trials[index].getDuration() + ", " ); System.out.println("(within " + difference + " of prediction)" ); }

Question 7[10] Question 7: recursive binary search public static boolean searchRec( int[] valueList, int findMe, int leftIndex, int rightIndex ) { // DECLARE VARIABLES / DATA DICTIONARY boolean found; // RESULT: True if search is successful, and false otherwise. int mid; // Index of array closest to the midpoint between leftIndex // and rightIndex // BODY OF ALGORITHM // Check for base case. The base case covers 2 situations: leftIndex and rightIndex // are the same, or they are two consecutive array positions. The latter case is // needed as there is no useful midpoint between two consecutive array // positions, and the possibility of not reducing the size of the interval. if ( leftIndex + 1 >= rightIndex ) { // For the base case, if the value doesn't match one of the two possible // endpoints, the value is not in the array. found = findMe == valueList[leftIndex] || findMe == valueList[rightIndex]; }

Q7 continued else { // Determine array position closest to the midpoint between leftIndex and rightIndex. mid = ( leftIndex + rightIndex ) / 2; // Compare with value at midpoint. if ( findMe == valueList[mid] ) {// We got lucky and found the value. found = true; } else {// Decide whether the value, if it were present, would be to the // left of the midpoint or to the right of the midpoint. if ( findMe < valueList[mid] ) { // Value is on left side of midpoint. Search left half of array recursively. found = searchRec( valueList, findMe, 0, mid ); } else { // Value is on the right side of the midpoint. Search right half of array // recursively. found = searchRec( valueList, findMe, mid, rightIndex ); } return found; // RETURN RESULT }