CS100M --> Question(s) of the Week --> Questions of Previous Weeks

Back to Question of this week

12:   1-d array, introduction to inheritance
Given v, a 1-d array of integers, reverse the order of values in v in-place.
Create w, a 1-d array of Intervals using random values in the range of 3 to 8 (floating point numbers). Reverse w in-place. The header for the constructor of Interval is
    public Interval(double base, double range)
Consider the class Vehicle below. With minimal work, create a class Car such that Car objects will have fields numWheels (number of wheels), id, and gpm. A Car object should also have instance method mpg() for calculating the miles per gallon. Write client code to create a Car object and calculate its fuel efficiency.
   class Vehicle {

       protected int id;          //vehicle id
       protected double gpm;      //gallons per mile

       public Vehicle(int id, int g) {
           this.id= id;
           gpm= g;
       }

       //Calculate miles per gallon
       public double mpg() { return 1/gpm; }
   }


11:   More OOP, 1-d array
Consider class Person discussed during the 4/8 lecture. We will modify the class and write client code.
  1. Suppose we (or the client) want to keep track of how many Person objects are created. Can we write some code in class Person to faciliate the counting?
  2. Modify toString method to also print the friend's name, but only if the Person has a friend.
  3. Write a method isFOMF, i.e., is-friend-of-my-friend. Method isFOMF takes one Person p as input argument and evaluates whether p is the friend of the current object's friend. Return a boolean value.
  4. Write client code to create the following "social circle":
    • Pat calls Les a friend (or you can say Pat has friend Les)
    • Jo calls Les a friend
    • Les calls Max a friend
    • Max has no friend
    Remember that our friend property is directional--Pat calls Les a friend does NOT mean Les calls Pat a friend.
    Write more code to perform the following checks:
    • "Pat wants to know if Max is the friend of her friend."
    • "Les wants to know if Jo is the firend of her friend."



Let v be a 1-d array of integers. Reverse v.


10:   Objects and classes
Consider class Interval developed during lecture from 3/27 to 4/3. We will improve the class definition and write client code.
  1. A proper Interval has left and right end values such that the range (width) is a positive number. For example, an improperly specified interval with a base of 9 and a range of -6 is really the proper Interval with base 3 and range 6. Re-write part of class Interval so that improperly entered interval values will still create proper Intervals.
  2. Overloading:   write an instance method overlap.
  3. Write "client code" to instantiate three Intervals. Call them i1 through i3. Assume the three Intervals overlap. Write more client code to find the overlapped Interval.
  4. What if you don't know beforehand whether the three Intervals overlap? Write code to find the overlapped Interval or display "no overlap" if the three Intervals don't overlap.


9:   Loops, Introduction to objects and classes
Write a code segment to draw a hollow triangle of stars given n, the number of lines of the figure. For example, if n is 5, the following triangle should be printed:
        *
        **
        * *
        *  *
        *****
Consider the classes Account and Bank below. Draw diagrams to trace the execution of the program.
        class Account {
          // variables
          private double bal;   // balance
          private int id;       // account number

          // getter and setters
          public void setID(int num)  { id = num; }
          public void setBal(double d)  { bal = d; }
          public int getID()  { return id; }
          public int getBal()  { return bal; }

          // method to deposit money into account
          public void deposit(double d)  { bal += d; }
        }

        public class Bank {
          public static void main(String[] args)  {
            Account a1;
            a1 = new Account();
            a1.setID(2234);
            a1.deposit(100.25);
            double x = a1.getBal();
            System.out.println(x);
            System.out.println(a1.getBal());
          }
        }


7:   Characters and strings, simulation
A DNA sequence is a double helix formed by two strands of bases "twisted together." The four bases are Adenine, Cytosine, Guanine, and Thymine. We will treat a strand as a string from an alphabet of four characters: A, C, G, and T.    A and C are complementary, and G and T are complementary. That means if one strand is
                              AGTAGCAT
the complementary strand must be
                              TCATCGTA
Write a function rComplement that takes a string as input and returns the complementary string in reverse order.



Approximate the value of pi by "throwing darts" randomly on a square dartboard and then counting the number of darts that land inside the largest circle that can be inscribed in the square.
  • Let N, the number of darts, represent the area of the square:   N = L^2
  • N_in is the number of darts that land inside the circle:   N_in = pi (L^2) / 4
  • Re-arranging the two equations gives   pi = 4  N_in / N



