teaching machines

CS 145 Lecture 36 – Blackboxes Cont’d

Agenda

  • what ?s
  • blackboxes cont’d
  • implementing ArrayList

TODO

  • Start homework 7. Due before December 14—unless you are pursuing the mercy bounty, in which it’s due before December 7.

Note

Today we keep exploring objects from the outside in with a few more blackboxes:

If we have time, we’ll also crack open the blackbox that is ArrayList and write our own!

Code

TickTickTick.java

package lecture1130;

public class TickTickTick {
  private int target;
  private int count;

  public TickTickTick(int target) {
    this.target = target;
    count = target;
  }

  public boolean click() {
    --count;
    return count <= 0;
  }
  
  public void reset() {
    count = target;
  }
  
  public static void main(String[] args) {
    TickTickTick ticker = new TickTickTick(3);
    for (int i = 0; i < 4; ++i) {
      System.out.println(ticker.click());
    }
    ticker.reset();
  }
}

Raffle.java

package lecture1130;

import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Random;

public class Raffle {
  private ArrayList<String> names;
  private Random generator;

  public Raffle() {
    names = new ArrayList<>();
    generator = new Random();
  }

  public void ticket(String name) {
    names.add(name);
  }

  public void ticket(String name,
                     int count) {
    for (int i = 0; i < count; ++i) {
      ticket(name);
    }
  }
  
  public String winner() {
    if (names.isEmpty()) {
      throw new NoSuchElementException();
    }
    
    int i = generator.nextInt(names.size());
    return names.remove(i);
  }
  
  public static void main(String[] args) {
    Raffle raffle = new Raffle();
    raffle.ticket("Jordan", 4);
    raffle.ticket("Logan");
    raffle.ticket("Ben");
    raffle.ticket("Louis");
    System.out.println(raffle.winner());
  }
}

Haiku

Life is a raffle
But can just anyone win?
Winners need tickets

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *