+ All Categories
Home > Documents > Answer Key - Villanova Universitymap/1051/s15/final-key.pdfAnswer Key CSC1051 Data Structures and...

Answer Key - Villanova Universitymap/1051/s15/final-key.pdfAnswer Key CSC1051 Data Structures and...

Date post: 27-Jun-2018
Category:
Upload: ngohanh
View: 239 times
Download: 0 times
Share this document with a friend
18
Answer Key CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari CSC 1051 Algorithms and Data Structures I Final Examination May 2, 2015 Name:______________________________ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 20 TOTAL 100 Please answer questions in the spaces provided. If you make a mistake or for some other reason need more space, please use the back of and clearly indicate where the answer can be found. Good luck and best wishes for a wonderful summer!
Transcript

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

CSC 1051 Algorithms and Data Structures I

Final Examination

May 2, 2015

Name:______________________________

Question Value Score1 10

2 10

3 10

4 10

5 10

6 10

7 10

8 10

9 20

TOTAL 100

Please answer questions in the spaces provided. If you make a mistake or for some other reason need more space, please use the back of and clearly indicate where the answer can be found. Good luck and best wishes for a wonderful summer!

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

1.(________/10)Whatgetsprinted?Pleaseshowoutputasitwillappear,orindicate“NOOUTPUT”,orshowsomeoftheoutputfollowedby“INFINITELOOP.” int a = 5; do { a--; System.out.println(a); }while (a >= 6) System.out.println("Done: " + a); for (int a = 4; a > 0; a++) System.out.println(a * 2); System.out.println("Done: " + a); String[] notes = {"do", "re", "mi"}; for (String st: notes) System.out.println(st + st); System.out.println("Done: "); for(int a = 1; a <= 3; a++) for (int b = 5; b <= 6; b++) System.out.println(a + "\t" + b); System.out.println("Done");

Output:1 5 1 6 2 5 2 6 3 5 3 6 Done

Output:dodo rere mimi Done

Output:4 Done: 4

Output:8 10 12 14 … INFINITE LOOP

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

2.(________/10)a) Show what gets printed and rewrite using if/else: char ch = 'n'; System.out.print ("The answer is "); switch(ch) { case 'y': System.out.println ("positive."); break; case 'N': System.out.println ("negative."); break; default: System.out.println ("unclear."); }

2. Show what gets printed and rewrite using while and if/else (i.e., eliminate the for and conditional operator): for (int a = 0; a < 4; a++) System.out.println(a + (a % 2 == 0? " yes ": " no "));

Output:The answer is unclear.

Usingif/else:char ch = 's'; System.out.print ("The answer is "); if (ch == 'y') System.out.println ("positive."); else if (ch == 'N') System.out.println ("negative."); else System.out.println ("unclear.");

Usingwhileandif/else:int a = 0; while (a < 4) { System.out.print(a); if (a % 2 == 0)

System.out.println(" yes"); else

System.out.println(" no"); a++; }

Output: 0 yes 1 no 2 yes 3 no

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

3.(________/10)Considerthefollowingprogram: import java.util.Scanner; import java.io.*; public class FinalS15FileIO { public static void main(String[] args) throws IOException { Scanner inFile; PrintWriter outFile; inFile = new Scanner (new File("data-in.txt")); outFile = new PrintWriter("data-out.txt"); while (inFile.hasNext()) { String line = inFile.nextLine(); Scanner scan = new Scanner(line); int count = 0; while (scan.hasNext()) { String token = scan.next(); count ++; } outFile.println(count); } outFile.close(); } } a) Suppose the file data-in.txt is used as the input file. Show the contents of the file data-out.txt after execution of the program. b) List two examples of situations that could cause IOExceptions in the above code.

file not found for the Scanner – cannot do input bad file name for the PrintWriter – cannot create the file

c) Suppose you want to catch and handle the IOExceptions using the following catch clause: catch (IOException e) { System.out.println("Warning: problem with IO. Run interactively."); inFile = new Scanner(System.in); outFile = new PrintWriter(System.out); }

(i.e., keep running, but issue a warning and do interactive I/O instead) • Show how to incorporate this in the above program: 1) Draw a box around

the statements of the above program that you would include in the try block, and 2) mark the position where you would insert the catch code.

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

4.(________/10) (a) WriteaJavamethodfindMax() withoneparameterthatisa2Darrayofdouble,thatfindsandreturnsthelargestofallthevaluesinthe2Darray.Assumethatallthevalueswillbepositive.Theremayberepetitions,butitshouldnotmatter,themethodshouldstillreturnavaluethatisnolessthananyoftheothervalues.Themethodshouldhaveoneparameter(the2Darrayofdouble)anditshouldreturnadouble,andnotprintanything.

(b) Assume findMax() is defined as a static method in the class below. Complete the code of main() below to use findMax so as to print the largest of the numbers stored in either of the arrays a and b (i.e., the largest number overall). public class ThisIsATest { public static void main(String[] args) { double[][] a = ... (arraysareinitializedwithsomevalues) double[][] b = ... //**** print the largest value stored in either a or b

double amax = findMax(a); double bmax = findMax(b); if (amax > bmax)

System.out.println(amax); else System.out.println(bmax);

} }

public static double findMax(double[][] array) { double max = 0; for (int i = 0; i < array.length; i++)

for (int j = 0; j < array[i].length; j++) if (array[i][j] > max)

max = array[i][j]; return max; }

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

5. (________/10).(a) Show the output produced by the following code fragment:

String mess = ""; char[] grades = {'A', 'B', 'C', 'D', ’F'}; for (char ch: grades) mess = ch + mess; System.out.println (mess);

_____FDCBA__________________

(b) Show the output produced by the following code fragment:

char[] grades = {'A', 'B', 'C', 'D', ’F'}; for (char ch: grades) System.out.print ((char) (ch + 1));

_____BCDEG__________________ (c) Suppose an int array ratings contains values in the range 0-3. Write a code fragment that creates an array count that contains the frequency of occurrences of 0’s, 1’s, 2’s and 3’s in the ratings array, and then prints this information.

Example: if the array ratings has these contents:

ratings 0 1 2 3 4 5 6 2 3 2 1 0 2 2

Your code should create the array count with the following contents: count

0 1 2 3 1 1 4 1

and the output would be: Count for 0: 1 Count for 1: 1 Count for 2: 4 Count for 3: 1

Write your code fragment below. Assume the array ratings is already initialized to some values. Your code should work for any size array.

int[] count = new int[4]; for (int x: ratings) count[x]++;

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

6.(________/10) SupposeyouhaveaDieclassdefinedasfollows: import java.awt.*; public class Die { private int faceValue; // current value showing on the die // Constructor: Sets the initial face value. public Die() { faceValue = 1; } // Rolls the die and returns the result. public int roll() { faceValue = (int)(Math.random() * 6) + 1; return faceValue; } // Face value mutator. public void setFaceValue (int value) { faceValue = value; } // Face value accessor. public int getFaceValue() { return faceValue; } // Returns a string representation of this die. public String toString() { String result = Integer.toString(faceValue); return result; } // Draws the die on page at position x, y. public void draw (Graphics page, int x, int y) { page.setColor (Color.white); page.fillRect (x, y, 30, 30); page.setColor (Color.black); page.drawString(Integer.toString(faceValue), x+10, y+20); } } Onthefacingpage,writetheJavacodeforadriverclassthatusestheDieclasstodeterminehowlikelyitistoroll“snakeeyes”,i.e.,twoones.Usethefollowingapproach:Ø DeclareandinstantiatetwoDieobjects,die1anddie2Ø Rollthem10,000times(orsomesufficientlylargenumber,specifiedbyaconstantin

yourprogram)whilekeepingtrackofhowmanytimesyourolledonesonbothdiceØ Intheend,printhowmanytimesthedicewererolled,thenumberofsnakeeyes,and

proportionofsnakeeyes(i.e.,probability).Careful:useacastwhendividingintegers!

çWriteyouransweronfacingpage(backofpreviouspage).çAnswerkeyonnextpageèè

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

public class SnakeEyes { public static void main(String[] args) { final int NUM_TIMES = 10000; Die die1 = new Die(); Die die2 = new Die(); int snakes = 0; // counter for snake eyes for (int i = 0; i < NUM_TIMES; i++) { die1.roll(); die2.roll(); if (die1.getFaceValue() == 1 && die2.getFaceValue() == 1) snakes ++; } System.out.println("The dice were rolled " + NUM_TIMES); System.out.println("There were " + snakes + " snake eyes."); System.out.println("Approximate probability of " + "getting snake eyes: " + ((double) snakes/ NUM_TIMES)); } }

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

7.(________/10) Supposeyouhavea Passenger classdefinedasfollowstorepresentpassengersintheTitanic:

public class Passenger {

// instance data private int status; private boolean child; private char sex; private boolean survivor; // constructor public Passenger(int status, boolean child, char sex, boolean survivor) { this.status = status; this.child = child; this.sex = sex; this.survivor = survivor; } // toString() – returns String description of Passenger public String toString() { String pass = ""; switch (status) { case 1: pass += "1st class\t"; break; case 2: pass += "2nd class\t"; break; case 3: pass += "3rd class\t"; break; case 4: pass += "crew\t"; break; } pass += (child? "child": "adult") + "\t"; pass += ((sex == 'm') ? "male" : "female") + "\t"; pass += (survivor? "survived": "perished"); return pass; }

}Onthenextpage,writethecodeforaPassengerCollectionclasstorepresentthelistofpassengersoftheTitanicandtokeeptrackoftotalnumberofpassengersandsurvivors,usinganarrayofPassengerobjects.Somebitsofthecodeandcommentsarealreadywritten.Usethesecommentsasguidelinesforyourcode,inthespacesprovidedonthenextpage.NotethatyouonlyneedtoimplementtheconstructorandaddPassenger()methods,whichshouldinitializeandupdate,respectively,thearrayandthetwocounts(i.e.,countandnumSurvivors).

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

(Question 7, continued)public class PassengerCollection { private Passenger[] collection; private int count; private int numSurvivors; // additional count: survivors //------------------------------------------------------ // Constructor: Creates an initially empty collection // with space for up to 5000 passengers. // Initializes count and numSurvivors appropriately. //------------------------------------------------------ public PassengerCollection () { collection = new Passenger[5000]; count = 0; numSurvivors = 0; } //------------------------------------------------------ // Method addPassenger(): Adds a Passenger to the // collection. Update // count and numSurvivors. //------------------------------------------------------ public void addPassenger (int status, boolean child, char sex, boolean survivor) { collection[count] = new Passenger(status, child, sex, survivor); count++; if (survivor) numSurvivors++; }

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

8.(________/10) Constructanalgorithmthatinputsanintegernumand10,000otherintegersandprintsamessageindicatingwhethernumwasfoundamongthe10,000otherintegers,followedbyagoodbyemessage. Hint:Youneedtouseabooleanvariablefoundtokeeptrackofwhetheryoufoundamatch.Example:Ifnum(i.e.,thefirstnumberinput)is1318,and10,000othernumbersareinputafterthat,noneofwhichisequalto1318,thealgorithmshouldprint:

Searching for 1318 Not found Goodbye

Alternatively,ifthenumber1318occurredoneormoretimesamongtheothernumbers,itshouldprint:Searching for 1318 Found it! Goodbye

Directions:Writeyouralgorithmbyrearrangingandstructuringelementschosenfromthelistbelow,usingindentationtoshowstructure.Donotuseanythingelseandnotethatnotalloftheseareneeded,butyoumayuseoneofthemmorethanonce,ifnecessarfound=truefound=falseinputnuminputxcount=1count=count+1x=x+1if(x==num)if(found)if(found==true)if(found==false)if(x!=num)

elsewhile(count<=10000)while(num<=10000)while(count<=num)print“Searchingfor”numprintxprintnumprint“Foundit!”print“Notfound”print“Goodbye”

inputnumfound=falsecount=1while(count<=10000)

inputxif(x==num)

found=true count=count+1if(found==true)

print“Foundit!”else

print“Notfound”print“Goodbye”

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

9.(________/20) WriteacompleteJavaprogramconsistingofadatatypeCatandaclientCrazyCatLadyanddrawaUMLclassdiagramforyourclasses. Example:a)TheCatclassshouldhavethefollowingmethods:

• Constructor:Oneparameter(forthename).SetsCat’sageto0andlivesto9.• birthday():increasesageofCatby1.• death():decreasestheCat’snumberoflivesby1.• toString():returnsaStringcorrespondingtothisCat.• getAge():returnsthisCat’sage• draw(Graphics page, int x, int y):drawsthisCatinthecurrent

Graphicscontextatpositionx, y. Pleasedonotdoanythingfancyhere:justdrawasimpleshapetorepresentthecatandadditsnamenearby.Addanotherfeaturesuchascolorordifferentshapetodepicttheageornumberoflives(youonlyneedtodooneofthem).

b)TheclientCrazyCatLadyshouldimplementthefollowingalgorithm:

o InstantiatethreevariablesoftheCatclassnamedcat1,cat2,cat3(Kindlymakeupfunnynamesforthem–I’mspendingmyholidaysgradingthisexam!J)

o Printtheinfoof cat1,cat2,cat3• Let’spretendthattwoyearshavegoneby…SotheCats’agesneedtoincrease.

Also, cat3hasdonesomethingstupidandlosesalife.Writesomecodethatusesthebirthday() and death() methodstomodelthissituation.

o Printtheinfoof cat1,cat2,cat3(again).o Calculateandprinttheaverageageofthecats.o NOTE:thisisnotagraphicalclass,soitdoesNOTusethedraw()methodatall.

c)DrawaUMLclassdiagramdepictingtheclassesCatandCrazyCatLady.WritethecompletecodeforthetwoclassesandUMLdiagraminthenext3pages.ItisNOTnecessarytoincludecommentswithyourcode,butbesuretousegoodindentation.èèè

Ø Name: Henri Ø Age: 7 Ø Lives: 5

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

public class Cat { private int age; private int lives; private String name; // Constructor: One parameter (for the name). // Sets Cat's age to 0 and lives to 9. public Cat(String name) { this.name = name; age = 0; lives = 9; } // birthday(): increases age of Cat by 1. public void birthday() { age++; } // death(): decreases the Cat's number of lives by 1. public void death() { lives--; } // toString(): returns a String corresponding to this Cat. public String toString() { return (name + ", Age: " + age + ", Lives: " + lives); } // getAge(): returns this Cat's age public int getAge() { return age; } // draw(): draws this Cat on page at position x, y public void draw(Graphics page, int x, int y) { page.setColor(age < 5? Color.black: Color.gray); page.fillOval(x, y); page.setColor(Color.red); page.drawString(name, x, y); } }

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

public class CrazyCatLady { public static void main(String[] args) { //Instantiate 3 variables of the Cat class named cat1, cat2, cat3 Cat cat1 = new Cat("Macavity"); Cat cat2 = new Cat("Mungojerrie"); Cat cat3 = new Cat("Rumpelteazer"); // print info on cats System.out.println(cat1); System.out.println(cat2); System.out.println(cat3); // Let's pretend that two years have gone by… // So the Cats' ages need to increase. cat1.birthday(); cat2.birthday(); cat3.birthday(); cat1.birthday(); cat2.birthday(); cat3.birthday(); // Also, cat3 has done something stupid and loses a life. cat3.death(); // print info on cats System.out.println(cat1); System.out.println(cat2); System.out.println(cat3); // Calculate and print the average age of the cats. System.out.println( "Average feline age: " + (double) (cat1.getAge() + cat2.getAge() + cat3.getAge()) / 3 ); } }

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

CrazyCatLady

main(args: String[]): void

Cat name: String age: int lives: int

birthday(): void death(): void toString: String getAge(): int draw(p: Graphics, x:int, y:int): void

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari

AnswerKey

CSC1051 Data Structures and Algorithms I Spring 2015 Dr. Papalaskari


Recommended