16
Name: Preceptor Name: Login Name: Precept Number: This exam has 9 questions. Do all of your work on these pages, giving the answer in the space provided. Write your login and precept number at the top. Put your name on each page (now). Write and sign the Honor Code pledge. “I pledge my honor that I have not violated the Honor Code during this examination.” Question Worth Earned 1 NP-Completeness 5 2 Analysis of algorithm 6 3 Turing Machines 8 4 ADT, automata 14 5 Arrays, trees, recursion 11 6 Java 6 7 TOY, automata, linked lists, architecture 15 8 Sequential circuits, finite state automata 22 9 Recursion, finite state automata 13 Total 1 00 Precepts: 1 MF10-10:50 Matt 4 MF2:30-3:20 Doug 2 MF11-11:50 Kevin 5 M7, F2:30 Lisa 3 MF1:30-2:20 Lisa 6 MF1:30-2:20 Doug Computer Science 126 Final Exam 5/21/200 1 1:30pm - 4:30pm

Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

Name: Preceptor Name:Login Name: Precept Number:

This exam has 9 questions. Do all of your work on these pages, giving the answer in the space provided. Writeyour login and precept number at the top. Put your name on each page (now). Write and sign the Honor Codepledge.

“I pledge my honor that I have not violated the Honor Code during this examination.”

Q u estio n W o rth E a rn ed

1 NP-Completeness 5

2 Analysis of algorithm 6

3 Turing Machines 8

4 ADT, automata 14

5 Arrays, trees, recursion 11

6 Java 6

7 TOY, automata, linked lists, architecture 15

8 Sequential circuits, finite state automata 22

9 Recursion, finite state automata 13

To ta l 1 00

Precepts:

1 MF10-10:50 Matt 4 MF2:30-3:20 Doug

2 MF11-11:50 Kevin 5 M7, F2:30 Lisa

3 MF1:30-2:20 Lisa 6 MF1:30-2:20 Doug

Computer Science 126 Final Exam5/21/200 1 1:30pm - 4:30pm

Page 2: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

1 o f 15

Name:

1. NP-Completeness. [5]Which of the following can we infer from the fact that the traveling salesperson problem is NP-complete, if weassume that P is not equal to NP?(A) There does exist an algorithm that solves arbitrary instances of the TSP problem.

(B) There does not exist an algorithm that efficiently solves arbitrary instances of the TSP problem.

(C) There exists an algorithm that efficiently solves arbitrary instances of the TSP problem, but no one has beenable to find it.

(D) The TSP is not in P.

(E) All algorithms that are guaranteed to solve the TSP run in polynomial time for some family of input points.

(F) All algorithms that are guaranteed to solve the TSP run in exponential time for all families of input points.

A, B, D.

This is exercise #1 on page 243 of the course packet.

Page 3: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

2 o f 15

Name:

2. Analysis of algorithm. [6]Consider the following array manipulation code:

(1) Which of the following is true?

(A)In the best case (i.e., for some sequence of r andom integers generate by rand()), the number ofcomparisons is proportional to N.

(B)In the worst case, the number of comparisons is proportional to N2.

(C)In the average case, the number of comparisons is proportional to N log2 N.

B.The best, worst, and average cases of this program take the same number of comparisons.

(2) Fill in the blanks:

(A)If it takes 1 second to solve a random input of size 1000, it will take roughly 100 seconds to solve arandom instance of size 10,000.

(B)If it takes 1 second to solve a random input of size 1000, it will solve a random instance of roughly size60 in 1 hour.

(C)The purpose of function f() is to sort the array a[] in ascending order .

#include <stdio.h>

#include <stdlib.h>

#define SIZE 100

void f(int a[], int left, int right) {

int i, j, t;

for (i=left+1; i<=right; i++) {

for (j = i; j > left; j--) {

if (a[j] < a[j-1]) {

t = a[j];

a[j] = a[j-1];

a[j-1] = t;

}

}

}

}

int main(void) {

int a[SIZE];

int i;

for (i = 0; i < SIZE; i++) {

a[i] = rand();

}

f(a, 0, SIZE-1);

return 0;

}

Page 4: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

3 o f 15

Name:

3. Turing Machines. [8]

In the Turing Machine illustrated above, the state labeled with “Move Left” is the start state and the state labeledwith “Yes” is the accept state.This Turing Machine erases two 1s for every 0 it sees until it can no longer do so.

(a) Does the machine accept the following string (given the initial read head position)?

(b) Does the machine accept the following string?

(c) Does the machine accept the following string?

(d) Does the machine accept the following string?

(e) Does the machine accept the following string?

(f) Characterize the strings that are accepted by this Turing machine, using one English sentence.

A string that contains twice as many 1s as 0s.

M ov e

0/0/L1/1/Lx/x/L

#/#/RL eft

S k ip

x/x/R

x#/#/R

Yes

G ot

0

G ot1

0/0/Rx/x/R

G ot01 o r N o

#/#/R

G ot

11

#/#/R

x/x/R

0/0/Rx/x/R

#/#/R

1/x/L

0/x/L

x/x/R1/1/R

#/#/R

10

# 0 1 #No

# 0 1 1 #Yes

# 0 1 0 #No

# 1 1 0 0 0 0 1 1 #No

# 1 1 1 1 0 1 1 0 0 #Yes

Page 5: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

4 o f 15

Name:

4. ADT, automata. [14]The following code emulates an automaton that employs a queue.

The function returns 1 if the emulated automaton accepts the string, 0 otherwise.

(a) Give an example string of length 9 that is accepted by this automaton. This string should include at least three different kinds of characters.

ababxabab

A string that consists of two identical halfs separated by an “x”.

(b) Does there exist a finite state automaton that is capable of recognizing the same set of strings? If yes, give aregular expression of the accepted strings. If not, justify your conclusion with 2 or 3 sentences.

No. Consider strings of the kind “aaxaa” or “aaaaxaaaa”. Recognizing such strings requires the ability tocount, which FSAs do not have.

int machineA(char input[]) { int i; char c; int state = 0; Queue q = queueInit();

for (i = 0; input[i] != '\0'; i++) { c = input[i]; if (state == 0) { if (c == 'x') state = 1; else queuePut(q, c); } else if (c == 'x' ||

queueIsEmpty(q) || c != queueGet(q))

return 0; }

if (state == 1 && queueIsEmpty(q)) return 1; else return 0;}

Page 6: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

5 o f 15

Name:

(c) The following code uses two stacks instead of one queue to emulate the same automaton. Fill in the missinglines. Do not declare or use any o ther data structures or variables. You may assume the following stackinterface:

This is a simpler variant of exercise #11 on page 226 of the course packet: implementing a queue using twostacks.

Stack stackInit();int stackIsEmpty(Stack s);void stackPush(Stack s, char item);char stackPop(Stack s);

int machineB(char input[]){ int i=0; char c; int state = 0; Stack s1 = stackInit(), s2 = stackInit();

for (i=0; input[i] != '\0'; i++) { c = input[i]; if (state == 0) { if (c == 'x') {

while (!stackIsEmpty(s1)) stackPush(s2, stackPop(s1)); state = 1;

} else stackPush(s1, c); } else {

if (c == 'x' || stackIsEmpty(s2) || c != stackPop(s2))

return 0;

/* note that we must test for stackIsEmpty() before we attempt to execute stackPop() */

} } if (state == 1 && stackIsEmpty(s2)) return 1; else return 0;}

Page 7: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

6 o f 15

Assumptions:Throughout the rest of the exam, we assume that the C definitions of a linked list and a binary tree are as the fol-lowing:

When we insert into a binary search tree, we shall assume the following (standard) bstInsert() function.

typedef struct ListNode *Link;

struct ListNode {

int key;

Link next;

};

typedef struct TreeNode *Tree;

