CS365 Final -- Spring 2016

  1. This exam allows you to use a one-page "cheat" sheet that may be filled on both sides.
  2. You must answer all of the questions.
  3. You will lose points if you choose an incorrect answer on one of the multiple answer problems
  4. Well written code that makes good use of the feature of a language and that is well-organized and readable will receive more credit than code that is poorly written or poorly organized or does not make good use of the feaures of a language.
  5. Good luck!

  1. (10 points) For each of the following user interface scenarios, choose from the following list the type of widget you think is most appropriate.
    1. slider
    2. menu/list
    3. type in text box
    4. radio button
    5. check box
    6. command button

    1. _________________ You want the user to select an occupation from a set of 50 possible occupations.

    2. _________________ You want the user to select one of 6 rooms returned from a hotel search engine. The user may select only one room.

    3. _________________ You want the user to select a font style. The possible options are bold, italic, underline, and oblique. They can select anywhere from zero to all four options.

    4. _________________ You want the user to enter the weight of a package and are willing to accept any weight up to 100000 pounds.

    5. _________________ You want the user to specify a color by entering the values for red, green, and blue as integers between 0 and 100. The user should be able to rapidly change the values and see the current color immediately updated in a color swatch.

  2. (4 points) Functions are considered first-class objects in a language if which of the following condition applies:

    1. A function may be passed as an argument to a function
    2. A function pointer may be passed as an argument to a function
    3. The language supports nested functions (i.e., a "private" function can be defined by declaring it within another function).
    4. A function can be created as a value within a function and returned as a value from that function.

  3. (4 points) The following technique used by functional language interpreters involves tagging an expression internally when an expression is first evaluated, and saving the expression's computed value. Thereafter, references to the expression use this computed value, rather than re-evaluating the expression.
    1. tail recursion
    2. memoization
    3. lazy evaluation
    4. applicative evaluation

  4. (4 points) Which of the following is an argument-passing scheme in functional programming that evaluates a function argument only when it is needed in the body of a function.
    1. applicative evaluation
    2. on demand evaluation
    3. normal order evaluation
    4. strict evaluation

  5. (4 points) Which of the following terms is used to describe a concurrency condition in which memory may have an unpredictable value due to two threads trying to modify the same memory simultaneously.
    1. deadlock
    2. liveness
    3. starvation
    4. race condition

  6. (4 points) Which of the following programs would be the best candidate for being implemented in a scripting language?

    1. A climate-modeling simulation
    2. A math library that provides a set of functions, such as trigonometric functions, random number generators, and exponentiation functions
    3. A program to calculate the student grades in a courses
    4. A compiler

  7. (4 points) Which of the following programs would be the best candidate for being implemented in a functional language?

    1. A program for finding the best move in a chess game by traversing a tree of possible moves.
    2. A talk server/client implementation, like the one in your JTtalk assignment.
    3. A graphical user interface for a drawing program.
    4. A program for counting word frequencies in a file.

  8. (4 points) The followng term refers to one endpoint of a two-way communication link between two programs running on the network. This endpoint is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.
    1. thread
    2. listener
    3. socket
    4. adapter

  9. (4 points) Which of the following Java synchronization techniques enforce happens-before relationships? Circle all valid answers.
    1. synchronized statements
    2. synchronized methods
    3. join
    4. atomic variables
    5. wait
    6. conditional critical regions

  10. (5 points) Which of the following characteristics common to functional languages have found their way into modern scripting languages, such as Python? Circle all correct answers. There are 5 correct answers:

    1. garbage collection
    2. prototype-instance model for objects rather than a class-instance model
    3. ability to create functions at run-time using lambda expressions
    4. higher-order functions such as map and reduce
    5. powerful macro facilities
    6. regular expressions for performing pattern matching in strings
    7. dictionaries (i.e., hash tables) as a built-in language feature
    8. implicit, parametric polymorphism
    9. constructors for data structures, such as lists, that allow a programmer to initialize a structure "all at once".
    10. side-effect free execution as a general way of programming

  11. (3 points) What are the advantages of using an appropriate Java thread pool? Circle all correct answers. There are three correct answers.
    1. Allow an application to degrade gracefully if a large number of thread requests are received simultaneously
    2. Allow the programmer to assign competing threads to separate pools and hence avoid race conditions
    3. Reduce the overhead of constantly allocating and deallocating thread objects.
    4. Increase concurrency by subdividing tasks until the amount of work they perform falls under a threshold and allowing the thread pool to concurrently schedule these tasks.
    5. Allow programmers to explicitly designate cores that should be used to execute different threads
    6. Prevent deadlock by removing a blocked thread from one pool and moving it to another pool where the lock may be available.

  12. (4 points) Suppose you are given the following Scheme function:
    (define mystery
      (lambda (L)
        (cond ((null? L) '())
              ((null? (cdr L)) (car L))
              (#t (let ((result (mystery (cdr L))))
                   (if (< (car L) result)
                       (car L)
                       result)))))))
    
    What is the value returned by:
    (mystery '(3 8 10 2 8 5))
    
  13. (4 points) What is the output of the following Python function call?
    map(lambda x,y: x + y, [3, 6, 8, 10], [4, 9, 1, 8])
    
    1. [7, 15, 9, 18]
    2. [3, 6, 1, 8]
    3. [3, 6, 8, 10, 4, 9, 1, 8]
    4. [27, 22]
    5. 27
    6. 22
    7. 49

  14. (5 points) Suppose I have 3 buttons, b1, b2, and b3. I want them to be grouped together with 20 pixels between b1 and b2 and 20 pixels between b2 and b3. I want the whole group of 3 buttons pushed against the right side of the window and to stay attached to the right side of the window if the window is resized. The figure below gives an example of how the buttons might look after the window has been resized:

    Assuming that buttonGroup is a horizontal box object, how would you assign the buttons and filler objects to buttonGroup to achieve the desired layout?

    1. buttonGroup.add(new RigidArea(new Dimension(INFINITY, 0)));
      buttonGroup.add(b1);
      buttonGroup.add(new RigidArea(new Dimension(20, 0)));
      buttonGroup.add(b2);
      buttonGroup.add(new RigidArea(new Dimension(20, 0)));
      buttonGroup.add(b3);
      
    2. buttonGroup.add(Box.createHorizontalGlue());
      buttonGroup.add(b1);
      buttonGroup.add(Box.createRigidArea(new Dimension(20, 0)));
      buttonGroup.add(b2);
      buttonGroup.add(Box.createRigidArea(new Dimension(20, 0)));
      buttonGroup.add(b3);
      
    3. buttonGroup.add(new horizontalGlue(), b1, 20, b2, 20, b3);
      
    4. buttonGroup.add(Box.createRigidArea(new Dimension(0, 0)));
      buttonGroup.add(b1);
      buttonGroup.add(Box.createHorizontalGlue(20));
      buttonGroup.add(b2);
      buttonGroup.add(Box.createHorizontalGlue(20));
      buttonGroup.add(b3);
      
    5. buttonGroup.add(Box.createHorizontalGlue());
      buttonGroup.add(b1);
      buttonGroup.add(Box.createHorizontalGap(20));
      buttonGroup.add(b2);
      buttonGroup.add(Box.createHorizontalGap(20));
      buttonGroup.add(b3);
      

  15. Model-View-Controller (MVC) model (10 points): An intern has created the following GUI that shows candidates' vote totals and allows a person to vote for a candidate:

    Below is a Java pseudo-code representation of the Java code that the intern created for displaying and updating the results of an election:

    class ElectionResults extends JPanel {
        int candidateVoteTotal = new int[4];
        JFrame window = new JFrame();
        
        ElectionResults() {
            initializeView();
            pack and make window visible
        }
    
        void addToCandidate(int candidate) {
            candidateVoteTotal[candidate]++;
            repaint();
        }
    
        void initializeView() {
            window.getContentPane().add(this);
            for each candidate {
                 create a JButton labeled vote
                 create a JLabel with the candidate's name
                 create a JLabel that display's the candidate's
                     total votes
                 add an event handler to the JButton that
                     1) calls addToCandidate with the appropriate index
                     2) updates the candidate's total vote JLabel
                     3) calls repaint
            }
        }
    }
    
    This code obviously does not conform to the MVC format. Assume that:

    Which of the following actions should you take to transform the code so that it meets the MVC format. Circle all answers that apply (if an answer has some valid and some invalid actions in it, do not circle it). There are 5 correct answers.
    1. Move the candidateVoteTotal array and the addToCandidate methods to a new model class. Remove the repaint() call from the addToCandidate method and add code to the addToCandidate method that notifies each view of the change to the candidate vote totals.
    2. Move the candidateVoteTotal array and the addToCandidate methods to a new model class and don't modify the addToCandidate method in any way.
    3. Move the view and event handling code to a new view class, but do not change any of the event handling code and do not add any additional methods to the view class.
    4. Create an interface that each view implements and that allows the model class to notify each view of changes to a candidate's vote.
    5. Keep the candidateVoteTotal array and the addToCandidate methods in ElectionResults. Remove the repaint() call from the addToCandidate method and add code to the addToCandidate method that notifies each view of the change to the candidate vote totals.
    6. Keep the view and event handling code in ElectionResults and don't modify any of it.
    7. Keep the view and event handling code in ElectionResults but 1) create a method that the model can call to notify the view of any changes, and 2) move the code that updates the JLabel representing the candidate's total votes and that calls repaint() (actions 2 and 3) from the event handling code to this new method.
    8. Add code to the constructor for ElectionResults that creates an instance of the new model class, an instance of the new view class (creating the instance will replace the call to initializeView()), and ties the two classes together. The constructor will continue to pack the window and make it visible.
    9. Move the code in the constructor for ElectionResults to the constructor for the new model class so that the new model class creates the instance of the view and packs and makes the window visible. The constructor for ElectionResults should be changed so that all it does is create an instance of the model and then returns.
    10. Move the view and event handling code to a new view class, and 1) create a method that the model can call to notify the view of any changes, and 2) move the code that updates the JLabel representing the candidate's total votes and that calls repaint() (actions 2 and 3) from the event handling code to this new method.
    11. Move the view and event handling code to a new view class and modify the first action in the event handling code so that it notifies any other views of changes to one of the candidate's vote totals. Don't modify either actions 2 or 3 in the event handling code. Finally, add methods to the new view class that allows new views to register and de-register themselves with the view.
    12. Add methods to the new model class that allows views to register and de-register themselves with the model.
    13. Add methods to the ElectionResults class that allows new views to register and de-register themselves with the ElectionResults class.
    14. Create an interface that the model implements and that allows the event handling code to notify the model of changes to a candidate's vote.

  16. (6 points) Suppose you wanted to write a Scheme function to reverse the elements of a list. For example
    (reverseList '(3 8 5 2 7))
    
    should return
    (7 2 5 8 3) 
    
    Which of the following functions would correctly perform this task? Circle all answers that apply:
    1. (define reverseList (lambda (L)
      		  (letrec ((reverseHelper (lambda (L reversedList)
      			    (cond
      			     ((null? L) reversedList)
      			     (#t (reverseHelper (cdr L) 
      						(cons (car L) reversedList)))))))
      		    (reverseHelper L '()))))
      
    2. (define reverseList (lambda (L)
      		  (cond
      		     ((null? L) '())
      		     (#t (cons (cdr L) (car L))))))
      
    3. (define reverseList (lambda (L)
      		      (cond 
      		       ((null? L) '())
      		       (#t (append (reverseList (cdr L)) (list (car L)))))))
      
    4. (define reverseList (lambda (L)
        (letrec ((reverseHelper 
                   (lambda (L reversedList)
      	        (cond
      		 ((null? L) reversedList)
      		  (#t (reverseHelper (cdr L) (car L)))))))
           (reverseHelper L '()))))
      

  17. (6 points--Java Concurrency) Consider the following Java class definition:
    public class BadThreads {
        static final int maxTasks = 5;    // the maximum number of tasks that may
                                          // be waiting for execution
        int tasksQueue[] = new int[maxTasks];  // holds the queued tasks, and more specifically the
                                          // number of milliseconds required to
                                          // execute the task
        int taskFront = 0;         // the index of the front of the task queue (i.e.,
                                   // the index of the next task to execute)
        int taskEnd = 0;           // the index of the back of the task queue (i.e.,
                                   // the index of the next empty spot in the task queue)
        int waitingTasks = 0;      // the number of queued tasks waiting to execute
    
        class Worker extends Thread {
            public void run() {
    	    try {
    		while (true) {
    		    int taskId = taskFront;
    		    int taskTime = tasksQueue[taskFront];
    		    taskFront = (taskFront + 1) % maxTasks;
    		    waitingTasks--;
    		    Thread.sleep(taskTime);
    		}
    	    } catch (InterruptedException e) {}
            }
        }
    
        class Scheduler extends Thread {
            public void run() {
    	    try {
    		while (true) {
    		    int taskTime = ThreadLocalRandom.current().nextInt(5, 10000);
    		    tasksQueue[taskEnd] = taskTime;
    		    taskEnd = (taskEnd + 1) % maxTasks;
    		    waitingTasks++;
    		    Thread.sleep(ThreadLocalRandom.current().nextInt(300, 2000));
    		}
    	    } catch (InterruptedException e) {}
    	}
        }
    
        public BadThreads() {
            Worker workers[] = new Worker[3];
            int i;
            for (i = 0; i < 3; i++) {
    	    workers[i] = new Worker();
                workers[i].start();
            }
            Scheduler s = new Scheduler();
    	s.start();
        }
    
        public static void main(String args[]) {
            new BadThreads();
        }
    }
    
    The tasksQueue is a wrap-around queue that can hold up to 5 tasks. The application spawns three Worker threads which execute infinite loops that remove tasks from the tasksQueue array and "execute" the task by sleeping for the indicated amount of time. It does not matter which Worker thread gets which task. The application also spawns a single Scheduler thread that executes an infinite loop that generates tasks with execution times of between 5 and 10000 milliseconds and adds the tasks to the tasksQueue. The Scheduler thread sleeps for a random interval between 300 and 2000 milliseconds after adding each task.

    There are three major bugs in this code. Circle the three choices from the following list that correctly describe these bugs.

    1. The Scheduler thread never yields to the Worker threads
    2. The Worker threads do not wait on the Scheduler thread if the tasksQueue is empty and hence might try to remove a task from an empty tasksQueue
    3. The Scheduler thread may get into a race condition trying to get a random number.
    4. The Scheduler thread does not wait on the Worker threads if the tasksQueue is full and hence could try to add a task to a full tasksQueue.
    5. The Worker threads could deadlock by both claiming a task and then trying to defer to the other thread that has claimed the task
    6. The Worker threads could livelock by waiting for each other to take a task from the tasksQueue
    7. The Worker threads can get into race conditions with each other as they update the information associated with the tasksQueue and the Scheduler thread can also get into a race condition with any of the Worker threads over the same information.
    8. the Worker threads and Scheduler thread could deadlock by blocking each other from using the tasksQueue.

  18. (15 points) Write a Python function that:
    1. takes a list of (voter, candidate) tuples as a parameter
    2. tabulates the vote for each candidate.
    3. prints out the candidates in descending order by vote count. If two candidates tie, you can print them out in any order. For each candidate print the candidate's name, a space, and the number of votes they received.
    Do not let a voter vote for more than one candidate. In other words, the first time you see a voter you should have the function record that voter's vote. If you encounter the voter later in the list, then ignore the voter's vote. For example, if your input were:
    [('nels', 'smiley'), ('brad', 'wolf'), ('nels', 'wolf'), ('sue', 'smiley')]
    
    then your output would be:
    smiley 2
    wolf 1
    
    Note that nels tried to vote twice and that his second vote was ignored.

    If your input list were instead:

    [('nels', 'smiley'), ('brad', 'wolf'), ('nels', 'wolf'), 
     ('sue', 'smiley'), ('sarah', 'huck'), ('mindy', 'smiley')]
    
    then your output would be:
    smiley 3
    wolf 1
    huck 1
    
    It would be fine if the order of wolf and huck were reversed.