SlideShare a Scribd company logo
For any help regarding Computer Network Assignment Help
Visit :- https://computernetworkassignmenthelp.com/ ,
Email :- support@computernetworkassignmenthelp.com or
Call us at :- +1 678 648 4277
Problem 1
For each question, choose all correct answers.
(a) Which of the following are true of thread confinement?
A.all privatefinalfields are confined
B.all immutable values are confined
C.the values of all local variables are confined
D.a BlockingQueueused to implement message passing should be confined
E.the view tree in a Swing GUI should be confined
Solution. E.
(b) Select all the strings below where the entire string is
matched by the regular expression:
([a-z]+[1-9]+)*[1-9]
A.bb8b8b
B.r2d222
C.c3po000
D.8
E.r5d4
Solution. B, D.
computernetworkassignmenthelp.com
(c) Consider an immutable class ComplexNumfor representing
complex numbers:
private final double realPart;
private final double imaginaryPart;
// AF: represents (realPart + i * imaginaryPart)
// RI: true
// ... other creators, producers, observers ...
public double absoluteValue() {
return Math.sqrt(realPart*realPart +
imaginaryPart*imaginaryPart)
}
@Override public boolean equals(Object other) {
if (!(other instanceof ComplexNum)) { return false; }
ComplexNum that = (ComplexNum)other;
return this.absoluteValue() == that.absoluteValue();
}
computernetworkassignmenthelp.com
This implementation of equals...
A.is reflexive
B.is symmetric
C.is transitive
D.returns true for ComplexNum pairs that should not be equal according to
the AF
E.returns false for ComplexNum pairs that should be equal according to the
AF
Solution. A, B, C, D. □
(d) Since ServerSocket.accept() is a blocking method, we can conclude
that...
A.accept()will not return until a client makes a connection
B.accept()will throw an exception if called when no clients are connecting
C.calling accept()could prevent the program from terminating
D.it is safe to call accept()simultaneously from multiple threads
E.while accept() is blocking, calling other methods on the same
ServerSocketinstance from other threads will block
Solution. A, C. □
computernetworkassignmenthelp.com
Problem 2 (Map/Filter/Reduce)
Ben Bitdiddle is trying to select a new password for his social media accounts. Given the
following interface for representing passwords:
public interface Password { public String
plainText(); public int strength();
}
For each method below, fill in the blanks to implement the specification using map, filter,
and reduce. You must use exactly two operations, but you may use the same operation
twice. On each line, fill in the first blank with map, filter, or reduce, and fill in the second
blank with a lambda expression. Solutions will be graded for correctness and clarity.
(a) /**
* @param passwords the passwords to consider
* @param minStrength the minimum strength a password should have
* @return the plaintext strings of passwords that have strength at least minStrength
*/
public static List<String> strongEnough(List<Password> passwords, int minStrength) {
return passwords.stream()
. ( )
. ( )
.collect(toList());
}
computernetworkassignmenthelp.com
(b) /**
* @param passwords the passwords to consider
* @param substring required substring
* @return the plaintext strings of passwords that contain substring
*/
public static List<String> containing(List<Password> passwords, String
substring) {
return passwords.stream()
. ( )
. ( )
.collect(toList());
}
(c) /**
* @param passwords the passwords to consider
* @return the average strength of the passwords
*/
public static double averageStrength(List<Password> passwords) {
return passwords.stream()
. ( )
computernetworkassignmenthelp.com
. (0, )
/ (double)passwords.size();
}
Solution.
(a).filter(p -> p.strength() >= minStrength)
.map(p -> p.plainText())
(b).map(p -> p.plainText())
.filter(p -> p.contains(substring))
(c).map(p -> p.length())
.reduce(0, (a,b) -> a+b)
Problem 3 (Abstract Data Types)
A tree is a data structure that consists of a root node and zero or more
children which themselves are also trees. A binary tree is a tree in which
each node has at most two children, designated left and right. For example:
computernetworkassignmenthelp.com
Simon Straightforward is an enthusiastic 6.005 student who just learned about ADTs
and wants to build a class to represent binary trees of positive integers. He comes up
with this internal representation:
/** A binary tree of positive integers. */
public class PosIntBinaryTree {
private final List<List<Integer>> nodes;
}
Simon wants each sub-list in nodes to represent a level in the binary tree, using 0 in
place of missing elements. For example, the binary tree shown above is represented by
the following list of lists:
[ [ 1 ]
[ 3, 5 ]
[ 0, 2, 6, 4 ] ]
(a) Silly Simon forgot to document his abstraction function and rep invariant!
Select statements to put into the AF and RI of PosIntBinaryTree by circling the letters of
all statements to include from the list below. Include all good statements that are
compatible with Simon’s design.
AF: A B C D E F G
RI: A B C D E F G
A.all 0 <= i < nodes.size(), nodes.get(i).get(0) > 0
B.if nodes.size() == 0, represents the empty tree
computernetworkassignmenthelp.com
Rob Recursive, an even more enthusiastic student, wants to represent binary trees of
any integers.
(b)What bad practice in Simon’s rep prevents Rob from easily extending it?
Solution. Magic number 0. □
(c)Rob decides to implement the binary trees recursively, using an interface
IntBinaryTree with two concrete variants, one of which represents the empty tree.
He also decides the type will be immutable.
/** An immutable binary tree of integers. */
public interface IntBinaryTree { ... }
Write a recursive datatype definition for IntBinaryTree:
Solution. IntBinaryTree = Empty() + Tree(value: int, left,right: IntBinaryTree) □
C.if nodes.size() > 0, nodes.get(0).get(0) is the root node
D.nodes.get(i).size() == 2^I
E.nodes.size() == 2^k for some nonnegative integer k
F.for node nodes.get(i).get(j),
its left child (if any) is nodes.get(i+1).get(j*2)
G.for node nodes.get(i).get(j),
its right child (if any) is nodes.get(i+1).get(j*2+1)
Solution. AF: B, C, F, and G. RI:
D.
computernetworkassignmenthelp.com
(d) Start implementing the concrete variant that represents the empty tree by
writing its field declarations, abstraction function, and rep invariant. If parts of the
AF or RI would normally be assumed in 6.005, write them explicitly.
Fields:
AF:
RI:
Solution.
No fields
AF: represents the empty immutable
binary tree of integers RI: true
□
(e) Start implementing the other concrete variant by writing its field declarations,
abstraction function, and rep invariant. If parts of the AF or RI would normally be
assumed in 6.005, write them explicitly.
Fields:
AF:
RI:
Solution.
private final int value;
private final IntBinaryTree left, right;
AF: represents the immutable binary tree of integers with root node value, left
subtree left, and right subtree right
computernetworkassignmenthelp.com
RI: left,right != null □
Problem 4 (Recursive Data Types) (20 points).
A Boolean formula is a propositional expression consisting of variables, ∧
(and) and ∨ (or) binary operators, and ¬ (not) unary operators.
For example, the following expression means “either P or Q is true, and
either P is false or R is true”:
(P ∨ Q) ∧ (¬P ∨ R)
A formula is in negation normal form if the negation operator (¬) is only
applied directly to variables. For example, P ∧ (¬Q ∨ R) is in negation
normal form, but P ∧ ¬(Q ∨ R) and ¬(P ∧ (¬Q ∨ R)) are not.
Here is a datatype definition for an ADT to represent negation normal form
Boolean formulas:
NegNormFormula = Variable(name: String, isNegated: boolean)
+ And(left: NegNormFormula, right:
NegNormFormula) + Or(left: NegNormFormula,
right: NegNormFormula)
Now consider this specification:
// returns a negation of the input formula
negate : NegNormFormula -> NegNormFormula
(a) Classify this operation according to our types of ADT operations:
computernetworkassignmenthelp.com
□
(b) Implement the operation. Use De Morgan’s laws and the
rule for double negation:
¬(P ∧ Q) = ¬P ∨ ¬Q and
¬(P ∨ Q) = ¬P ∧ ¬Q and
public class Variable implements NegNormFormula {
private final String name;
private final boolean isNegated;
public Variable(String name, boolean isNegated) {
... } @Override public NegNormFormula negate() {
¬¬P = P
Solution.
return new Variable(name, ! isNegated);
□
}
}
public class And implements
NegNormFormula { private final
NegNormFormula left; private final
NegNormFormula right;
public And(NegNormFormula left, NegNormFormula
right) { ... } @Override public NegNormFormula negate() {
Soluti
on.
return new Or(left.negated(),
right.negated());
□
computernetworkassignmenthelp.com
}
}
public class Or implements
NegNormFormula { private final
NegNormFormula left; private final
NegNormFormula right;
public Or(NegNormFormula left, NegNormFormula right)
{ ... } @Override public NegNormFormula negate() {
Solution.
return new And(left.negated(),
right.negated());
□
}
}
Problem 5 (Thread Safety)
It’s election season! With the tight race for president of Fictional Dystopia,
you’ve been asked to develop a secure online voting system.
In Fictional Dystopian elections, each voter has exactly two votes. Each
voter can vote twice for the same candidate, or split their vote between two
different candidates.
computernetworkassignmenthelp.com
public class TwoVotesEachElection {
private final AtomicInteger[] voteCounts;
private final Set<String> voters;
// ... constructor initializes voteCounts to an array of AtomicIntegers,
// each with value zero, and initializes voters to a threadsafe Set ...
public int getNumberOfCandidates() { return voteCounts.length; }
// requires: 0 <= can1, can2 < getNumberOfCandidates()
// effects: if and only if the voter hasn’t already voted, casts both votes
public void vote(final String voterID, final int can1, final int can2) {
if (voters.contains(voterID)) { return; }
voters.add(voterID);
// use the atomic incrementAndGet operation
// (we don’t need the "get" part, but there is no plain "increment")
voteCounts[can1].incrementAndGet();
voteCounts[can2].incrementAndGet();
}
// ...
}
Suppose election is a TwoVotesEachElection with 4 candidates (so voteCounts.length
= 4).
(a) Unfortunately, even though TwoVotesEachElection uses threadsafe datatypes, the
vote() opera- tion is not threadsafe. Explain clearly an interleaving that violates thread
safety for TwoVotesEachElection.
computernetworkassignmenthelp.com
Solution. Two threads enter votewith the same voterIDnot yet in voters.
Both threads call voters.containsand obtain false, then both call voters.addsuccessfully.
At this point, both threads will increment the vote counts for their can1 and can2, giving this
voter 4 votes instead of 2, in violation of the postcondition. □
Louis Reasoner is convinced that using AtomicInteger is unnecessary, so he changes the
code to use primitive integers instead:
public class LouisTwoVotesEachElection {
private final int[] voteCounts;
private final Set<String> voters;
// ... constructor initializes voteCounts to an array of zeros,
// and initializes voters to a threadsafe Set ...
public int getNumberOfCandidates() { return voteCounts.length; }
// requires: 0 <= can1, can2 < getNumberOfCandidates()
// effects: if and only if the voter hasn’t already voted, casts both votes
public void vote(final String voterID, final int can1, final int can2) {
if (voters.contains(voterID)) { return; }
computernetworkassignmenthelp.com
voters.add(voterID); voteCounts[can1]++;
voteCounts[can2]++;
}
// ...
}
Of course, this just makes the problem worse.
(b) Suppose 100 voters, each using a different thread, participate in our 4-candidate
election by concur- rently calling Louis’ vote(). Every voter uses a unique ID, and no one
casts both of their votes for the same candidate. The value of the sum
voteCounts[0] + voteCounts[1] + voteCounts[2] + voteCounts[3]
could be which of the following? Choose all that apply.
A.0
B.1
C.2
D.4
E. 100
F. 200
G. 400
Solution. C, D, E, F.
□
computernetworkassignmenthelp.com
Solution. A, C, D.
Locking on different voterID strings doesn’t help. voteCounts[0] is a primitive in Louis’
code.
At least one thread will successfully increment the count for its first candidate; same
for some thread and its second candidate. With no races at all, 200 votes will be
counted.
(c) Louis wants to fix the thread safety problems by putting all the code inside vote()
in a synchronized block. Of the following objects in Louis’ version of the code,
which are suitable for us to synchronize on in order to ensure thread safety for
concurrent calls to vote()? Choose all that apply.
A.this
B.voterID
C.voters
D.voteCounts
E.voteCounts[0]
computernetworkassignmenthelp.com

More Related Content

PPTX
Software Construction Assignment Help
PPTX
Computer Science Assignment Help
PPTX
C Assignment Help
PPTX
C Programming Homework Help
PDF
46630497 fun-pointer-1
DOC
C aptitude.2doc
DOC
Captitude 2doc-100627004318-phpapp01
DOCX
Maharishi University of Management (MSc Computer Science test questions)
Software Construction Assignment Help
Computer Science Assignment Help
C Assignment Help
C Programming Homework Help
46630497 fun-pointer-1
C aptitude.2doc
Captitude 2doc-100627004318-phpapp01
Maharishi University of Management (MSc Computer Science test questions)

What's hot (20)

PDF
C programming & data structure [arrays & pointers]
PDF
Function Composition - forward composition versus backward composition
PPTX
Introduction to c++
PPTX
Functions in C++
DOCX
C interview question answer 2
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
PDF
C aptitude scribd
PPS
C programming session 01
PPT
Advanced Programming C++
PDF
Tutorial2
PPT
C++ Functions
PPT
Computer Programming- Lecture 3
PDF
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
PPT
C++ Function
PPT
Computer Programming- Lecture 6
PDF
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
PPT
C++ Language
PPT
C++ Overview
PDF
Functions in C++
C programming & data structure [arrays & pointers]
Function Composition - forward composition versus backward composition
Introduction to c++
Functions in C++
C interview question answer 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
C aptitude scribd
C programming session 01
Advanced Programming C++
Tutorial2
C++ Functions
Computer Programming- Lecture 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
C++ Function
Computer Programming- Lecture 6
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
C++ Language
C++ Overview
Functions in C++
Ad

