SlideShare uma empresa Scribd logo
1 de 16
For any help regarding Computer Science Assignment Help
Visit : https://www.programminghomeworkhelp.com/,
Email : support@programminghomeworkhelp.com or
Call us at : +1 678 648 4277 programminghomeworkhelp.com
Problem 1 (Multiple Choice)
For each question, choose all correct answers.
(a) Which of the following are true of thread confinement?
A. all private final fields are confined
B. all immutable values are confined
C. the values of all local variables are confined
D. a BlockingQueue used to implement message passing should be confined
E. 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 r2d222
D. 8 E. r5d4 programminghomeworkhelp.com
(c) Consider an immutable class ComplexNum for 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();
}
2 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
programminghomeworkhelp.com
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 ServerSocket instance
from other threads will block
Solution. A, C.
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.
programminghomeworkhelp.com
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()); )
}
(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()); )
}
programminghomeworkhelp.com
(c) /**
*@param passwords the passwords to consider
*@return the average strength of the passwords
*/
public static double averageStrength(List<Password> passwords) { return
passwords.stream()
. ( ) ) . (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:
programminghomeworkhelp.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.
programminghomeworkhelp.com
AF: A B C D E F G
RI: A B C D E F G
A. for all 0 <= i < nodes.size(), nodes.get(i).get(0) > 0
B. if nodes.size() == 0, represents the empty tree
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.
(c) 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)
programminghomeworkhelp.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;
programminghomeworkhelp.com
AF: represents the immutable binary tree of integers with root node value, left subtree
left, and right subtree right
RI: left,right != null
Problem 4 (Recursive Data Types).
ABooleanformula 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)
Nowconsider this specification:
programminghomeworkhelp.com
// returns a negation of the input formula
negate : NegNormFormula -> NegNormFormula
(a) Classify this operation according to our types of ADT operations:
Solution. Producer.
(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 ¬¬P =P
public class Variable implements NegNormFormula {
private final String name;
private final boolean isNegated;
public Variable(String name, boolean isNegated) { ... }
@Override public NegNormFormula negate() {
Solution. return new Variable(name, ! isNegated);
}
}
public class And implements NegNormFormula {
private final NegNormFormula left;
private final NegNormFormula right;
programminghomeworkhelp.com
public And(NegNormFormula left, NegNormFormula right) { ... }
@Override public NegNormFormula negate() {
Solution. return new Or(left.negated(), right.negated());
}
}
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.
programminghomeworkhelp.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).
programminghomeworkhelp.com
(a) Unfortunately, even though TwoVotesEachElection uses threadsafe datatypes, the
vote() operation is not threadsafe. Explain clearly an interleaving that violates
thread safety for TwoVotesEachElection.
Solution. Two threads enter vote with the same voterID not yet in voters.
Both threads call voters.contains and obtain false, then both call voters.add
successfully.
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; }
programminghomeworkhelp.com
// 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);
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 concurrently 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
programminghomeworkhelp.com
D. 4
E. 100
F. 200
G. 400
Solution. C, D, E, F.
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 fixthethread 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]
Solution. A, C, D.
Locking on different voterID strings doesn’t help. voteCounts[0] is a primitive in Louis’ code
programminghomeworkhelp.com

Mais conteúdo relacionado

Mais procurados

100 c interview questions answers
100 c interview questions answers100 c interview questions answers
100 c interview questions answers
Sareen Kumar
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
Srikanth
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
MomenMostafa
 

Mais procurados (20)

Computational Assignment Help
Computational Assignment HelpComputational Assignment Help
Computational Assignment Help
 
Ch9c
Ch9cCh9c
Ch9c
 
Computer Science Programming Assignment Help
Computer Science Programming Assignment HelpComputer Science Programming Assignment Help
Computer Science Programming Assignment Help
 
100 c interview questions answers
100 c interview questions answers100 c interview questions answers
100 c interview questions answers
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
Adobe
AdobeAdobe
Adobe
 
Programming Assignment Help
Programming Assignment HelpProgramming Assignment Help
Programming Assignment Help
 
Programming with matlab session 1
Programming with matlab session 1Programming with matlab session 1
Programming with matlab session 1
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview Questions
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
 
