EXAMINATION INSTRUCTIONS

advertisement
UnitExam#2
CSE116IntroductiontoComputerScienceII
Spring2016
EXAMINATIONINSTRUCTIONS
Thisexaminationhas7pages;checkthatyouhaveacompletepaper.
Eachcandidateshouldbepreparedtoproduce,uponrequest,hisorherSUNY/UBcard.
Thisexaminationhas5questions.Answerallquestions.
Youhave60minutestocompletethisexamination.Useyourtimeaccordingly.
READANDOBSERVETHEFOLLOWINGRULES:
► Namesarepre-printedontheexambooklets.EnsurethatyouhaveYOURexam.
► Sign,usingyourusualsignature,inthespaceprovidedonthebackcover.
► Allofyourwritingmustbehandedin.Thisbookletmustnotbetornormutilatedinanyway,
andmustnotbetakenfromtheexaminationroom.
► Showallofyourworkinarrivingatananswer,unlessinstructedotherwise.Partialcreditwillbe
awardedasappropriate.
► Candidates are not permitted to ask questions of the invigilators, except in cases of supposed
errorsorambiguitiesinexaminationquestions.
► CAUTION – Candidates guilty of any of the following, or similar, dishonest practices shall be
immediatelydismissedfromtheexaminationandshallbeliabletodisciplinaryaction.
♦ Making use of any books, papers or memoranda, calculators or computers, audio or
visual cassette players, or other memory aid devices, other than those explicitly
authorisedbytheexaminers.
♦ Speakingorcommunicatingwithothercandidates.
♦ Purposelyexposingwrittenpaperstotheviewofothercandidates.Thepleaofaccident
orforgetfulnessshallnotbereceived.
---------------------------DONOTWRITEBELOWTHISLINE!---------------------------
Q1
/10
Q2
/10
Q3
/10
Q4
Q5
/10
/10
1
TOTAL
/50
%
/100
UnitExam#2
CSE116IntroductiontoComputerScienceII
Spring2016
Question1[10marks–2each]
Inthecodeonthebelowandonthenextpage,clearlycircleandidentifybyletterone(andonly
one)exampleofeachoftheitemsinthelistontheleft.Ifyoubelievenoexampleexistsinthegiven
code,write“noexample”nexttothatitem.
A.innerclassdefinition
B.expressionoftypeThrowable
C.atypevariable
D.anonymousclassinstantiation
E.argumentlist
package multiset;
import
import
import
import
java.util.Collection;
java.util.ConcurrentModificationException;
java.util.Iterator;
java.util.NoSuchElementException;
public class MultiSet<E> implements Collection<E> {
private E[] _store;
private int _size;
private long _modCount;
public MultiSet() {
_modCount = 0;
_store = (E[]) (new Object[10]);
_size = 0;
_modCount++;
}
@Override public boolean add(E e) {
_store[_size] = e;
_size = _size + 1;
if (_size == _store.length) {
E[] temp = (E[]) (new Object[_store.length * 2]);
for (int i=0; i<_store.length; i=i+1) {
temp[i] = _store[i];
}
_store = temp;
}
_modCount++;
return true;
}
@Override public boolean contains(Object obj) {
if (obj == null) {
for (int i=0; i<_size; i=i+1) {
if (obj == _store[i]) {
return true;
}
}
}
else {
for (int i=0; i<_size; i=i+1) {
if (obj.equals(_store[i])) {
return true;
}
}
}
return false;
}
@Override public int size() {
return _size;
}
2
UnitExam#2
CSE116IntroductiontoComputerScienceII
@Override public boolean remove(Object obj) {
if (obj == null) {
for (int i=0; i<_size; i=i+1) {
if (obj == _store[i]) {
_store[i] = _store[_size-1];
_store[_size-1] = null;
_size--;
_modCount++;
return true;
}
}
}
else {
for (int i=0; i<_size; i=i+1) {
if (obj.equals(_store[i])) {
_store[i] = _store[_size-1];
_store[_size-1] = null;
_size--;
_modCount++;
return true;
}
}
}
return false;
}
@Override public boolean isEmpty() {
return _size == 0;
}
@Override public Iterator<E> iterator() {
return new MultiSetIterator();
}
private class MultiSetIterator implements Iterator<E> {
private int _index;
private long _modCountOfMultiSetAtIteratorCreation;
public MultiSetIterator() {
_index = 0;
_modCountOfMultiSetAtIteratorCreation = _modCount;
}
@Override public boolean hasNext() {
if (_modCountOfMultiSetAtIteratorCreation != _modCount) {
throw new ConcurrentModificationException();
}
return _index < _size;
}
@Override public E next() {
if (_modCountOfMultiSetAtIteratorCreation != _modCount) {
throw new ConcurrentModificationException();
}
if (hasNext()) {
E temp = _store[_index];
_index++;
return temp;
}
throw new NoSuchElementException();
}
}
// rest of code omitted
}
3
Spring2016
UnitExam#2
CSE116IntroductiontoComputerScienceII
Spring2016
Question2[10marks]
Considerthefollowing(partial)definitionoftheTileclassinthecurrentteamproject.Definethe
rotateClockwisemethod.
package code;
import java.util.ArrayList;
public class Tile {
public
public
public
public
static
static
static
static
final
final
final
final
int
int
int
int
N
E
S
W
=
=
=
=
0;
1;
2;
3;
//
//
//
//
North
East
South
West
public static final int T = 0;
public static final int I = 1;
public static final int L = 2;
private ArrayList<Boolean> _paths;
public Tile(int type) {
_paths = new ArrayList<Boolean>();
switch (type) {
case T: _paths.add(true);_paths.add(true);_paths.add(true);_paths.add(false); break;
case I: _paths.add(true);_paths.add(false);_paths.add(true);_paths.add(false); break;
case L: _paths.add(true);_paths.add(true);_paths.add(false);_paths.add(false); break;
default: throw new IllegalArgumentException("Unknown type of tile");
}
}
public boolean canMoveTo(Tile that, int direction) {
return this._paths.get(direction) && that._paths.get((direction+2)%2);
}
public void rotateClockwise() {
// DEFINE THIS METHOD SO THAT WHENEVER CALLED THE TILE IS ROTATED 90 DEGREES
// CLOCKWISE.
}
}
4
UnitExam#2
CSE116IntroductiontoComputerScienceII
Spring2016
Question3[10marks]
Studythe(partial)Queueimplementationgivenbelow(codenotrelevanthasbeenomitted):
public class Queue<E> {
private LRStruct<E> _front;
private LRStruct<E> _back;
public QueueByCompositionWithLRStruct() {
_front = new LRStruct<E>();
_back = _front;
}
@Override public void enqueue(E item) {
_back.insertFront(item);
_back = _back.getRest();
}
@Override public E dequeue() {
if (isEmpty()) { throw new EmptyQueueException("Cannot dequeue an empty queue."); }
else {
E item = _front.getDatum();
_front = _front.getRest();
return item;
}
}
}
Afterthefollowingcodehasbeenexecuted,
Queue<Integer> q = new Queue<>();
q.enqueue(1);
q.enqueue(2);
thefollowingdiagramrepresentsthecurrentstateoftheQueue.
q
_back
_front
Queue
object
_state
LRS
object
_rest
_datum
_state
LRS
object
NonEmptyState
object
anIntegerobject
holding thevalue
1
_rest
_datum
_state
LRS
object EmptyState
object
NonEmptyState
object
anIntegerobject
holding thevalue
2
AddtoandedittheaboveobjectdiagramasneededsoitshowsthestructureoftheQueueafterthe
followingoperationshavebeenperformed:
q.dequeue();
q.enqueue(3);
IMPORTANT:assumethatnogarbagecollectionoccurs(i.e.keepobjectsthatareeligibleforgarbage
collectioninthediagram!)
5
UnitExam#2
CSE116IntroductiontoComputerScienceII
Spring2016
Question4[10marks]
RecalltheArrayList-basedimplementationofStackwedidasanin-classexercise.Assumethefrontofthe
ArrayListisatindex0andthebackisatindexsize()-1.Answerthefollowingquestions:
DidthepushandpopoperationsaffectthefrontorthebackoftheArrayList?[2points]
AssumingthatnoresizeoftheArrayListwastriggered,whatwastheefficiencyofpush?Diditrequiretime
constantorlinearinthesizeofthequeue?YouMUSTjustifyyouranswertoreceiveanycredit.[4points]
NowsupposewehadmadetheoppositedecisionaboutwhichendoftheArrayListpushandpopaffected.
AgainassumingthatnoresizeoftheArrayListwastriggered,whatwastheefficiencyofpop?Diditrequire
timeconstantorlinearinthesizeofthequeue?YouMUSTjustifyyouranswertoreceiveanycredit.[4
points]
6
UnitExam#2
CSE116IntroductiontoComputerScienceII
Spring2016
Question5[10marks]
CompletethedefinitionofthefollowingLRStruct<String>visitor.Whenexecutedonan
LRStruct<String>itmustreturnaHashSet<String>oftheStringsfromtheLRStructthathave
lengthlessthanorequaltothesuppliedargument.Forexample:
LRStruct<String> list = new LRStruct<String>();
list.insertFront("Fred");
list.insertFront("Wilma");
list.insertFront("Betty");
list.insertFront("Wilma");
list.insertFront("Pebbles");
HashSet<String> answer = list.execute(new ExamVisitor(), 5);
System.out.println(answer);
mustproducethefollowingoutput(thoughorderisnotimportant,sincewe'redealingwitha
HashSet):
[Wilma, Betty, Fred]
Completethedefinitionofthevisitorbelow:
public class ExamVisitor implements IAlgo<HashSet<String>,String,Integer> {
@Override
public HashSet<String> emptyCase(LRStruct<String> host, Integer maxLength) {
}
@Override
public HashSet<String> nonEmptyCase(LRStruct<String> host, Integer maxLength) {
}
}
7
Download