Monday, April 16, 2012

Test 3

Here are the two tests, with some sample solutions.
  1. (25%) What does the following program print out when run?
    public class Q1 {
    public static boolean swing (int strength) throws Exception{
           
    if (strength < 5)
               
    throw new Exception("Too weak");
           
    if (strength > 10)
               
    return false;
           
    return true;
       
    }
    public static void main(String[] args)  {
           
    int[] strengths = {5,6,-1,12};
           
    for (int s : strengths) {
               
    try {
                   
    if (swing(s))
                       
    System.out.println("Homerun");
                   
    else
                       
    System.out.println("Strike!");
               
    } catch (RuntimeException e){
                   
    System.out.println("You are OUT!");
               
    } catch (Exception e) {
                   
    System.out.println(e.getMessage());
               
    }
           
    }
           
    System.out.println("Done.");
       
    }
    }

  2. (25%)Given a text file called sales.txt which contains data that looks like
    aba 55.99
    akdkd8dj 12.95
    iwjwhe 4
    Iji8keJl 44.99
    ijdddawe 10.00
    ...and so on for many more rows...
    
    where each row represents one item that is for sale in a store. The first column is a String that uniquely identifies the item and the second column is a double that represents the price of the item. Write a program which


    1. Implements a simple Item class that can represent one item.
    2. In the main, your program reads the complete contents of the file sales.txt into an ArrayList<Item> variable called items.
    Answer:
    public class Item {
       
    private String sku;

       
    private double price;

       
    public Item(String sku, double price){
           
    this.sku = sku;
           
    this.price = price;
       
    }

       
    public String toString(){
           
    return sku + " " + price;
       
    }
       
    public static void main(String[] args) {
           
    try {
               
    Scanner in = new Scanner(new FileInputStream("sales.txt"));
               
    ArrayList<Item> items = new ArrayList<Item>();
               
    while (in.hasNext()){
                   
    String sku = in.next();
                   
    double price = in.nextDouble();
                    items
    .add(new Item(sku,price));
               
    }
               
    System.out.println(items);
           
    } catch (FileNotFoundException e) {
                e
    .printStackTrace();
           
    }
       
    }
    }
  3. (25%) Read over the code below and implement the empty method.
    import java.util.ArrayList;

    public class Q3 {

       
    private ArrayList<Q3> data;

       
    private Integer number;

       
    public Q3(Integer number){
            data
    = new ArrayList<Q3>();
           
    this.number = number;
       
    }

       
    public void add(Q3 q){
            data
    .add(q);
       
    }

       
    public void add(Integer number){
            data
    .add(new Q3(number));
       
    }
       

       
    /**
         * Calculates and returns the sum of all even numbers in
         * this object or in any of the ones in 'data', and so on
         * recursively.
         * @return The sum.
         */

       
    public int sumEven(){
           
    //TODO: implement this method
           
    int result = 0;
           
    if (number % 2 == 0)
                result
    = number;
           
    for (Q3 q: data){
                result
    += q.sumEven();
           
    }
           
    return result;

       
    }
       


       
    public static void main(String[] args) {
            Q3 q
    = new Q3(0);
            Q3 first
    = new Q3(1);
            q
    .add(first);
            Q3 second
    = new Q3(2);
            q
    .add(second);
            q
    .add(3);
            q
    .add(4);
            first
    .add(8);
            second
    .add(5);
           
    System.out.println(q.sumEven());

       
    }
    }
    For example, when the main above is run it should print out
    14
  4. (25%) Implement a method String mostFrequent(String s) which returns the 3-character substring that appears most frequently in s, or one of the most frequent if there is a tie. For example
    mostFrequent("AABABA") returns "ABA" because "ABA" appears twice
    mostFrequent("AAAAAB") returns "AAA" because it appears 3 times
    mostFrequent("ATATATA") returns "ATA" because it appears 3 times
                
    Answer:
    public static String mostFrequent(String seq){
           
    HashMap<String, Integer> count = new HashMap<String, Integer>();
           
    int max = 0;
           
    String maxKey = null;
           
    //add them all
           
    for (int i = 0; i <= seq.length() - 3; i++) {
               
    String key = seq.substring(i,i+3);
               
    if (count.containsKey(key))
                    count
    .put(key, count.get(key) + 1);
               
    else
                    count
    .put(key, 1);
               
    if (count.get(key) > max){
                    max
    = count.get(key);
                    maxKey
    = key;
               
    }
           
    }
           
    return maxKey;
       
    }