Similar to Computer Network Assignment Help (20)

PDF
Answers withexplanations
PPTX
Computer Network Assignment Help
DOC
NET_Solved ans
PDF
AP PGECET Computer Science 2016 question paper
PDF
combat unacademy.pdf
PPTX
Proficient Computer Network Assignment Help
PPTX
Algorithm Homework Help
PDF
Scala Functional Patterns
PDF
Cplus plus abd datastructure
PDF
ecoop-slides.pdf
PDF
Cwkaa 2010
PDF
2nd Semester M Tech: Structural Engineering (June-2015) Question Papers
PDF
Ee693 questionshomework
PDF
Sample quizz test
PPTX
Daa unit 5
PDF
Gate Computer Science Solved Paper 2007
PDF
QB104541.pdf
PDF
Lecture 5: Functional Programming
PDF
Computer Science Paper 1 (Theory) - 2017.pdf
DOC
White box-sol
Answers withexplanations
Computer Network Assignment Help
NET_Solved ans
AP PGECET Computer Science 2016 question paper
combat unacademy.pdf
Proficient Computer Network Assignment Help
Algorithm Homework Help
Scala Functional Patterns
Cplus plus abd datastructure
ecoop-slides.pdf
Cwkaa 2010
2nd Semester M Tech: Structural Engineering (June-2015) Question Papers
Ee693 questionshomework
Sample quizz test
Daa unit 5
Gate Computer Science Solved Paper 2007
QB104541.pdf
Lecture 5: Functional Programming
Computer Science Paper 1 (Theory) - 2017.pdf
White box-sol
Ad

