CS131 Module 5: Solutions to Practice Problems

Ask if you are surprised by any of these answers.
  1. Widget w = t1.unload();
    w = m.transform(w);
    t2.load(w)
    
    or, alternatively:
    t2.load(m.transform(t1.unload()));
    

  2. Widget w = t1.unload();
    if (w.isDefective())
       t2.load(m.transform(w));
    else
       t2.load(w);
    

  3. while (!t1.isEmpty() && !t2.isFull())
       t2.load(t1.unload());
    

  4. while (!t1.isEmpty()) {
       Widget w = t1.unload();
       if (w.getWeight() + t2.getTotalWidgetWeight() <= 1000)
          t2.load(w);
    }
    

  5. m3.transform(m2.transform(m1.transform(w)));
    

  6. while (!t1.isEmpty()) {
       Widget w = t1.unload();
       if (w.isDefective())
          defectiveWidgets.load(w);
       else if (w.getWeight() < 50)
          lightWidgets.load(w);
       else
          heavyWidgets.load(w);
    }
    

  7. for (int i = 0; i < 100; i++)
       (new Truck()).load(new Widget());
    

  8. Truck t2 = new Truck();
    Truck t3 = new Truck();
    moveAll(t1, t2);  // t2 will have them in reverse order
    moveAll(t2, t3);  // t3 will have them in the original order
    moveAll(t3, t1);  // t1 will have them in reverse order
    
    void moveAll(Truck a, Truck b) {
       while (!a.isEmpty())
          b.load(a.unload());
    }
    

  9. boolean done = false;
    while (!done) {
       if (m1.isBroken || w.isDefective())
          done = true;
       else {
          w = m1.transform(w);
          if (m2.isBroken() || w.isDefective())
             done = true;
          else
             w = m2.transform(w);
       }
    }
    

  10. while (!t1.isEmpty()) {
       w = t1.unload();
       while (w.isDefective())
          w = m.transform(w);
       t2.load(w);
    }
    

  11. (for the test-driven development optional extension) Answers may vary, but the test must force the developer implementation in each row. That is, the developer should not assume semantics beyond those required by the tests. The goal of the developer is to provide the simplest implementation that will pass the tests.

    TesterDeveloper
    @Test
    public void testFoo() {
       Widget w = new Widget();
       assertEquals(0, w.foo(7));
    }
    
    public class Widget {
       public int foo(int n) {
          return 0;
       }
    }
    
    @Test
    public void testFoo() {
       Widget w = new Widget();
       assertEquals(0, w.foo(7));
       assertEquals(7, w.foo(3));
    }
    
    public class Widget {
       int v = 0;
       public int foo(int n) {
          int old = v;
          v = n;
          return old;
       }
    }
    
    @Test
    public void testFoo() {
       Widget w = new Widget();
       assertEquals(0, w.foo(7));
       assertEquals(7, w.foo(3));
       assertEquals(7, w.foo(10));
    }
    
    
    public class Widget {
       int v = 0;
       public int foo(int n) {
          int old = v;
          v = Math.max(v,n);
          return old;
       }
    }