Solutions to Quiz 2 (April 27, 2018)

Similar documents
Solutions to Quiz 1 (March 22, 2019)

Quiz 2 (November 20, 2015)

Quiz 1 (October 25, 2017)

Solutions to Quiz 1 (October 25, 2017)

Solutions to Quiz 1 (March 14, 2016)

Solutions to Quiz 2 (December 3, 2018)

Quiz 2 (April 22, 2016)

Quiz 1 (March 14, 2016)

Quiz 2 (December 3, 2018)

CSC 1351: Quiz 6: Sort and Search

Solutions to Quiz 1 (October 19, 2015)

Quiz 2 (November 28, 2016)

Recursion and collections

CSE wi Midterm Exam 2/8/18. Name UW ID #

CSE wi Midterm Exam 2/8/18 Sample Solution

6.170 Lecture 7 Abstract Data Types MIT EECS

CSE 331 Midterm Exam Sample Solution 2/13/12

CSE 331 Midterm Exam 2/13/12

Introduction to Programming Using Java (98-388)

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

CSE331 Winter 2014, Midterm Examination February 12, 2014

Recursion (Part 2) 1

CSE 131 Introduction to Computer Science Fall Exam II

Indirect measure the measurement of an object through the known measure of another object.

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, Instructions

COS 126 Midterm 1 Written Exam Fall 2012

L13: Synchronization

WHOLE NUMBER AND DECIMAL OPERATIONS

Announcements. Testing. Announcements. Announcements

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Classes, interfaces, & documentation. Review of basic building blocks

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Sec$on 2: Specifica)on, ADTs, RI WITH MATERIAL FROM MANY

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help

CSE 143 Section Handout #13 Practice Midterm #5

Ryerson University Department of Electrical & Computer Engineering COE618 Midterm Examination February 26, 2013

CIS 120 Midterm II November 8, Name (printed): Pennkey (login id):

INTRODUCTION TO SOFTWARE SYSTEMS (COMP1110/COMP1140/COMP1510/COMP6710)

1 Method Signatures and Overloading (3 minutes, 2 points)

CIT 590 Homework 6 Fractions

CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016

CIS 120 Final Exam May 7, Name (printed): Pennkey (login id):

CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016

JAVA OPERATORS GENERAL

Representation Invariants and Abstraction Functions

CSE 331 Midterm Exam Sample Solution 2/18/15

Concurrency Quiz: Java Threads

Exam 1 CSCI 2600 Principles of Software October 6, 2015

CS 455 Midterm Exam 1 Fall 2017 [Bono] Thursday, Sep. 28, 2017

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012

Project Compiler. CS031 TA Help Session November 28, 2011

CIS 110 Introduction to Computer Programming. February 29, 2012 Midterm

CPSC 121 Some Sample Questions for the Final Exam Tuesday, April 15, 2014, 8:30AM

Introduction to Computing II (ITI 1121) Final Examination

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

CS 101 Spring 2007 Midterm 2 Name: ID:

Assertions. Assertions - Example

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Top Down Design vs. Modularization

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014

CSE 331 Final Exam 3/16/15 Sample Solution

Java Fundamentals (II)

CS/ENGRD2110: Final Exam

COS 126 Midterm 1 Written Exam Fall 2011

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT. Object Oriented Programming

Java Collections Framework: Interfaces

CS 520 Theory and Practice of Software Engineering Fall 2017

2-9 Operations with Complex Numbers

Give one example where you might wish to use a three dimensional array

Data Abstraction and Specification of ADTs

COS 126 General Computer Science Fall Written Exam 1

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Exponents and Real Numbers

CSC 207H Fall L Java Quiz Duration 25 minutes Aids allowed: none

CS 520 Theory and Practice of Software Engineering Fall 2017

Interfaces & Generics

Learning Log Title: CHAPTER 3: ARITHMETIC PROPERTIES. Date: Lesson: Chapter 3: Arithmetic Properties

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

MIDTERM EXAMINATION - CS130 - Spring 2003

CSE 331 Summer 2016 Final Exam. Please wait to turn the page until everyone is told to begin.

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking

CS 351 Design of Large Programs Threads and Concurrency

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer

EINDHOVEN UNIVERSITY OF TECHNOLOGY

Answers to review questions from Chapter 2

Introduction to Computer Science Unit 2. Notes

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Jim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 4

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Lecture Overview Code generation in milestone 2 o Code generation for array indexing o Some rational implementation Over Express Over o Creating

York University AK/ITEC INTRODUCTION TO DATA STRUCTURES. Final Sample II. Examiner: S. Chen Duration: Three hours

1.00/ Introduction to Computers and Engineering Problem Solving. Quiz 2 / November 10, 2005

A. Incorrect! To simplify this expression you need to find the product of 7 and 4, not the sum.

1.00/1.001 Introduction to Computers and Engineering Problem Solving. Final Exam

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

C# Programming for Developers Course Labs Contents

Transcription:

MIT 6.031: Software Construction Prof. Rob Miller & Max Goldman revised Tuesday 1 st May, 2018, 11:59 This quiz uses the same abstract data type as Quiz 1. Solutions to Quiz 2 (April 27, 2018) In sciences like physics and chemistry, dimensional analysis is often used to check calculations for errors. Dimensional analysis associates a number with a unit of measure, called its dimension. Examples of dimensioned numbers include: a length of 10 meters (m) a time of 0.8 seconds (s) a relative velocity of -20 meters per second (m/s, or ms 1 ) an acceleration of 9.8 meters per second per second (m/s 2 ) an area of 100 square meters (m 2 ) a volume change of -0.001 cubic meters (m 3 ) Less familiar but still valid examples of dimensioned numbers include: 99.9 seconds per meter (s/m) 2 meter-seconds (m s) A number s dimension can be empty, or dimensionless, like π. Two rules of dimensional analysis are: Numbers with different dimensions should not be added, subtracted, or compared. For example, it makes no sense to compare a length in meters with a time in seconds, or to add them together. The ratio (or product) of two dimensioned numbers produces a number whose dimension is the ratio (or product) of the two dimensions. For example, a velocity in m/s multiplied by a time in seconds produces a length in meters. The problems in this quiz refer to the code for DimDouble on page 5, which you may detach. Lines 4 11 implement a static creator method, and lines 12 16 declare instance methods of DimDouble. Problem 1 (Grammars) (22 points). Ben Bitdidle is building a system to manipulate dimensioned numbers. To start, Ben wants to parse a product of dimensioned numbers and produce the correct output. For example, the input: 4 x 3 kg x 9.8 m / s^2 x 1.5 m x 0.1 / s equals 17.64 kg m 2 /s 3, or 17.64 watts. In the input, terms of the product are separated by 'x' characters. Within a term, if there are units in the denominator, those units all follow a single '/'. The terms in the example above are all valid. The following term is not as useful, but is also valid: 0.0 kg^22 m m / kg m kg^2 s Examples of invalid terms that the grammar should reject include: 1 / s^2^2 (no extra unit exponents) 1.5 m^1 (no unit exponents of 1)

