Ballot.java


Below is the syntax highlighted version of Ballot.java.


/***********************************************************************
  * Name: COS 126 Staff
  * NetID: cos126
  * Precept: P99
  * 
  * Ballot: represent a preferential ballot for RIRV
  * 
  * Dependencies: none
  * 
  * Note: there are MANY possible correct solutions! This is just one of them.
  */
public class Ballot {
    
    // an array of all remaining candidates from favorite to least
    // it might have extra unused space at the end
    private String[] remaining; 
    
    // number of remaining candidates
    private int n; 
    
    // make preferential ballot (order: favorite to least)
    public Ballot(String[] prefs) { 
        n = prefs.length;
        
        // make a defensive copy
        remaining = new String[n];
        for (int i = 0; i < n; i++)
            remaining[i] = prefs[i];
    }
    
    // convert to String
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++)
            // append > and name
            sb.append(" > " + remaining[i]); 
        
        // cut off the initial " > "
        return sb.substring(3);
    }
    
    // which remaining candidate is our favorite?
    public String top() {
        // most preferred at start
        return remaining[0]; 
    }
    
    // which remaining candidate is our least favorite?
    public String bottom() {
        // least preferred at end
        return remaining[n-1]; 
    }   
    
    // remove this candidate from this ballot
    public void cut(String candidate) {
        // pass through array, looking for our desired candidate
        for (int i = 0; i < n; i++) {
            if (remaining[i].equals(candidate)) {
                // found them! reduce n; bump everyone after closer to favorite
                n--;
                for (int j = i; j < n; j++)
                    remaining[j] = remaining[j+1];
                // job's done
                return; 
            }
        }
        
        // we never found a match
        throw new RuntimeException("Couldn't find " + candidate);
    }
    
    public static void main(String[] args) {
        String[] testPrefs = {"Doug", "Nanxi", "Bebe", "Aleksey"};
        Ballot b = new Ballot(testPrefs);
        System.out.println(b); // toString(): "Doug > Nanxi > Bebe > Aleksey"
        
        System.out.println(b.top()); // gives "Doug"
        System.out.println(b.bottom()); // gives "Aleksey"
        
        b.cut("Doug");
        System.out.println(b); // gives "Nanxi > Bebe > Aleksey"
        System.out.println(b.top()); // "Nanxi" - change from original top()
        
        b.cut("Bebe");
        System.out.println(b); // gives "Nanxi > Aleksey"
        
        b.cut("Bebe"); // throws a RuntimeException
    }
}