struct TreeNode {

int key;

Tree left;

Tree right;

};

Tree bstInsert(Tree tree, int key) { if (tree == NULL) { tree = malloc(sizeof(*tree)); tree->key = key; tree->left= NULL; tree->right = NULL; return tree; } if (key < tree->key) { tree->left = bstInsert(tree->left, key); } else { tree->right = bstInsert(tree->right, key); } return tree;}

Page 8: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

7 o f 15

Name:

5. Arrays, trees, recursion. [11]

(a) Graphically draw the tree produced by this code.

This code builds a balanced tree from a sorted array: it puts the middle element of the array at the root of thetree and then recursively builds each half of the tree from each half of the array.

(b) Suppose the node with the key value of 3 in the above tree is removed. We want to move one of the leafnodes into the position occupied by this removed node. (None of the remaining nodes is to move.) Which ofthe leaf nodes is eligible to be moved without violating the binary search tree property.

2 or 4.

This question shows how one implements deletion from a BST: by replacing the deleted node with a leaf.

(c) Suppose the constant SIZE in the above code is replaced with the value 4095. What i s the height of theresulting tree? Note that the height of a single node tree is defined to be 1.

log2 (4095+1) = 12

#include <stdio.h>

#define SIZE 15

int a[SIZE];

Tree makeTree(Tree t, int a[],

int l, int r)

{

int m;

if (l > r) return t;

m = (l + r) / 2;

t = bstInsert(t, a[m]);

if (l == r)

return t;

t = makeTree(t, a, l, m-1);

t = makeTree(t, a, m+1, r);

return t;

}

int main(void)

{

int i;

Tree tree;

for (i = 0; i < SIZE; i++) {

a[i] = i;

}

tree = makeTree(NULL, a, 0, SIZE-1);

return 0;

}

20

1

3

64

5

108

9

11

1412

13

7

Page 9: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

8 o f 15

Name:

6. Java [6](a) Suppose the following working files exist on a Unix system. Which of them are guaranteed to work when

they are copied to a Windows PC?

(A) A Java source file (a .java file).

(B) A byte code file (a .class file).

(C) The Java compiler (javac).

(D) The Java virtual machine (java).

A, B.

(b) What does the following Java program print?

1000500750

Even when a Boss object (b) is converted to a super class Employee object (e2), the Java virtual machine“knows” that e2 is really a Boss object and invokes the right Boss.Bonus() method on e2, even from within anEmployee.average() method. We never explicitly covered this in lecture: one way of answering this questioncorrectly (in addition to guessing) is to pretend that you’re the Java language designer and ask yourself thequestion of whether a different alternative is acceptable, especially in a collaborative object-oriented develop-ment environment where the Employee and the Boss classes could be developed by different people...

class Employee {

int years;

public Employee() {

years = 0;

}

public void Worked(int y) {

years = y;

}

public int Bonus() {

return years * 100;

}

int average(Employee e) {

return (this.Bonus() +

e.Bonus())/2;

}

}

class Boss extends Employee {

public int Bonus() {

return years * 200;

}

}

class Test {

public static void main(String[ ] args) {

Boss b = new Boss();

b.Worked(5);

Employee e1 = new Employee( );

e1.Worked(5);

Employee e2 = b;

System.out.println(b.Bonus( ));

System.out.println(e1.Bonus ());

System.out.println(e1.avera ge(e2));

}

}

Page 10: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

9 o f 15

Name:

7. TOY, automata, linked lists, architecture. [15](a) In ou r lectures, when we discussed the relationship between abstract automaton and general purpose

computers, we assumed that the general purpose computers have unlimited memory. In this question, let usconsider a TOY machine that has only limited memory (256 words) that cannot be expanded. Which one ofthe following choices is true?

(A) TOY can simulate the behavior of any finite state automaton (FSA).

(B) TOY can simulate the behavior of any non-deterministic finite state automaton (NFSA).

(C) TOY can simulate the behavior of any pushdown automaton (PDA).

(D) TOY can simulate the behavior of any Turing Machine (TM).

(E) All of the above are true.

(F) None of the above is true.

F.

The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannotemulate a finite state machine that has even more states. In practice, the number of states that can be emulatedby the TOY machine is huge so even a simple machine like this is already very powerful.

In the rest of this problem, we implement the following C code using the TOY instructions.

#include <stdio.h>

Link newNode(int key, Link next) {

Link x;

x = malloc(sizeof(*x));

x->key = key;

x->next = next;

return x;

}

int main(void)

{

Link x;

x = newNode(88, NULL);

x = newNode(32, x);

x = newNode(21, x);

return 0;

}

Page 11: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

10 o f 1 5

Name:

(b) Fill in the missing instructions in the following TOY program that is supposed to implement the C codeabove.

Many other legal answers exist.

// main()

10: B000 R0 <- 0 // R0 contains the constant 011: B101 R1 <- 1 // R1 contains the constant 112: B202 R2 <- 2 // R2 contains the constant 213: B458 R4 <- 5814: B500 R5 <- NULL

15: 8730 jump and link to 30 // newNode(88, NULL)

16: B420 R4 <- 20

17: 1560 R5 <- R6

18: 8730 jump and link to 30 // newNode(32, R6)

19: B415 R4 <- 15

1A: 1560 R5 <- R6

1B: 8730 jump and link to 30 // newNode(21, R6)

1C: 0000 halt

// newNode(int key, Link next);

30: 9640 R6 <- mem[40] // R6 points to newly allocated mem.31: 1362 R3 <- R6 + 2 // next available memory location32: A340 mem[40] <- R3 // update the available mem. location

33: AC60 mem[R6+0] <- R4 // store “key” in the new memory

34: AD61 mem[R6+1] <- R5 // store “next” in the new memory

35: 5807 pc <- R0 + R7 // function return

40: 00A0 // initial location of avail. memory

Page 12: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

11 o f 1 5

INSTRUCTION FORMATS

Format 1: opcode, r0, r1, and r2Format 2: opcode, r0, and 8-bit addr

Indexed addressing (for format 2):if leading bit of r0 hex digit is 1,then addr = r1 + r2

TRANSFER between registers and memory

9: loadA: storeB: load address

r0 <- mem[addr]mem[addr] <- r0r0 <- addr

ARITHMETIC operations

1: add2: subtract3: multiply

r0 <- r1 + r2r0 <- r1 - r2r0 <- r1 * r2

LOGICAL operations

C: xorD: andE: shift rightF: shift left

r0 <- r1 ^ r2r0 <- r1 & r2r0 <- r0 >> addrr0 <- r0 << addr

CONTROL

0: halt4: system call5: jump6: jump if positive7: jump and count

8: jump and link

haltprint r0 on ttypc <- addrif (r0 > 0) pc <- addrr0--if (r0 != 0) pc <- addrr0 <- pcpc <- addr

Page 13: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

12 o f 1 5

Name:

(c) Consider the following datapath of the TOY machine.

And consider the following TOY instruction of the above TOY program:

Right before the moment (a falling clock edge) when this instruction is about to complete, give the values of thefollowing signals in hexadecimal:

In the context of the TOY program shown on Page 10, R0 always contains the value 0; therefore, the content ofbus2 is 0.

op co d e (15 :12 ) r0 (11 :8) r1 (7 :4) r2 (3 :0 )

In stru c tio n L atch (IR )

In stru c tio nM em o ry

A dd er

M U X

P C

Imm 8

n P C se l

Im m 8

1

IA dd ress

In str

C l

C l

r0

3

r1

3

r2

3

16

R egW r

8x16-bitR egister s

16

163

16

ALUctrl

b u s0bu s1

bu s2

2Cond

8

8

8

16

M U X

D ataM em ory16

M U X

8

Imm 88

16

C l

M em W r

A dd rSel

W B sel

16

