CMSI 386
Quiz 1

The test is open-everything with the sole limitation that you neither solicit nor give help while the exam is in progress.

Submit all answers on these exam sheets. No extra sheets are allowed. If you are nervous about this, work out the problem on a separate sheet and copy your answers here. Work quickly but carefully. I don't suspect many people will finish all the problems; the intent is to make sure the people most familiar with the material get the best grades.

ProblemYou gotOut of
1
 
20
2
 
20
3
 
20
4
 
20
5
 
20
TOTAL
 
100
  1. Write a Ruby class called Account, representing a kind of bank account with an account number that never changes once constructed, and an account balance which can be read and written. All writes cause, as a side effect, a message to be written to standard output. Also all writes that would make the balance negative are prohibited. Example:
        a = Account.new(14)
        a.id                 returns      14
        a.balance            returns       0
        a.balance = 100      prints "depsited 100 to account 14", returns 100
        a.balance = 20       prints "withdrew 80 from account 14", returns 20
        a.balance = -20      prints "overdrafts not allowed", returns -20
        a.balance            returns       20
    
  2. Repeat the previous problem, using JavaScript. Instead of a class, you will have a constructor function and will get and set the account balance with functions defined in the constructor's prototype.
  3. Consider this script:
        var a = [];
        for (var i = 0; i < 10; i++) {
            a[i] = function() {return i;}
        }
        var b = [];
        for (var j = 0; j < 10; j++) {
            b[j] = a[j]();
        }
    

    At the end of this script, what is the value of b? Explain in detail why this is. A sketch will be very helpful and improve your chances of getting full credit. Running the script and simply reporting the value of b is worth only 2 points out of 20, so make sure you can explain the value.

  4. Write, in Ruby, a method that takes in a function f and a list [a0, a1, ..., an-1] and returns the list [a0, f(a1), f(f(a2)), f(f(f(a3))), ...].

    For example, if you pass as arguments the function that doubles its inputs, and the list [4, 3, 1, 2, 2], then the return value would be [4, 6, 4, 16, 32].

    Hints: Do the f(f(f...)) as a separate function. Also you do NOT have to make your function tail recursive.

  5. Repeat the previous problem in JavaScript. You can implement your solution with a global function.