More from Computer Network Assignment Help (20)

PPTX
Online TCP-IP Networking Assignment Help
PPTX
Quantum Computing: Your University Assignment Solution!
PPTX
Advanced Modularity Optimization Assignment Help
PPTX
Elevate Your Networking Game with Expert Computer Network Assignment Help
PPTX
Get 15% off on Computer Network Assignment Help
PPTX
Computer Network Assignment Help
PPTX
Advanced Computer Network Assignment Help
PPTX
Computer Network Assignment Help.pptx
PPTX
Computer Network Homework Help
PPTX
Computer Network Homework Help
PPTX
Online Computer Network Security Assignment Help
PPTX
Computer Network Homework Help
PPTX
Computer Network Assignment Help
PPTX
Computer Network Assignment Help
PPTX
Networking Assignment Help
PPTX
Design & Analysis of Algorithms Assignment Help
PPTX
Computer Network Assignment Help
PPTX
Network Design Assignment Help
PPTX
Computer Networking Assignment Help
PPTX
Computer Network Assignment Help
Online TCP-IP Networking Assignment Help
Quantum Computing: Your University Assignment Solution!
Advanced Modularity Optimization Assignment Help
Elevate Your Networking Game with Expert Computer Network Assignment Help
Get 15% off on Computer Network Assignment Help
Computer Network Assignment Help
Advanced Computer Network Assignment Help
Computer Network Assignment Help.pptx
Computer Network Homework Help
Computer Network Homework Help
Online Computer Network Security Assignment Help
Computer Network Homework Help
Computer Network Assignment Help
Computer Network Assignment Help
Networking Assignment Help
Design & Analysis of Algorithms Assignment Help
Computer Network Assignment Help
Network Design Assignment Help
Computer Networking Assignment Help
Computer Network Assignment Help