2 Solutions to Quiz 2 (April 27, 2018) 4 kg^0 (no unit exponents of 0) 9.8 m s^-2 (no negative unit exponents) 3 kg / (no empty unit denominators) 1 / 10 s (no numbers in the denominator) Complete the grammar by filling in the rest of each incomplete production. product is the root. The grammar should use all the productions. Make sure we can read what you write. No credit will be given for unreadable or ambiguous writing. @skip whitespace { product ::= term ('x' term)* ; term ::= numer_units ::= dimension+ ; denom_units ::= dimension ::= exponent ::= value ::= '-'? \d+ ('.' \d*)? ; unit ::= 'm' 'kg' 's' 'A' 'K' 'mol' 'cd' ; whitespace ::= [ \t\r\n]+ ; Solution. term ::= value numer_units? denom_units? ; denom_units ::= / dimension+ ; dimension ::= unit ( ^ exponent)? ; exponent ::= [2-9] [1-9] [0-9]+ ; Problem 2 (Recursive Types) (18 points). Alyssa proposes the DimDouble implementation on page 5, using two concrete variants. She draws a snapshot diagram to show Ben an example: unit WithUnit WithUnit inverse amount true unit inverse amount Unit METER false Numeric value 5 (a) Write a clear, complete abstraction function for Numeric: Solution. AF(value) = dimensionless number value (b) Write a clear, complete safety from rep exposure argument for WithUnit:

Solutions to Quiz 2 (April 27, 2018) 3 Solution. amount, unit, and inverse are all private final fields and immutable values Implement numericvalue(): (c) In Numeric: @Override public double numericvalue() { Solution. return value; (d) In WithUnit: @Override public double numericvalue() { Solution. return this.amount.numericvalue(); Problem 3 (Specifications) (18 points). Ben is implementing DimDouble.units() and dimensionless(). Their signatures, and the spec for dimensionless(), are on page 5 (lines 13 15). Alyssa points to the snapshot diagram in Problem 2. Ben, make sure this is a valid rep for the dimensionless number 5, she says. I m going to use the same implementation of dimensionless() in both variants, says Ben. It doesn t depend on the rep at all because it just calls units(): @Override public boolean dimensionless() { return this.units().isempty(); Good plan, says Alyssa, but it depends on the spec of units(). Write two specifications for units(), one weaker and one stronger. You may not state preconditions, only postconditions. Ben s implementation should only work with one of your specs: the other spec should not be enough to guarantee that his implementation is correct. Then, write an implementation for dimensionless() that works with both of your specs for units(). Similar to Ben s implementation, your code should work for both concrete variants of DimDouble, by calling units() instead of examining the rep. (a) Weaker spec for units(): Solution. returns a map m where for all units u, m.getordefault(u, 0) is the exponent of u in this; 0 indicates unit not present (b) Stronger spec for units():

4 Solutions to Quiz 2 (April 27, 2018) Solution. returns a map m where for all units u in the units of this, m.get(u) is the exponent of u; no value in the map is 0 (c) dimensionless() implementation that works with either units() spec: @Override public boolean dimensionless() { Solution. return units().values().stream().allmatch(e -> e == 0); Problem 4 (Code Review) (28 points). The code for parallelmultiply on page 6 is buggy. For each of these code review comments, circle whether you AGREE or DISAGREE with the comment, and explain why in one sentence. (a) Because of sublist, this code creates aliases to the terms input from multiple threads. That means there is a thread safety bug if terms is not threadsafe. Solution. AGREE, line 7 will run on multiple threads, accessing the original terms through sublist wrappers. If terms is not threadsafe, the concurrent calls to observers size, get are not threadsafe. (b) Need to wait for both threads to finish (for example, call join() on them) before line 18 where results is used. Solution. DISAGREE, each take() will block until another result is available. (c) There is a race condition bug with how this code uses the results queue twice on line 18. Solution. DISAGREE, each take() will return a different result, and since multiplication is commutative, they can be multiplied in either order. (d) Need to return a defensive copy on line 7 to prevent an aliasing bug. Solution. DISAGREE, DimDouble is immutable, so aliasing is not a problem. Problem 5 (Concurrency) (14 points). Assume we fix any issues from the previous question, and we run: public static void main(string[] args) { DimDouble somemeters = DimDouble.make(9.8, new Unit[] { METER, new Unit[] {); DimDouble persecond = DimDouble.make(1, new Unit[] {, new Unit[] { SECOND ); // 9.8 m x 1 / s x 1 / s = 9.8 m / s^2 DimDouble g = parallelmultiply(arrays.aslist(somemeters, persecond, persecond)); (a) How many main threads will be created? Solution. 1

Solutions to Quiz 2 (April 27, 2018) 5 (b) And how many additional threads will be created by parallelmultiply? Solution. 4 (c) In total, how many threads will multiply a pair of DimDoubles? Solution. 2 (d) Leif Noad realizes that we can implement parallelmultiply using Java s parallel streams. Complete the implementation using the two-argument reduce method whose signature is: reduce : Stream<T> T (T T T) T public static DimDouble parallelmultiply(list<dimdouble> terms) { return terms.stream().parallel().reduce(, ); Solution. DimDouble.ONE, DimDouble::multiply You may detach this page. Write your username at the top, and hand in all pages when you leave. public enum Unit { METER, KILOGRAM, SECOND, AMPERE, KELVIN, MOLE, CANDELA 1 /** Immutable dimensioned number. */ 2 public interface DimDouble { 3 public static final DimDouble ONE = make(1, new Unit[] {, new Unit[] {); 4 public static DimDouble make(double value, Unit[] numeratorunits, 5 Unit[] denominatorunits) { 6 DimDouble amount = new Numeric(value); 7 for (Unit unit : numeratorunits) 8 amount = new WithUnit(amount, unit, false); 9 for (Unit unit : denominatorunits) 10 amount = new WithUnit(amount, unit, true); 11 return amount; 12 public double numericvalue(); 13 public Map<Unit,Integer> units();

6 Solutions to Quiz 2 (April 27, 2018) 14 /** @return true if and only if this DimDouble is a dimensionless value */ 15 public boolean dimensionless(); 16 public DimDouble multiply(dimdouble other); 17 public class Numeric implements DimDouble { 18 private final double value; 19 public Numeric(double value) { this.value = value; 20 //... methods... 21 public class WithUnit implements DimDouble { 22 private final DimDouble amount; 23 private final Unit unit; 24 private final boolean inverse; 25 public WithUnit(DimDouble amount, Unit unit, boolean inverse) {... 26 //... methods... 1 public class Parallel { 2 public static DimDouble parallelmultiply(list<dimdouble> terms) { 3 final int termcount = terms.size(); 4 // product of no terms is the identity 5 if (termcount == 0) { return DimDouble.ONE; 6 // product of one term is itself 7 if (termcount == 1) { return terms.get(0); 8 // split terms in half 9 final List<DimDouble> firsthalf = terms.sublist(0, termcount/2); 10 final List<DimDouble> secondhalf = terms.sublist(termcount/2, termcount); 11 final List<Thread> threads = new ArrayList<>(); 12 final BlockingQueue<DimDouble> results = new LinkedBlockingQueue<>(); 13 // recursively compute products for each half in parallel... 14 threads.add(new Thread(() -> results.put(parallelmultiply(firsthalf)))); 15 threads.add(new Thread(() -> results.put(parallelmultiply(secondhalf)))); 16 for (Thread t : threads) { t.start(); 17 //... and multiply those two products 18 return results.take().multiply(results.take());

Solutions to Quiz 2 (April 27, 2018) 7 For reference: List.subList (used on lines 9 & 10) creates a wrapper that refers to part of a larger list. Its spec is: List<E> sublist(int fromindex, int toindex) Returns a view of the portion of this list between the specified fromindex, inclusive, and toindex, exclusive. (If fromindex and toindex are equal, the returned list is empty.) The returned list is backed by this list. For example, the following removes a range of elements from a list: list.sublist(from, to).clear(); BlockingQueue (used on line 12) provides both non-blocking operations (e.g. add and remove) and blocking operations (e.g. put and take).