6:   More arrays, vectorized code
Compute the first n lines of Pascal's triangle. Pascal's triangle, for n=3, is shown on the right. Store the triangle in an n-by-n matrix with ones in the first column of all rows. (All rows except the last will be "padded" with zeros.)

        1
      1   1
    1   2   1

Given a vector v, determine whether its values are strictly increasing: (a) using a loop, (b) using vectorized code--no loop.



5:   User-defined functions, matrices
Write a function hms2s that converts a time expressed in hours, minutes, seconds to a time expressed in seconds. Function hms2s returns one variable seconds and takes three input arguments: hours (h), minutes (m), and seconds (s).


Write a function s2hms that performs the opposite operation. Function s2hms takes one input argument seconds and returns three variables: h, m, and s.


Write a function that reverses the order of the rows in a matrix. The function takes one matrix as input and returns a re-ordered matrix.


4:   Iteration with for loop, nesting loops
How many ways can you stack three CDs (say red, blue, and green) on a shelf? Write a program segment to calculate how many different ways there are to stack your collection of n CDs. Do not use MATLAB predefined functions.


Given a vector v, write a program segment to calculate the pair sums. For example,
                     v = [ 2 4 3 1 1]
        pair sums of v =   [ 6 7 4 2]
How about the triple sums? For example,
                     v = [ 2 4 3 1 1]
      triple sums of v =     [ 9 8 5]
How about "n sums" where n is less than the length of vector v? Use for loops and do not use the MATLAB predefined function sum.


3:   Iteration with while loop, Vectors
Eeeeeeeee...   Functions often can be approximated by infinite series. The approximation becomes better as more terms are added in the series. The exponential function ex can be approximated by the series

The notation n! represents the factorial of number n, n!=1*2*3...*n, 0!=1. The MATLAB function factorial performs this computation.

Use the MATLAB function exp to calculate the "true" value of ex for a given value of x. The difference between the true and approximated values is the approximation error. The tolerance is the amount of error that we are willing to accept. Usually, we are willing to accept this error due to practical limitations on computing time or memory. The smaller the tolerance we choose, the more accurate the approximation becomes.

Write a program that uses the series shown above to approximate e0.5. The program should start by approximating e0.5 with just the first term of the series and add the additional terms one by one until a tolerance of 0.001 is satisfied. The program should show one line of output for each additional term used. This line of output should display the number of terms used, the approximated value of e0.5, and the approximation error. Below is an example of what the first few lines of output may look like:

No. of Terms    Approximation    Error
1               1.000000         0.648721
2               1.500000         0.148721

Write a program segment to evaluate an nth order polynomial of x:   a0 + a1x + a2x2 + ... + anxn. A given vector p has length n + 1 and contains the coefficients of the polynomial where p(1) is the coefficient of the term x0. Your program should request a user input value for variable x and then evaluate the polynomial. Use a while loop.


2: Branching
In lecture, we wrote the following program segment to find the minimum value of the quadratic function q(x)=x^2+bx+c in the interval [L,R]. Write a different program segment to find the minimum function value. In particular, consider the critical point, xc, relative to L and R. Is xc in, left of, or right or [L,R]?
% Find min of q(x)=x*x+bx+c
% given b,c,L,R
xc= -b/2;   % x where q'(x)=0
if (L<=xc & xc<=R)
   qMin= -b*b/4+c;     % q(xc)
else
   qL= L*L + b*L + c;  % q(L)
   qR= R*R + b*R + c;  % q(R)
   if (qL < qR)
      qMin= qL;
   else
      qMin= qR;
   end
end
According to the rules of the Gregorian calendar, a year is a leap year if it is divisible by four except for century years that are not divisible by 400. Write a program to determine whether a user input year is a leap year.


1: Algorithms
What does the "program" on the left compute? Can you explain the algorithm? How is the program on the right different?
a= 9
x0= a
x1= (x0 + a/x0)/2
x2= (x1 + a/x1)/2
x3= (x2 + a/x2)/2
.
:
a= 9
x= a
x= (x + a/x)/2
x= (x + a/x)/2
x= (x + a/x)/2
.
:
What problem does the following algorithm solve? Use integer division. E.g., 35/10 gives 3 as the quotient and 5 as the remainder. Try a couple examples, say (A,B) is (10,35) or (19,67).
  1. Given two integers, call the smaller of the two A and the other one B.
  2. Divide A into B.
  3. Take the remainder and call it R.
  4. If R is 0, then we're done, and A is the answer.
  5. Otherwise, R is not 0, then set B=A and A=R and start over at step 2.