Data Structures and Algorithms in Java

Similar documents
Solutions Manual. Data Structures and Algorithms in Java, 5th edition International Student Version. M. T. Goodrich and R.

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

University of Palestine. Mid Exam Total Grade: 100

Following is the general form of a typical decision making structure found in most of the programming languages:

Recitation: Loop Jul 7, 2008

Computer Science II Data Structures

About this exam review

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Java Primer 1: Types, Classes and Operators

Programming Problems 22nd Annual Computer Science Programming Contest

CS2 Algorithms and Data Structures Note 1

Center for Computation & Louisiana State University -

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Administrivia. HW on recursive lists due on Wednesday. Reading for Wednesday: Chapter 9 thru Quicksort (pp )

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Getting started with Java

Controls Structure for Repetition

1 If you want to store a letter grade (like a course grade) which variable type would you use? a. int b. String c. char d. boolean

EXAM Computer Science 1 Part 1

Java Programming with Eclipse

Array. Prepared By - Rifat Shahriyar

CS : Introduction to Computer Programming Final Exam December 9, Please wait to open this exam booklet until you are told to do so.

Object Oriented Programming. What is this Object? Using the Object s Slots

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Exercise (Revisited)

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

CMSC 132, Object-Oriented Programming II Summer Lecture 6:

JAVA OPERATORS GENERAL

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

COE 212 Engineering Programming. Welcome to the Final Exam Tuesday December 15, 2015

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

CS 106 Introduction to Computer Science I

CSEN 202: Introduction to Computer Programming

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

List of Known Errata. Harnessing Java 7: A Comprehensive Approach to Learning Java. (Volumes 1, 2, and 3) Kishori Sharan

Last Name: Circle One: OCW Non-OCW

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

Introduction to Computer Science Unit 2. Notes

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

CS212 Midterm. 1. Read the following code fragments and answer the questions.

CMSC131 Final Exam Practice Questions

More types, Methods, Conditionals. ARCS Lab.

CSE 1223: Exam II Autumn 2016

Data dependent execution order data dependent control flow

CS211 Spring 2005 Prelim 1 March 10, Solutions. Instructions

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Java 1.8 Programming

CIS 110 Introduction to Computer Programming 8 October 2013 Midterm

CS 61B Discussion 5: Inheritance II Fall 2014

Divide-and-Conquer. Divide-and conquer is a general algorithm design paradigm:

CS S-08 Arrays and Midterm Review 1

ESC101 : Fundamental of Computing

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

DUKE UNIVERSITY Department of Computer Science. Test 1: CompSci 100

CIS 110 Introduction to Computer Programming. 12 February 2013 Midterm. Answer Key

CS 455 Final Exam Spring 2018 [Bono] May 8, 2018

Arrays and Array Lists

Prelim 1. Solution. CS 2110, 14 March 2017, 7:30 PM Total Question Name Short answer

Assertions, pre/postconditions

ECE264 Fall 2013 Exam 1, September 24, 2013

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

CSEN 202: Introduction to Computer Programming Spring term Final Exam

Full file at

CS : Introduction to Computer Programming Final Exam December 9, Please wait to open this exam booklet until you are told to do so.

Pace University. Fundamental Concepts of CS121 1

Programming Language Concepts: Lecture 2

Chapter 8. Arrays and Array Lists. Chapter Goals. Chapter Goals. Arrays. Arrays. Arrays

Linked Structures - Review Chapter 13. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

CSE 331 Winter 2016 Midterm Solution

CSC 222: Computer Programming II. Spring 2005

public static boolean isoutside(int min, int max, int value)

JAVA WRAPPER CLASSES

Java Basic Programming Constructs

Computação I. Exercises. Leonardo Vanneschi NOVA IMS, Universidade Nova de Lisboa. Leonardo Vanneschi Computação I NOVA IMS

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

CS 1302 Chapter 9 (Review) Object & Classes

CS 11 java track: lecture 1

Example: Monte Carlo Simulation 1

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

CSC 1214: Object-Oriented Programming

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

Syntax of Variable Declarations. Variables Usages as Expressions. Self-assignment Statements. Assignment. Scoping and Naming Rules

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

CIS 110 Introduction to Computer Programming. 12 February 2013 Midterm

3. Java - Language Constructs I

Big-O-ology 1 CIS 675: Algorithms January 14, 2019

CSCI 212 Practice Final Exam Summer Instructor: Krishna Mahavadi

COE 212 Engineering Programming. Welcome to the Final Exam Thursday December 15, 2016

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Odds and Ends. Think about doing research Programming grading. Assignment 3 due Tuesday

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Chapter Seven: Arrays and Array Lists. Chapter Goals

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Module 5. Arrays. Adapted from Absolute Java, Rose Williams, Binghamton University

Introduction to Computer Science Unit 2. Notes

Transcription:

Data Structures and Algorithms in Java Sixth Edition Michael T. Goodrich Department of Computer Science University of California, Irvine Roberto Tamassia Department of Computer Science Brown University Michael H. Goldwasser Department of Mathematics and Computer Science Saint Louis University Instructor s Solutions Manual

Chapter 1 Java Primer Reinforcement Hints and Solutions R-1.1) Hint Use the code templates provided in the Simple Input and Output section. R-1.2) Hint You may read about cloning in Section 3.6. R-1.2) Solution Since, after the clone, A[4] and B[4] are both pointing to the samegameentry object, B[4].score is now 550. R-1.3) Hint The modulus operator could be useful here. R-1.3) Solution public boolean ismultiple(long n, long m) { return (n%m == 0); R-1.4) Hint Use bit operations. R-1.4) Solution public boolean iseven(int i) { return (i & 1 == 0); R-1.5) Hint The easy solution uses a loop, but there is also a formula for this, which is discussed in Chapter 4. R-1.5) Solution public int sumton(int n) { for (int j=1; j <= n; j++) total += j; return total;

2 Chapter 1. Java Primer R-1.6) Hint The easy thing to do is to write a loop. R-1.6) Solution public int sumodd(int n) { for (int j=1; j <= n; j += 2) total += j; return total; R-1.7) Hint The easy thing to do is to write a loop. R-1.7) Solution public int sumsquares(int n) { for (int j=1; j <= n; j++) total += j j; return total; R-1.8) Hint You might use a switch statement. R-1.8) Solution public int numvowels(string text) { for (int j=0; j < text.length(); j++) { switch (text.charat(j)) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': total += 1; return total; R-1.9) Hint Consider each character one at a time.

R-1.10) Hint Consider using get and set methods for accessing and modifying the values. R-1.11) Hint The traditional way to do this is to use setfoo methods, where Foo is the value to be modified. R-1.11) Solution public void setlimit(int lim) { limit = lim; R-1.12) Hint Use a conditional statement. R-1.12) Solution public void makepayment(double amount) { if (amount > 0) balance = amount; R-1.13) Hint Try to make wallet[1] go over its limit. R-1.13) Solution for (int val=1; val <= 58; val++) { wallet[0].charge(3 val); wallet[1].charge(2 val); wallet[2].charge(val); This change will cause wallet[0] to attempt to go over its limit. 3 Creativity C-1.14) Hint The Java method does not need to be passed the value of n as an argument. C-1.15) Hint Note that the Java program has a lot more syntax requirements. C-1.16) Hint Create an enum type of all operators, including =, and use an array of these types in a switch statement nested inside for-loops to try all possibilities. C-1.17) Hint Note that at least one of the numbers in the pair must be even. C-1.17) Solution

4 Chapter 1. Java Primer public boolean hasevenpair(int[ ] data) { if (data.length > 1) { for (int j=0; j < data.length; j++) if (data[j] % 2 == 0) return true; return false; C-1.18) Hint Use the Math.pow function for calculations. Use your solution for norm(v,p) to implement norm(v). C-1.18) Solution public double norm(double[ ] v, int p) { for (double k : v) total += Math.pow(k,p); double exp = 1.0/p; return Math.pow(total, exp); public double norm(double[ ] v) { return norm(v,2); C-1.19) Hint This is the same as the logarithm, but you can use recursion here rather than calling the log function. C-1.20) Hint The simple solution just checks each number against every other one, but we will discuss better solutions later in the book. Make sure you don t compare a number to itself. C-1.20) Solution public boolean distinct(float[ ] data) { for (int j=0; j < data.length 1; j++) for (int k=j+1; k < data.length; k++) if (data[j] == data[k]) return false; return true; C-1.21) Hint Consider using swaps to reshuffle the array one entry at a time, starting from the beginning and moving to the end. C-1.22) Hint There are many solutions. If you know about recursion, the easiest solution uses this technique. Otherwise, consider using an array to

hold solutions. If this still seems to hard, then consider using six nested loops (but avoid repeating characters and make sure you allow all string lengths). C-1.22) Solution Here is a possible solution: public static void permute(arraylist bag, ArrayList permutation) { // When the bag is empty, a full permutation exists if (bag.isempty() ) { System.out.println(permutation); else { // For each element left in the bag for(int i = 0; i < bag.size(); i++) { // Take the element out of the bag // and put it at the end of the permutation Object obj = bag.get(i); bag.remove(i); permutation.add(obj); // Permute the rest of the bag (recursively) permute(bag, permutation); // Take the element off the permutation // and put it back in the bag permutation.remove(permutation.size() 1); bag.add(i, obj); public static void main(string[ ] args) { ArrayList<Character> orig = new ArrayList<>(); char[ ] word = {'c', 'a', 't', 'd', 'o', 'g'; for (char c : word) orig.add(c); permute(orig, new ArrayList()); 5 C-1.23) Hint Go back to the definition of dot product and write a for loop that matches it. C-1.23) Solution

6 Chapter 1. Java Primer public int[ ] compute(int[ ] a, int[ ] b) { if (a.length!= b.length) throw new IllegalArgumentException("arrays must have same length") int[ ] c = new int[a.length]; for (int j=0; j < a.length; j++) c[j] = a[j] b[j]; return c; C-1.24) Hint The card is no longer needed as an explicit parameter. C-1.24) Solution public void printsummary() { System.out.println("Customer = " + customer); System.out.println("Bank = " + bank); System.out.println("Account = " + account); System.out.println("Balance = " + balance); System.out.println("Limit = " + limit); C-1.25) Hint You might use astringbuilder to compose the pieces of the string into one large string (including newlines). C-1.25) Solution public String tostring() { StringBuilder sb = new StringBuilder(); sb.append("customer = " + customer + System.lineSeparator()); sb.append("bank = " + bank + System.lineSeparator()); sb.append("account = " + account + System.lineSeparator()); sb.append("balance = " + balance + System.lineSeparator()); sb.append("limit = " + limit + System.lineSeparator()); return sb.tostring(); Projects P-1.26) Hint Use an array to buffer all the original lines. P-1.27) Hint You do not need to use a graphical user interface, but you may want to use the System.console() method. P-1.28) Hint Define a way of indexing all the sentences and the location in each one and then work out a way of picking eight of these locations for a typo.

P-1.29) Hint Use a two-dimensional array to keep track of the statistics and a one-dimensional array for each experiment. P-1.30) Hint We recommend using the Java Swing package. 7