And, the other one:


  1. (25%) What does the following program print out when run?

    public class Q1 {
    public static boolean pitch (String type) throws Exception {
           
    if (type.startsWith("f"))
               
    return true;
           
    if (type.startsWith("c"))
               
    return false;
           
    if (type.startsWith("x"))
               
    throw new Exception("Oops");
           
    return true;
       
    }
    public static void main(String[] args)  {
           
    String[] types = {"fast", "foo", "curve", "xoom"};
           
    for (String t : types) {
               
    try {
                   
    if (pitch(t))
                       
    System.out.println("Hit");
                   
    else
                       
    System.out.println("Miss");
               
    } catch (RuntimeException e){
                   
    System.out.println("You hit the umpire");
               
    }
               
    catch (Exception e) {
                   
    System.out.println(e.getMessage());
               
    }
           
    }
           
    System.out.println("Done.");

       
    }
    }

  2. (25%) Given a text file called points.txt which contains data that looks like
    1.44 5.666
    12.999 0
    9.163 3.1415
    6 7
    5 6.999
    ...and so on for many more rows...
    
    where each row represents the x and y coordinates of a point in 2-dimensional space. Both columns are doubles. Write a program which


    1. Implements a simple Point class that can represent one point in space.
    2. In the main, your program reads the complete contents of the file points.txt into an ArrayList<Point> variable called points.
    Answer:
    public class Point {

       
    private double x;
       
    private double y;
       
    public Point(double x, double y){
           
    this.x = x;
           
    this.y = y;
       
    }
       
    public String toString(){
           
    return "(" + x + "," + y + ")";
       
    }
       
    public static void main(String[] args) {
           
    try {
               
    Scanner in = new Scanner(new FileInputStream("points.txt"));
               
    ArrayList<Point> points = new ArrayList<Point>();
               
    while (in.hasNext()){
                   
    double x= in.nextDouble();
                   
    double y = in.nextDouble();
                    points
    .add(new Point(x,y));
               
    }
               
    System.out.println(points);
           
    } catch (FileNotFoundException e) {
                e
    .printStackTrace();
           
    }
       
    }
    }
  3. (25%) Read over the code below and implement the empty method.
    import java.util.ArrayList;

    public class Q3 {

       
    private ArrayList<Q3> data;

       
    private Integer number;

       
    public Q3(Integer number){
            data
    = new ArrayList<Q3>();
           
    this.number = number;
       
    }

       
    public void add(Q3 q){
            data
    .add(q);
       
    }

       
    public void add(Integer number){
            data
    .add(new Q3(number));
       
    }

       

       
    /**
         * Find if x is either equal to number, or equal to one of
         * the numbers in 'data', and so on recursively.
         * @param x the number we are looking for
         * @return true if x is there, false otherwise.
         */

       
    public boolean find(Integer x){
           
    //TODO: implement this method
           
    if (number == x)
               
    return true;
           
    for (Q3 q : data) {
               
    if (q.find(x))
                   
    return true;
           
    }
           
    return false;

       
    }


       
    public static void main(String[] args) {
            Q3 q
    = new Q3(0);
            Q3 first
    = new Q3(1);
            q
    .add(first);
            Q3 second
    = new Q3(2);
            q
    .add(second);
            q
    .add(3);
            q
    .add(4);
            first
    .add(8);
            second
    .add(5);
           
    System.out.println(q.find(3));
           
    System.out.println(q.find(5));
           
    System.out.println(q.find(10));

       
    }
    }
    For example, when the main above is run it should print
    out
    true
    true
    false
  4. (25%) Implement a method String mostPoints(String[] name, int[] points) which returns the name that has the most points, assuming that for all indeces i we have that points[i] has the number of points for name[i]. For example
       String[] name1 = {"a", "b", "c", "a", "b", "a"};
       
    int[] points1 =  { 1,   2,   7,   4 ,  3,   1};
       mostPoints
    (name1, points1); //returns "c" because it has 7
       
    // points and "a" has 6, and "b" has 5.

       
    String[] name2 = {"a", "b", "c", "a", "b", "a"};
       
    int[] points2 =  { 5,   2,   7,   4 ,  3,   1};
       mostPoints
    (name2, points2); //returns "a"

       
    String[] name3 = {"a", "a", "a", "a", "b", "c"};
       
    int[] points3 =  { 1,   1,   1,   1 ,  3,   2};
       mostPoints
    (name3, points3); //returns "a"
    Answer:
    public static String mostPoints(String[] name, int[] points){
           
    HashMap<String, Integer> count = new HashMap<String, Integer>();
           
    int max = 0;
           
    String maxKey = null;

           
    for (int i = 0; i < points.length; i++) {
               
    if (count.containsKey(name[i]))
                    count
    .put(name[i], points[i] + count.get(name[i]));
               
    else
                    count
    .put(name[i], points[i]);
               
    if (count.get(name[i]) > max){
                    max
    = count.get(name[i]);
                    maxKey
    = name[i];
               
    }
           
    }
           
    return maxKey;
       
    }

No comments: