csc 1051 algorithms and data structures i final ...map/1051/s17/final-key.pdfname:___key_____...

17
Answer Key Villanova University CSC 1051 www.csc.villanova.edu/~map/1051 Dr. Papalaskari CSC 1051 Algorithms and Data Structures I Final Examination May 12, 2017 Name:___KEY___________________ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the spaces provided. Please be legible. If you make a mistake or need more space, use backs of pages - clearly indicate where the answer can be found. Good luck and best wishes for a great summer!

Upload: others

Post on 29-Aug-2020

4 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

CSC 1051 Algorithms and Data Structures I

Final Examination May 12, 2017

Name:___KEY___________________

Question Value Score1 10

2 10

3 10

4 10

5 10

6 10

7 10

8 10

9 10

10 10

TOTAL 100

Please answer questions in the spaces provided. Please be legible. If you make a mistake or need more space, use backs of pages - clearly indicate where the answer can be found. Good luck and best wishes for a great summer!

Page 2: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

1.(________/10)Whatgetsprinted?Pleaseshowoutputasitwillappear,orindicate“NOOUTPUT”.Ifthereisaninfiniteloop,besuretoshowsomelinesoftheoutputfollowedby“…INFINITELOOP”. int a = 4; do { a--; System.out.println(a); }while (a < 4) String[] word = {"up", "down"}; for (String w1 : word)

for (String w2 : word) System.out.println("yes "

+ w1 + " " + w2 + " " + w1); int size = 10; do { System.out.print(size + " => "); int category = size / 5; switch(category) { case 0: System.out.println ("S"); break; case 1: System.out.println ("M"); break; default: System.out.println ("L"); } size = size - 2; } while (size > 2); boolean flipFlop = false; for (int i = 3; i>=1; i--) { flipFlop = !flipFlop; System.out.println(i + " " + flipFlop); }

Output:3 true 2 false 1 true

Output:3 2 1 … … INFINITE LOOP

Output:yes up up up yes up down up yes down up down yes down down down

Output:10 => L 8 => M 6 => M 4 => S

Page 3: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

2.(________/10) b. Given a Random object named gen, what range of values are produced by the following expressions?

• gen.nextInt(8) ________ 0 to 7 • gen.nextInt(30) + 100 _________ 100 to 129 • gen.nextInt(3) – 2 __________-2 to 0

c. Suppose you have the following declarations; evaluate some expressions and show the output produced: String word = "kumbaya"; int num = word.length(); int n = 0; while (n < word.length()) { System.out.print("*" + word.charAt(n);

n = n + 2 }

0 40 80 120 0

40 80 120

a. Complete the code for the applet that produces the image to the left. import javax.swing.JApplet; import java.awt.*; public class Mystery extends JApplet { public void paint (Graphics page) { page.drawLine (10, 60, 90, 60); page.drawLine (20, 20, 40, 80); page.drawRect (0, 40, 60, 40); page.fillOval (40, 0, 80, 40); } }

Output:*k*m*a*a

num _7_ word.charAt(1)__u___ word.charAt(4)_a_ word.charAt(num-1) _a_

Page 4: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

3.(________/10)a.WriteaJavamethod birthday()withoneintparameternthatprints“HappyBirthday”ntimes.Themethodshouldnotreturnanything.Forexample,ifthemethodisinvokedlikethis:birthday(3),itshouldprintthefollowing:

Happy Birthday Happy Birthday Happy Birthday

b.WriteaJavamethodstars()withoneintparameternthatprintstheshapebelow.Themethodshouldnotreturnanything.Forexample,ifthemethodisinvokedlikethis:stars(5),itshouldprintthefollowing:

* ** *** **** *****

void birthday(int n) {

for (int i = 0; i < n; i++) { System.out.println(“Happy Birthday”);

} }

void stars(int n) {

for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) System.out.print(“*”); System.out.println();

} }

Page 5: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

4.(________/10)Considerthefollowingprogram:public class ArrayDemo { public static void main(String[] args) { int[] anArray; // declares an array of integers anArray = new int[10]; // allocates memory for 10 integers anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // etc. anArray[3] = 400; anArray[4] = 500; anArray[5] = 600; anArray[6] = 700; anArray[7] = 800; anArray[8] = 900; anArray[9] = 1000; System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]); System.out.println("Element at index 3: " + anArray[3]); System.out.println("Element at index 4: " + anArray[4]); System.out.println("Element at index 5: " + anArray[5]); System.out.println("Element at index 6: " + anArray[6]); System.out.println("Element at index 7: " + anArray[7]); System.out.println("Element at index 8: " + anArray[8]); System.out.println("Element at index 9: " + anArray[9]); } }

• SketchthecontentsofanArray(besuretoincludeindicesinyourdiagram). 0 1 2 3 4 5 6 7 8 9

100 200 300 400 500 600 700 800 900 1000

• WhathappensiftheanArrayisnotinitialized(ifwecommentoutthecodein(a)).allthevaluesaresettozero• Rewritea:Writeafor-looptoreplacetherepetitivecodein(a),sothatthearrayis

initializedtoexactlythesamevaluesasbefore.for (int i = 0; i < anArray.length; i++) anArray[i] = i*100 +100; • Rewrite(b):Writeafor-looptoreplacetherepetitivecodein(b),sothatthe

programproducesexactlythesameoutputasbefore.for (int i = 0; i < anArray.length; i++) System.out.println("Element at index " + "i" + ": " + anArray[i]);

b

a

Page 6: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

5.(________/10)Drawdiagramsshowingthecontentsofarray tableafterexecutionofthefollowingcodefragments.(Besuretoincludeindicesinyourdiagram). int[][] table = new int[2][3]; for (int i=0; i < 2; i++) table[i][2] = i + 1;

0 1 2

0 0 0 1

1 0 0 2

char[][] table = new char[4][2]; String sample = "Alternative facts."; int count = 0; for (int i=0; i < 4; i++) for (int j=0; j < 2; j++) { table[i][j] = sample.charAt(count); count++; }

0 1

0 ‘A’ ‘l’

1 ‘t’ ‘e’

2 ‘r’ ‘n’

3 ‘a’ ‘t’

int[][] table = new int[3][4]; for (int i=0; i < table.length; i++) for (int j=0; j < table[i].length; j++) table[i][j] = i / (j+1);

0 1 2 3

0 0 0 0 0

1 1 0 0 0

2 2 1 0 0

Page 7: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

6.(________/10) a. Trace through the following code and show what gets printed. int[] a = {40, 80, 120, 160}; int[] b = {1000, 2000, 3000, 4000}; int[] c = b; for (int i=0; i<a.length; i++)

a[i] = b[i]; a[1] = 25; b[2] = 50; c[3] = 77;

for (int x: a) System.out.print(x + " ");

System.out.println(); for (int x: b)

System.out.print(x + " "); System.out.println();

for (int x: c)

System.out.print(x + " "); System.out.println(); b. 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]++; for (int i = 0; i < count.length; i++) System.out.println ("Count for " + i + ": " + count[i]);

Output:1000 25 3000 4000 1000 2000 50 77 1000 2000 50 77

Page 8: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

7.(________/10) a. WriteamethodnamedrandomYakwithoneparameter,anarrayofString,thatreturnsarandomlyselectedStringfromthearray. b.Writeamethodnamedshufflewithoneparameter,anarrayofString,thatshufflestheelementsofthearray.

String randomYak(String[] a) { Random rand = new Random(); return a[rand.nextInt(a.length)]; }

void shuffle(String[] a) { Random rand = new Random(); // shuffling enough times (not specified in question) // using 2 * a.length for (int i = 0; i < 2 * a.length; i++)

{ int x = rand.nextInt(a.length); int y = rand.nextInt(a.length); String temp = a[x]; a[x] = a[y]; b[y] = temp;

} }

Page 9: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

//Answer for Question 8 (next page) import java.text.NumberFormat; public class Billing {

public static void main (String[] args) {

Person [] subject; subject = new Person[3]; subject[0] = new Person(“Mr Bean”); subject[1] = new Person(“person 1”); subject[2] = new Person(“person 2”); subject[0].bill(130); subject[1].bill(215); subject[2].bill(85); System.out.println(subject[0]); System.out.println(subject[1]); System.out.println(subject[2]); subject[2].bill(60); for (int i = 0; i < subject.length; i++)

System.out.println(subject[i]); int sum = 0; for (int i = 0; i < subject.length; i++)

sum = sum + subject[i].getBalance();

NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println(“Total balance:” + fmt.format(sum));

} }

Page 10: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

8.(________/10)SupposeyouhaveaPersonclassdefinedasfollows:import java.text.NumberFormat; public class Person { private String name; private double balance; public Person (String x) // constructor { name = x; balance = 0; } public double getBalance() // balance accessor { return balance; } public void bill(double amount) // bills a Person { // adds to balance) balance = balance + amount; } public String toString () // toString() {

NumberFormat fmt = NumberFormat.getCurrencyInstance(); return (name + "\t" + fmt.format(balance)); } } Onthefacingpage,writetheJavacodeforaclientthatimplementsthefollowingalgorithm:Ø Declare(butdonotinstantiate)anarraynamedsubjectthatstoresPerson

objectsØ InstantiateanarrayofthreePerson objectsandassignittosubjectØ CreateaPerson objectforsomeonenamed“Mr Bean”,andstoreitasthefirst

elementinthearraysubjectØ CreatetwomorePersonobjectsandstorethemasthenexttwoelementsinthe

arraysubjectØ Usethebill()methodtoadd$130,$215,and$85tothebalancesofthe

Personobjectsstoredinthearraysubject.Ø PrinttheinformationaboutallthePersonobjectsstoredinthearraysubject.

(doNOTusealoop,userepetitivecode).Ø Add$60tothebillofthelastPersonobjectstoredinthearraysubject.Ø PrinttheinformationaboutallthePersonobjectsstoredinthearraysubject.

(thistimeuseaforloop).Ø Computeandprintthetotalbalanceofallthesubjects.

çWriteyouransweronfacingpage(backofpreviouspage).ç

Page 11: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

9.(________/10)ConsidertheprogramResponseTimeExperiment.java onthefollowingpage. a.Rewritethecodeintheboxlabeled(a)usingtheconditionaloperatorinsteadofif/else.int outcome = (number == a + b) ? 1: 0; b.Rewritethecodeintheboxlabeled(b)usingtheconditionaloperatorinsteadofif/else.System.out.println( outcome == 1? "Correct!" : "Incorrect."); c.Annotatethecodeonthenextpagewiththenumbertomatcheachstepinthealgorithm. d.Rewritethealgorithm,modifyingitto:• Repeattheexperiment4times • Countthenumberofcorrectresponses • Computeandprinttheaverageresponse

time.

DONOTwritejavacode,justrewritethealgorithm.(Usefacingpageifyouneedmoreroomforyouranswer.)

1.inputname

2.printpersonalizedwelcomemessage&instructionsA.numCorrect=0B.totalTime=0

C.repeat4times: 3.waitforusertohit“ENTER”4.a=randomint 5.b=randomint 6.startTime=currenttime 7.printquestionusinga,b 8.inputanswer

9.endTime=currenttime 10.outcome=1or0(answeriscorrectorincorrect) 11.reactionTime=endTime–startTime 12.printoutcomeas“Correct”or“Incorrect” D.numCorrect=numCorrect+outcome E.totalTime=totalTime+reactionTimeF.averageTime=totalTime/4G.printaverageTime13.printgoodbye

Algorithm:1. inputname2. printpersonalizedwelcomemessage&instructions3. waitforusertohit“ENTER”4. a=randomint5. b=randomint6. startTime=currenttime7. printquestionusinga,b8. inputanswer9. endTime=currenttime10. outcome=1or0(answeriscorrectorincorrect)11. reactionTime=endTime–startTime12. printoutcomeas“Correct”or“Incorrect”13. printreactiontime14. print“goodbye”

Page 12: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

// ResponseTimeExperiment.java // Measure response time for addition problems. // M A Papalaskari import java.util.Scanner; import java.util.Random; public class ResponseTimeExperiment { public static void main(String[] args) { Scanner in = new Scanner(System.in); Random rand = new Random(); System.out.print("Please enter your name: "); String name = in.nextLine(); System.out.println("Hello " + name + ". Please answer as fast as you can."); System.out.println("\n\nHit <ENTER> when ready."); in.nextLine(); // wait for user to hit <ENTER> int a = rand.nextInt(100); int b = rand.nextInt(100); long startTime = System.currentTimeMillis(); System.out.print(a + " + " + b + " = "); String response = in.nextLine(); int number = Integer.parseInt(response); long endTime = System.currentTimeMillis(); int outcome; if (number == a + b) outcome = 1; else outcome = 0; long reactionTime = endTime - startTime; if (outcome == 1) System.out.println("Correct!") ; else System.out.println("Incorrect."); System.out.println("Time: " + reactionTime + "milliseconds"); System.out.println("Thank you " + name + ", goodbye."); } }

1

2

45

6

87

9

144

13

10

11

12

3

a

b

Page 13: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

10.(________/10)ConsidertheprogramResponseTimeExperiment.java.Thecodeisreproducedonthenextpagetomakeiteasierforyoutoanswerthisquestion.Thisquestionisindependentofthepreviousquestion(doesNOTassumeyouhaveansweredthepreviousquestion).a.Supposeyouwishtocreateatextfile,namedname.txt,wherenameistheStringenteredbytheuserwhenpromptedtoentertheirname.Annotatetheprogramonthenextpagetoshowwheretoinsertthefollowingcodefragmentstoaccomplishthis:

1. outfile.println((number == a + b) + "\t" + reactionTime); 2. import java.io.*; 3. throws IOException 4. outfile.close(); 5. PrintWriter outfile = new PrintWriter (name + ".txt");

b.WhichofthejavacodefragmentsabovemightthrowanIOException?(notethecorrespondingnumber)___5_______c.Supposeyouwishtopreventfileswithcertainnamesfrombeingcreated.Youhavealistofbannedwordssavedinafilenamedbanned.txtandiftheuserentersanyofthesewordsastheirname,theprogramshouldthrowanexceptionandterminate.AssumetheclassBadWordExceptionisalreadydefined.ShowwherewouldyouplacethefollowingcodeinResponseTimeExperiment.java

Scanner badWords = new Scanner(new File("banned.txt")); while (badWords.hasNext()) if (name.equals(badWords.next())) throw (new BadWordException("Watch your tongue"));

d.SupposeyouwishtohandleNumberFormatExceptionexceptionsusingthefollowingcatchclause.Drawarectanglearoundthecodeonthenextpage,indicatingwheretoplacethetryblock. catch (NumberFormatException problem) { System.out.println("FAIL: You were supposed to type in a number"); outfile.println("*"); }

Page 14: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

// ResponseTimeExperiment.java // Measure response time for addition problems. // M A Papalaskari import java.util.Scanner; import java.util.Random; public class ResponseTimeExperiment { public static void main(String[] args) { Scanner in = new Scanner(System.in); Random rand = new Random(); System.out.print("Please enter your name: "); String name = in.nextLine(); System.out.println("Hello " + name + ". Please answer as fast as you can."); System.out.println("\n\nHit <ENTER> when ready."); in.nextLine(); // wait for user to hit <ENTER> int a = rand.nextInt(100); int b = rand.nextInt(100); long startTime = System.currentTimeMillis(); System.out.print(a + " + " + b + " = "); String response = in.nextLine(); int number = Integer.parseInt(response); long endTime = System.currentTimeMillis(); int outcome; if (number == a + b) outcome = 1; else outcome = 0; long reactionTime = endTime - startTime; if (outcome == 1) System.out.println("Correct!") ; else System.out.println("Incorrect."); System.out.println("Time: " + reactionTime + "milliseconds"); System.out.println("Thank you " + name + ", goodbye."); } }

1

2

4

5 c

3

d

Page 15: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

Page 16: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari

Page 17: CSC 1051 Algorithms and Data Structures I Final ...map/1051/s17/final-key.pdfName:___KEY_____ Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please

AnswerKey

VillanovaUniversityCSC1051www.csc.villanova.edu/~map/1051Dr.Papalaskari