Recently uploaded (20)

PPTX
master seminar digital applications in india
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
GDM (1) (1).pptx small presentation for students
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Classroom Observation Tools for Teachers
PDF
Trump Administration's workforce development strategy
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
master seminar digital applications in india
Anesthesia in Laparoscopic Surgery in India
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
RMMM.pdf make it easy to upload and study
GDM (1) (1).pptx small presentation for students
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Orientation - ARALprogram of Deped to the Parents.pptx
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Chinmaya Tiranga quiz Grand Finale.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Abdominal Access Techniques with Prof. Dr. R K Mishra
Classroom Observation Tools for Teachers
Trump Administration's workforce development strategy
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Microbial diseases, their pathogenesis and prophylaxis
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student

Computer Network Assignment Help

  • 1. For any help regarding Computer Network Assignment Help Visit :- https://computernetworkassignmenthelp.com/ , Email :- [email protected] or Call us at :- +1 678 648 4277
  • 2. Problem 1 For each question, choose all correct answers. (a) Which of the following are true of thread confinement? A.all privatefinalfields are confined B.all immutable values are confined C.the values of all local variables are confined D.a BlockingQueueused to implement message passing should be confined E.the view tree in a Swing GUI should be confined Solution. E. (b) Select all the strings below where the entire string is matched by the regular expression: ([a-z]+[1-9]+)*[1-9] A.bb8b8b B.r2d222 C.c3po000 D.8 E.r5d4 Solution. B, D. computernetworkassignmenthelp.com
  • 3. (c) Consider an immutable class ComplexNumfor representing complex numbers: private final double realPart; private final double imaginaryPart; // AF: represents (realPart + i * imaginaryPart) // RI: true // ... other creators, producers, observers ... public double absoluteValue() { return Math.sqrt(realPart*realPart + imaginaryPart*imaginaryPart) } @Override public boolean equals(Object other) { if (!(other instanceof ComplexNum)) { return false; } ComplexNum that = (ComplexNum)other; return this.absoluteValue() == that.absoluteValue(); } computernetworkassignmenthelp.com
  • 4. This implementation of equals... A.is reflexive B.is symmetric C.is transitive D.returns true for ComplexNum pairs that should not be equal according to the AF E.returns false for ComplexNum pairs that should be equal according to the AF Solution. A, B, C, D. □ (d) Since ServerSocket.accept() is a blocking method, we can conclude that... A.accept()will not return until a client makes a connection B.accept()will throw an exception if called when no clients are connecting C.calling accept()could prevent the program from terminating D.it is safe to call accept()simultaneously from multiple threads E.while accept() is blocking, calling other methods on the same ServerSocketinstance from other threads will block Solution. A, C. □ computernetworkassignmenthelp.com
  • 5. Problem 2 (Map/Filter/Reduce) Ben Bitdiddle is trying to select a new password for his social media accounts. Given the following interface for representing passwords: public interface Password { public String plainText(); public int strength(); } For each method below, fill in the blanks to implement the specification using map, filter, and reduce. You must use exactly two operations, but you may use the same operation twice. On each line, fill in the first blank with map, filter, or reduce, and fill in the second blank with a lambda expression. Solutions will be graded for correctness and clarity. (a) /** * @param passwords the passwords to consider * @param minStrength the minimum strength a password should have * @return the plaintext strings of passwords that have strength at least minStrength */ public static List<String> strongEnough(List<Password> passwords, int minStrength) { return passwords.stream() . ( ) . ( ) .collect(toList()); } computernetworkassignmenthelp.com
  • 6. (b) /** * @param passwords the passwords to consider * @param substring required substring * @return the plaintext strings of passwords that contain substring */ public static List<String> containing(List<Password> passwords, String substring) { return passwords.stream() . ( ) . ( ) .collect(toList()); } (c) /** * @param passwords the passwords to consider * @return the average strength of the passwords */ public static double averageStrength(List<Password> passwords) { return passwords.stream() . ( ) computernetworkassignmenthelp.com
  • 7. . (0, ) / (double)passwords.size(); } Solution. (a).filter(p -> p.strength() >= minStrength) .map(p -> p.plainText()) (b).map(p -> p.plainText()) .filter(p -> p.contains(substring)) (c).map(p -> p.length()) .reduce(0, (a,b) -> a+b) Problem 3 (Abstract Data Types) A tree is a data structure that consists of a root node and zero or more children which themselves are also trees. A binary tree is a tree in which each node has at most two children, designated left and right. For example: computernetworkassignmenthelp.com
  • 8. Simon Straightforward is an enthusiastic 6.005 student who just learned about ADTs and wants to build a class to represent binary trees of positive integers. He comes up with this internal representation: /** A binary tree of positive integers. */ public class PosIntBinaryTree { private final List<List<Integer>> nodes; } Simon wants each sub-list in nodes to represent a level in the binary tree, using 0 in place of missing elements. For example, the binary tree shown above is represented by the following list of lists: [ [ 1 ] [ 3, 5 ] [ 0, 2, 6, 4 ] ] (a) Silly Simon forgot to document his abstraction function and rep invariant! Select statements to put into the AF and RI of PosIntBinaryTree by circling the letters of all statements to include from the list below. Include all good statements that are compatible with Simon’s design. AF: A B C D E F G RI: A B C D E F G A.all 0 <= i < nodes.size(), nodes.get(i).get(0) > 0 B.if nodes.size() == 0, represents the empty tree computernetworkassignmenthelp.com
  • 9. Rob Recursive, an even more enthusiastic student, wants to represent binary trees of any integers. (b)What bad practice in Simon’s rep prevents Rob from easily extending it? Solution. Magic number 0. □ (c)Rob decides to implement the binary trees recursively, using an interface IntBinaryTree with two concrete variants, one of which represents the empty tree. He also decides the type will be immutable. /** An immutable binary tree of integers. */ public interface IntBinaryTree { ... } Write a recursive datatype definition for IntBinaryTree: Solution. IntBinaryTree = Empty() + Tree(value: int, left,right: IntBinaryTree) □ C.if nodes.size() > 0, nodes.get(0).get(0) is the root node D.nodes.get(i).size() == 2^I E.nodes.size() == 2^k for some nonnegative integer k F.for node nodes.get(i).get(j), its left child (if any) is nodes.get(i+1).get(j*2) G.for node nodes.get(i).get(j), its right child (if any) is nodes.get(i+1).get(j*2+1) Solution. AF: B, C, F, and G. RI: D. computernetworkassignmenthelp.com
  • 10. (d) Start implementing the concrete variant that represents the empty tree by writing its field declarations, abstraction function, and rep invariant. If parts of the AF or RI would normally be assumed in 6.005, write them explicitly. Fields: AF: RI: Solution. No fields AF: represents the empty immutable binary tree of integers RI: true □ (e) Start implementing the other concrete variant by writing its field declarations, abstraction function, and rep invariant. If parts of the AF or RI would normally be assumed in 6.005, write them explicitly. Fields: AF: RI: Solution. private final int value; private final IntBinaryTree left, right; AF: represents the immutable binary tree of integers with root node value, left subtree left, and right subtree right computernetworkassignmenthelp.com
  • 11. RI: left,right != null □ Problem 4 (Recursive Data Types) (20 points). A Boolean formula is a propositional expression consisting of variables, ∧ (and) and ∨ (or) binary operators, and ¬ (not) unary operators. For example, the following expression means “either P or Q is true, and either P is false or R is true”: (P ∨ Q) ∧ (¬P ∨ R) A formula is in negation normal form if the negation operator (¬) is only applied directly to variables. For example, P ∧ (¬Q ∨ R) is in negation normal form, but P ∧ ¬(Q ∨ R) and ¬(P ∧ (¬Q ∨ R)) are not. Here is a datatype definition for an ADT to represent negation normal form Boolean formulas: NegNormFormula = Variable(name: String, isNegated: boolean) + And(left: NegNormFormula, right: NegNormFormula) + Or(left: NegNormFormula, right: NegNormFormula) Now consider this specification: // returns a negation of the input formula negate : NegNormFormula -> NegNormFormula (a) Classify this operation according to our types of ADT operations: computernetworkassignmenthelp.com
  • 12. □ (b) Implement the operation. Use De Morgan’s laws and the rule for double negation: ¬(P ∧ Q) = ¬P ∨ ¬Q and ¬(P ∨ Q) = ¬P ∧ ¬Q and public class Variable implements NegNormFormula { private final String name; private final boolean isNegated; public Variable(String name, boolean isNegated) { ... } @Override public NegNormFormula negate() { ¬¬P = P Solution. return new Variable(name, ! isNegated); □ } } public class And implements NegNormFormula { private final NegNormFormula left; private final NegNormFormula right; public And(NegNormFormula left, NegNormFormula right) { ... } @Override public NegNormFormula negate() { Soluti on. return new Or(left.negated(), right.negated()); □ computernetworkassignmenthelp.com
  • 13. } } public class Or implements NegNormFormula { private final NegNormFormula left; private final NegNormFormula right; public Or(NegNormFormula left, NegNormFormula right) { ... } @Override public NegNormFormula negate() { Solution. return new And(left.negated(), right.negated()); □ } } Problem 5 (Thread Safety) It’s election season! With the tight race for president of Fictional Dystopia, you’ve been asked to develop a secure online voting system. In Fictional Dystopian elections, each voter has exactly two votes. Each voter can vote twice for the same candidate, or split their vote between two different candidates. computernetworkassignmenthelp.com public class TwoVotesEachElection { private final AtomicInteger[] voteCounts; private final Set<String> voters;
  • 14. // ... constructor initializes voteCounts to an array of AtomicIntegers, // each with value zero, and initializes voters to a threadsafe Set ... public int getNumberOfCandidates() { return voteCounts.length; } // requires: 0 <= can1, can2 < getNumberOfCandidates() // effects: if and only if the voter hasn’t already voted, casts both votes public void vote(final String voterID, final int can1, final int can2) { if (voters.contains(voterID)) { return; } voters.add(voterID); // use the atomic incrementAndGet operation // (we don’t need the "get" part, but there is no plain "increment") voteCounts[can1].incrementAndGet(); voteCounts[can2].incrementAndGet(); } // ... } Suppose election is a TwoVotesEachElection with 4 candidates (so voteCounts.length = 4). (a) Unfortunately, even though TwoVotesEachElection uses threadsafe datatypes, the vote() opera- tion is not threadsafe. Explain clearly an interleaving that violates thread safety for TwoVotesEachElection. computernetworkassignmenthelp.com
  • 15. Solution. Two threads enter votewith the same voterIDnot yet in voters. Both threads call voters.containsand obtain false, then both call voters.addsuccessfully. At this point, both threads will increment the vote counts for their can1 and can2, giving this voter 4 votes instead of 2, in violation of the postcondition. □ Louis Reasoner is convinced that using AtomicInteger is unnecessary, so he changes the code to use primitive integers instead: public class LouisTwoVotesEachElection { private final int[] voteCounts; private final Set<String> voters; // ... constructor initializes voteCounts to an array of zeros, // and initializes voters to a threadsafe Set ... public int getNumberOfCandidates() { return voteCounts.length; } // requires: 0 <= can1, can2 < getNumberOfCandidates() // effects: if and only if the voter hasn’t already voted, casts both votes public void vote(final String voterID, final int can1, final int can2) { if (voters.contains(voterID)) { return; } computernetworkassignmenthelp.com
  • 16. voters.add(voterID); voteCounts[can1]++; voteCounts[can2]++; } // ... } Of course, this just makes the problem worse. (b) Suppose 100 voters, each using a different thread, participate in our 4-candidate election by concur- rently calling Louis’ vote(). Every voter uses a unique ID, and no one casts both of their votes for the same candidate. The value of the sum voteCounts[0] + voteCounts[1] + voteCounts[2] + voteCounts[3] could be which of the following? Choose all that apply. A.0 B.1 C.2 D.4 E. 100 F. 200 G. 400 Solution. C, D, E, F. □ computernetworkassignmenthelp.com
  • 17. Solution. A, C, D. Locking on different voterID strings doesn’t help. voteCounts[0] is a primitive in Louis’ code. At least one thread will successfully increment the count for its first candidate; same for some thread and its second candidate. With no races at all, 200 votes will be counted. (c) Louis wants to fix the thread safety problems by putting all the code inside vote() in a synchronized block. Of the following objects in Louis’ version of the code, which are suitable for us to synchronize on in order to ensure thread safety for concurrent calls to vote()? Choose all that apply. A.this B.voterID C.voters D.voteCounts E.voteCounts[0] computernetworkassignmenthelp.com