S ign E xt

16

DataIn

DA ddress

2

C om p

2

bu s0

ALUout

32: A340 mem[40] <- R3 // update the available mem. location

PC: 32

RegWr: 0

r0: 3

r1: 4

r2: 0

MemWr: 1

DAddress: 40

bus2: 0

Page 14: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

13 o f 1 5

Name:

8. Sequential circuits, finite state automata. [22]

Two master-slave D flip-flops, also known as negative edge-triggered D flip-flops (flip-flops that change state onfalling clock edges) are connected as shown in the figure above. Both A and B are initialized to 0. X is an inputsignal. Z is an output signal.

(a) Fill in the timing diagram below for the signals A, B, and Z. (You may assume that the delays introduced by the flip-flops, the gates, and the wires are negligible.)

A B

DA DB

Clock

X

Z

TimeClock 0

1

0

1

0

1

0

1

0

1

X

A

B

Z

Page 15: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

14 o f 1 5

Name:

(b) In the following truth table, A and B are the current states of the flip-flops. A+ and B+ are the next states ofthe flip-flops after the next falling clock edge. Complete the truth table. (You may o mit t he rowscorresponding to AB=10.)

(c) The above sequential circuit implements a finite state machine: a state is represented by the values of thetwo flip-flops. When Z=1, it signifies that the current state is the accept state. The input signal X can changeonly when the clock is low, and it can change at most once per clock cycle. Complete the following statetransition diagram. Label the accept state. (You may omit the state corresponding to AB=10.)

(d) Characterize the strings that are accepted by this finite state machine, using one English sentence.

Strings that end with the sequence “10”.

Finite state machines are not only of theoretical interest, they are also embedded in all kinds of real-worlddevices. This question shows an FSA built with circuit components that we have learned in this class. With Nflip-flops, we can build an FSA with a maximum of 2N states. If the specific FSA that we build requires fewerstates (as in this case), then some of these extra states are called “don’t-care” states that can never be enteredduring the normal operation of the FSA (such as AB=10 in this case).

A B X A + B + Z

000 000

001 010

010 111

011 010

100

101

110 000

111 010

AB=00X = 0

AB=01

AB=11

X = 1X = 1

X = 0X = 1

X = 0

Page 16: Computer Science 126 Final Exam 5/21/2001 1:30pm - 4:30pm · The TOY machine with limited resource can only emulate a finite number of states, so theoretically it cannot emulate a

15 o f 1 5

Name:

9. Recursion, finite state automata. [13]Consider the following recursive program:

(a) What does the program print?NoYesYesNoYes

(b) This program emulates a finite state automaton. Complete the following state transition diagram.

(c) Which is the start state? Which is the accept state? start state = L accept state = N

(d) Characterize the strings that are accepted by this finite state machine, using one English sentence.Strings that end with the sequence “10”.

In lectures, we learned that regular expressions and FSAs are equivalent. This question shows a third way ofdescribing a language: a “grammar”; this recursive program is a simple example of a program that can recog-nize strings specified by a grammar; such programs are called “parsers”. The compiler that you use contains amore sophisticated parser for the C grammar; the browser that you use contains a more sophisticated parserfor the HTML grammar.

#include <stdio.h>

int L(char s[], int len) {

if (len == 0) return 1;

return (s[len-1] == '0') && (L(s, len-1) || N(s, len-1));

}

int M(char s[], int len) {

if (len == 0) return 0;

return (s[len-1] == '1') && (L(s, len-1) || M(s, len-1) || N(s, len-1));

}

int N(char s[], int len) {

if (len == 0) return 0;

return (s[len-1] == '0') && M(s, len-1);

}

void machine(char s[], int len) {

if(N(s, len))

printf("Yes\n");

else

printf("No\n");

}

int main(void) {

machine("0", 1);

machine("10", 2);

machine("1010", 4);

machine("101001", 6);

machine("1010010", 7);

return 0;

}

L0

M1

N

1

01

0