Dag representation of basic blocks
Dag representation of basic blocksDag representation of basic blocks
Dag representation of basic blocks
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
 
Advanced C - Part 3
Advanced C - Part 3Advanced C - Part 3
Advanced C - Part 3
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and Cats
 
Signal Processing Assignment Help
Signal Processing Assignment HelpSignal Processing Assignment Help
Signal Processing Assignment Help
 

Semelhante a Computer Science Assignment Help

Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
maxinesmith73660
 

Semelhante a Computer Science Assignment Help (20)

Programming Exam Help
 Programming Exam Help Programming Exam Help
Programming Exam Help
 
Class 12 computer sample paper with answers
Class 12 computer sample paper with answersClass 12 computer sample paper with answers
Class 12 computer sample paper with answers
 
Gsp 215 Effective Communication / snaptutorial.com
Gsp 215  Effective Communication / snaptutorial.comGsp 215  Effective Communication / snaptutorial.com
Gsp 215 Effective Communication / snaptutorial.com
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
Gsp 215 Believe Possibilities / snaptutorial.com
Gsp 215  Believe Possibilities / snaptutorial.comGsp 215  Believe Possibilities / snaptutorial.com
Gsp 215 Believe Possibilities / snaptutorial.com
 
GSP 215 Education Organization - snaptutorial.com
GSP 215  Education Organization - snaptutorial.comGSP 215  Education Organization - snaptutorial.com
GSP 215 Education Organization - snaptutorial.com
 
C Programming
C ProgrammingC Programming
C Programming
 
Gsp 215 Enhance teaching-snaptutorial.com
Gsp 215 Enhance teaching-snaptutorial.comGsp 215 Enhance teaching-snaptutorial.com
Gsp 215 Enhance teaching-snaptutorial.com
 
GSP 215 Technology levels--snaptutorial.com
GSP 215 Technology levels--snaptutorial.comGSP 215 Technology levels--snaptutorial.com
GSP 215 Technology levels--snaptutorial.com
 
Gsp 215 Massive Success / snaptutorial.com
Gsp 215  Massive Success / snaptutorial.comGsp 215  Massive Success / snaptutorial.com
Gsp 215 Massive Success / snaptutorial.com
 
Gsp 215 Enthusiastic Study / snaptutorial.com
Gsp 215 Enthusiastic Study / snaptutorial.comGsp 215 Enthusiastic Study / snaptutorial.com
Gsp 215 Enthusiastic Study / snaptutorial.com
 
Gsp 215 Exceptional Education / snaptutorial.com
Gsp 215  Exceptional Education / snaptutorial.comGsp 215  Exceptional Education / snaptutorial.com
Gsp 215 Exceptional Education / snaptutorial.com
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
GSP 215 Effective Communication - tutorialrank.com
GSP 215  Effective Communication - tutorialrank.comGSP 215  Effective Communication - tutorialrank.com
GSP 215 Effective Communication - tutorialrank.com
 
Tutorial2
Tutorial2Tutorial2
Tutorial2
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
 
GSP 215 Enhance teaching/tutorialrank.com
 GSP 215 Enhance teaching/tutorialrank.com GSP 215 Enhance teaching/tutorialrank.com
GSP 215 Enhance teaching/tutorialrank.com
 
GSP 215 Inspiring Innovation/tutorialrank.com
GSP 215 Inspiring Innovation/tutorialrank.comGSP 215 Inspiring Innovation/tutorialrank.com
GSP 215 Inspiring Innovation/tutorialrank.com
 
C Programming Homework Help
C Programming Homework HelpC Programming Homework Help
C Programming Homework Help
 

Mais de Programming Homework Help

Python Question - Python Assignment Help
Python Question - Python Assignment HelpPython Question - Python Assignment Help
Python Question - Python Assignment Help
Programming Homework Help
 

Mais de Programming Homework Help (20)

C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 
Python Question - Python Assignment Help
Python Question - Python Assignment HelpPython Question - Python Assignment Help
Python Question - Python Assignment Help
 
Best Algorithms Assignment Help
Best Algorithms Assignment Help Best Algorithms Assignment Help
Best Algorithms Assignment Help
 
Design and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment HelpDesign and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptxprogramminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
Algorithms Design Assignment Help
Algorithms Design Assignment HelpAlgorithms Design Assignment Help
Algorithms Design Assignment Help
 
Algorithms Design Homework Help
Algorithms Design Homework HelpAlgorithms Design Homework Help
Algorithms Design Homework Help
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
Computer Science Assignment Help
Computer Science Assignment Help Computer Science Assignment Help
Computer Science Assignment Help
 
C Programming Homework Help
C Programming Homework HelpC Programming Homework Help
C Programming Homework Help
 
Computation Assignment Help
Computation Assignment Help Computation Assignment Help
Computation Assignment Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Computer Science Homework Help
Computer Science Homework HelpComputer Science Homework Help
Computer Science Homework Help
 

Último

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Último (20)

Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 

Computer Science Assignment Help

  • 1. For any help regarding Computer Science Assignment Help Visit : https://www.programminghomeworkhelp.com/, Email : support@programminghomeworkhelp.com or Call us at : +1 678 648 4277 programminghomeworkhelp.com
  • 2. Problem 1 (Multiple Choice) For each question, choose all correct answers. (a) Which of the following are true of thread confinement? A. all private final fields are confined B. all immutable values are confined C. the values of all local variables are confined D. a BlockingQueue used to implement message passing should be confined E. 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 r2d222 D. 8 E. r5d4 programminghomeworkhelp.com
  • 3. (c) Consider an immutable class ComplexNum for 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(); } 2 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 programminghomeworkhelp.com
  • 4. 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 ServerSocket instance from other threads will block Solution. A, C. 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. programminghomeworkhelp.com
  • 5. 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()); ) } (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()); ) } programminghomeworkhelp.com
  • 6. (c) /** *@param passwords the passwords to consider *@return the average strength of the passwords */ public static double averageStrength(List<Password> passwords) { return passwords.stream() . ( ) ) . (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: programminghomeworkhelp.com
  • 7. 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. programminghomeworkhelp.com
  • 8. AF: A B C D E F G RI: A B C D E F G A. for all 0 <= i < nodes.size(), nodes.get(i).get(0) > 0 B. if nodes.size() == 0, represents the empty tree 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. (c) 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) programminghomeworkhelp.com
  • 9. (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; programminghomeworkhelp.com
  • 10. AF: represents the immutable binary tree of integers with root node value, left subtree left, and right subtree right RI: left,right != null Problem 4 (Recursive Data Types). ABooleanformula 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) Nowconsider this specification: programminghomeworkhelp.com
  • 11. // returns a negation of the input formula negate : NegNormFormula -> NegNormFormula (a) Classify this operation according to our types of ADT operations: Solution. Producer. (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 ¬¬P =P public class Variable implements NegNormFormula { private final String name; private final boolean isNegated; public Variable(String name, boolean isNegated) { ... } @Override public NegNormFormula negate() { Solution. return new Variable(name, ! isNegated); } } public class And implements NegNormFormula { private final NegNormFormula left; private final NegNormFormula right; programminghomeworkhelp.com
  • 12. public And(NegNormFormula left, NegNormFormula right) { ... } @Override public NegNormFormula negate() { Solution. return new Or(left.negated(), right.negated()); } } 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. programminghomeworkhelp.com
  • 13. 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). programminghomeworkhelp.com
  • 14. (a) Unfortunately, even though TwoVotesEachElection uses threadsafe datatypes, the vote() operation is not threadsafe. Explain clearly an interleaving that violates thread safety for TwoVotesEachElection. Solution. Two threads enter vote with the same voterID not yet in voters. Both threads call voters.contains and obtain false, then both call voters.add successfully. 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; } programminghomeworkhelp.com
  • 15. // 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); 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 concurrently 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 programminghomeworkhelp.com
  • 16. D. 4 E. 100 F. 200 G. 400 Solution. C, D, E, F. 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 fixthethread 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] Solution. A, C, D. Locking on different voterID strings doesn’t help. voteCounts[0] is a primitive in Louis’ code programminghomeworkhelp.com