EECS1030Z Test 5

Wednesday April 2, 2015, 14:30-15:45
Lab 01
Version H


package test5;

import java.util.List;

public class Test5H {
  
  private Test5H() {
    // prevent instantiation
  }

  /**
   * Returns the string made up of the characters in s starting
   * from index idx and going to the end of s. For
   * example,
   * 
   * Test5H.endOf("abcdef", 0) returns "abcdef"
   * Test5H.endOf("abcdef", 1) returns "bcdef"
   * Test5H.endOf("abcdef", 2) returns "cdef"
   * Test5H.endOf("abcdef", 3) returns "def"
   * 
   * An empty string is returned if idx is greater than or equal to
   * the length of s.
   * 
   * @param s
   *          a string
   * @param idx
   *          the starting index in s
   * @pre. idx >= 0
   * @return the string made up of the characters in s starting from index idx
   *         and going to the end of s
   */
  public static String endOf(String s, int idx) {
    String result = "";
    if (idx >= s.length()) {
      result = "";
    } else {
      result = s.charAt(idx) + Test5H.endOf(s, idx + 1);
    }
    return result;
  }

  /**
   * Returns the sum of the elements in t ignoring elements that
   * are null. For example, if t is the list
   * [null, 2, 3, null, 5] then sumIgnoreNull(t)
   * returns 10.
   * 
   * The value 0 is returned if t is empty,
   * or if all elements of t are null. 
   * 
   * @param t
   *          the list to sum (some elements in t might be null)
   * @return the sum of the elements in t ignoring null values
   */
  public static int sumIgnoreNull(List<Integer> t) {
    int sum = 0;
    if (t.isEmpty()) {
      sum = 0;
    } 
    else {
      Integer first = t.get(0);
      if (first != null) {
        sum += first;
      }
      sum += Test5H.sumIgnoreNull(t.subList(1, t.size()));
    }
    return sum;
  }

}


Other questions

Consider the following method:
  /**
   * Returns the string made up of the characters of s
   * in reverse order.
   * 
   * @param s a string
   * @return the string made up of the characters of s in reverse order
   */
  public static String reverse(String s) {
    String rev = "";
    if (s.length() < 2) {
      rev = s;
    } 
    else {
      int lastIndex = s.length() - 1;
      char lastChar = s.charAt(lastIndex);
      String sMinusLast = s.substring(0, lastIndex);
      rev = lastChar + X.reverse(sMinusLast);
    }
    return rev;
  }
Question 1

Prove the above method correct.



Question 2

Prove that the above method terminates.



Question 3

Give the recurrence relation of the above method.



Question 4

Let f : ℕ → ℕ be defined by f(n) = n / 2 + sqrt(n),
where sqrt(n) is the square root of n. Then f ∈ O().



Question 5

Prove your answer to Question 4. You must state reasonable values of M and m (or F and M if you are using the notation from the notes) and then prove that the appropriate inequality is true.