Tuesday, November 30, 2010

Lab 22 -- Some More Programs

If you are done with the execution and understanding of the LinkedList Program, try to pick any problem from this list of topcoder problems and implement it.

MagicSpell was already implemented in lecture. You can see answer under the "Sample Programs" link, as usual.

Lab 22 - LinkedList.java -- with Generics -- Fill in the Function Bodies


1) Remove the quotes. I had to put in order to get the E to print.
2) First Refer to the Book to Fill in the Similar Functions and then try yourself the non-similar ones 

import java.util.ArrayList;


public class LinkedList<"E extends Comparable"<"E">>

{

 private ListNode<"E"> head;


 public LinkedList()

 {

  head = null;

 }


 public void showList()

 {

 
 }


 public int length()

 {

 
 }


 public void addNodeToStart(E addData)
 {
 
 }

 public void deleteHeadNode()
 {


 }

 public boolean onList(E target)
 {
 
 }

 public ListNode<"E"> contains(E target)
 {
 

 }

 public void addNodeAfterN(E theData, int n)
 {
 

 }

 public void deleteAfterNodeN(int n)
 {
 

 }

 public ArrayList<"E"> toArrayList()
 {
 
 
 }

}

Lab 22 -- Driver.java -- Use this to Test


1) Remove the quotes round String and Record.

public class Driver {

 
 public static void main(String[] args) 
 {
  LinkedList<"String"> stringList = new LinkedList<"String">();
  stringList.addNodeToStart("Hello");
  stringList.addNodeToStart("Good-Bye");
  stringList.showList();
  
  System.out.println("Is 'Hello' present: " + stringList.onList("Hello"));
  System.out.println("Is 'Meeee' present: " + stringList.onList("Meeee"));
  
  System.out.println("Item Added:");
  stringList.addNodeAfterN("That Me First Time",1);
  stringList.showList();
  
  System.out.println("Item Added:");
  stringList.addNodeAfterN("That Me Second Time",2);
  stringList.showList();
  
  System.out.println("Item Added:");
  stringList.addNodeAfterN("That Me 3rd Time",4);
  stringList.showList();
  
  System.out.println("Item Deleted:");
  stringList.deleteAfterNodeN(3);
  stringList.showList();
  
  System.out.println("Item Deleted:");
  stringList.deleteAfterNodeN(3);
  stringList.showList();
  
  /* *********************************************** */
  
  System.out.println(" ************************************************* ");
  
  LinkedList<"Record"> RecordList = new LinkedList<"Record">();
  Record TomRecord = new Record("Tom", 12);
  RecordList.addNodeToStart(TomRecord);
  
  Record HarryRecord = new Record("Harry", 23);
  RecordList.addNodeToStart(HarryRecord);
  RecordList.showList();
  
  Record MyRecord = new Record("Me", 14);
  System.out.println("Is 'TomRecord' present: " + RecordList.onList(TomRecord));
  System.out.println("Is 'MyRecord' present: " + RecordList.onList(MyRecord));
  
  Record Person1 = new Record("Person1", 12);
  System.out.println("Item Added:");
  RecordList.addNodeAfterN(Person1,1);
  RecordList.showList();
  
  Record Person2 = new Record("Person2", 30);
  System.out.println("Item Added:");
  RecordList.addNodeAfterN(Person2,2);
  RecordList.showList();
  
  Record Person3 = new Record("Person3", 33);
  System.out.println("Item Added:");
  RecordList.addNodeAfterN(Person3,4);
  RecordList.showList();
  
  System.out.println("Item Deleted:");
  RecordList.deleteAfterNodeN(3);
  RecordList.showList();
  
  System.out.println("Item Deleted:");
  RecordList.deleteAfterNodeN(3);
  RecordList.showList();
  
  
 }

}

Lab 22 -- ListNode


1) Remove quotes around E.

public class ListNode<"E"> 
{
 private E data;
 private ListNode<"E"> link;
 
 public ListNode()
 {
  link = null;
  data = null;
 }
 
 public ListNode(E newData, ListNode linkValue)
 {
  data = newData;
  link = linkValue;
 }

 public E getData() {
  return data;
 }

 public void setData(E data) {
  this.data = data;
 }

 public ListNode<"E"> getLink() {
  return link;
 }

 public void setLink(ListNode<"E"> link) {
  this.link = link;
 }
 
 
}

Lab 22 - Record Class


1) Remove quotes around Record

public class Record implements Comparable<"Record">
{
 private String name;
 private int age;
 
 public Record()
 {
  this.setName("");
  this.setAge(0);
 }
 
 public Record(String n, int a)
 {
  this.setName(n);
  this.setAge(a);
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }
 
 public int compareTo(Record that)
   {
     int returnValue;

     returnValue = 0;

     if(this.getName().compareTo(that.getName()) < 0)
     {
       returnValue = -1;
     }
     else if(this.getName().compareTo(that.getName()) > 0)
     {
       returnValue = +1;
     }
     else
     {
      if(this.getAge() < that.getAge())
       returnValue = -1;
      else if(this.getAge() > that.getAge())
       returnValue = +1;
      else
       returnValue = 0;
     }

     return returnValue;
   } 
 
 public String toString()
 {
  String s;
  s = String.format("Name: %s , Age: %d" , this.getName(), this.getAge());
  return s;
 }
 
 
}

Lab 22 - LinkedList with Generics -- Output


Good-Bye
Hello
Is 'Hello' present: true
Is 'Meeee' present: false
Item Added:
Good-Bye
That Me First Time
Hello
Item Added:
Good-Bye
That Me First Time
That Me Second Time
Hello
Item Added:
Good-Bye
That Me First Time
That Me Second Time
Hello
That Me 3rd Time
Item Deleted:
Good-Bye
That Me First Time
That Me Second Time
That Me 3rd Time
Item Deleted:
Good-Bye
That Me First Time
That Me Second Time
 ******************************************************** 
Name: Harry , Age: 23
Name: Tom , Age: 12
Is 'TomRecord' present: true
Is 'MyRecord' present: false
Item Added:
Name: Harry , Age: 23
Name: Person1 , Age: 12
Name: Tom , Age: 12
Item Added:
Name: Harry , Age: 23
Name: Person1 , Age: 12
Name: Person2 , Age: 30
Name: Tom , Age: 12
Item Added:
Name: Harry , Age: 23
Name: Person1 , Age: 12
Name: Person2 , Age: 30
Name: Tom , Age: 12
Name: Person3 , Age: 33
Item Deleted:
Name: Harry , Age: 23
Name: Person1 , Age: 12
Name: Person2 , Age: 30
Name: Person3 , Age: 33
Item Deleted:
Name: Harry , Age: 23
Name: Person1 , Age: 12
Name: Person2 , Age: 30

Test 3 Averages

The averages for test 3 are shown below. As always, we will discuss about this and the final in class.

Tuesday, November 23, 2010

Lab test 3 - send your program to these email ids

jmvidal@gmail.com, shamik.usc@gmail.com, humayun.k1@gmail.com

Lab Test 3 - section 6 - To do list

INPUT FILE FORMAT
(1) First Line : 10 -- Number of Items to be added to an ArrayList
(2) 10 Lines follow -- each line corresponds to data of an Item
Item Data Format :
--------------------------
Name;Color;Size;Price
(3) Line 12 : 3 -- Number of Items to search in ArrayList
(4) 3 Items' Name, Color and Size follows
----------------------------------------------------------------
Things To Do:
--------------------
(a) Read the data from the Input File
(b) Store information about each item in an ArrayList
(c) Read the names, colors and sizes from the file which are to be searched
(d) If items are there in the list corresponding to each Name,Color, and Size, then display their average price

Lab Test 3 - Section 6 - Input File

10
Shirt;blue;S;$40
Shirt;yellow;M;$50
Pant;black;M;$100
Shirt;blue;S;$60
Pant;grey;L;$80
Jacket;black;M;$50
Pant;grey;S;$60
Pant;black;M;$110
Shirt;blue;S;$80
T-Shirt;red;S;$60
3
Shirt;blue;S
Pant;black;M
T-Shirt;green;M

LabTest3 -- Section 5


INPUT FILE FORMAT
--------------------------------
1) First Line : 10 -- Number of Employees to be added to an ArrayList
2) 10 Lines follow -- each line corresponds to data on an Employee
    Employee Data Format :
    ----------------------------------- 
    Name;Age;Salary;Office
3) Line 12 : 4 -- Number of names to search in ArrayList
4) 4 Names follow 
5) Line 17 : 3 -- Number of names to remove from the ArrayList
6) 3 Names follow

7) Check the Output File to see what to display.

-------------------------------------------------------------------------------------------------------
Things To Do:
--------------------
a) Read the data from the Input File
b) Store informattion about each employee in an ArrayList
c) Calculate the Average Salary
d) Read the names which are to be searched to see if they are contained in the list
    If contained in the list then print whether salary above or below average salary
e) Read the names which are to be removed from the ArrayList
   if contained in the list then remove them.
f) Finally display the Final List.

** Check the Output File for the Output Format

LabTest3 -- Output


********* READING EMPLOYEE DATA **************

Employee Data Added: Herbert 32 10000 2A41

Employee Data Added: Lander 45 15000 2A47

Employee Data Added: Winthrop 27 0 3A71

Employee Data Added: Marion 23 3000 4B25

Employee Data Added: Adams 31 4765 5A67

Employee Data Added: Richard 38 20000 6A11

Employee Data Added: Jason 34 12456 4C32

Employee Data Added: Karthik 39 14567 3B33

Employee Data Added: Bernard 40 34234 4A22

Employee Data Added: Sofia 26 45676 3C56
********* EMPLOYEE DATA READ **************

********* BEGIN SEARCH **************
Lander is contained in the list
Employee Details :Lander 45 15000 2A47
Below Average Salary

Arnold is not contained in the list

Marion is contained in the list
Employee Details :Marion 23 3000 4B25
Below Average Salary

Shenoy is not contained in the list

********* END SEARCH **************

********* REMOVING SPECIFIC EMPLOYEE DATA **************
Lander is contained in List - hence removing ...
Jason is contained in List - hence removing ...
Sopna not contained in list
********* SPECIFIC EMPLOYEE DATA REMOVED **************

********** THE FINAL LIST IS: **************
Herbert 32 10000 2A41 
Winthrop 27 0 3A71 
Marion 23 3000 4B25 
Adams 31 4765 5A67 
Richard 38 20000 6A11 
Karthik 39 14567 3B33 
Bernard 40 34234 4A22 
Sofia 26 45676 3C56 

LabTest3 -- Input File


10
Herbert;32;$10000;2A41
Lander;45;$15000;2A47
Winthrop;27;7000;3A71
Marion;23;$3000;4B25
Adams;31;$4765;5A67
Richard;38;$20000;6A11
Jason;34;$12456;4C32
Karthik;39;$14567;3B33
Bernard;40;$34234;4A22
Sofia;26;$45676;3C56
4
Lander
Arnold
Marion
Shenoy
3
Lander
Jason
Sopna

Test 3 Solutions

  1. (20%) Implement a method called isFileThere(String fileName) which returns true if either fileName exists (is the name of a file in the filesystem) or filename.png exists. For example, if the file is "apple" then it should return true if either "apple" or "apple.png" refer to a file in the filesystem. Return false otherwise.
    Answer:
     public static boolean isFileThere(String fileName) {
      File f = new File(fileName);
      if (f.exists()) {
       return true;
      }
      f = new File(fileName + ".png");
      if (f.exists()) {
       return true;
      }
      return false;
     }
     
  2. (20%) What does the following program print out?
    public class Exceptional {
    
     public void happyDays(int x, int y) throws Exception {
      int a[] = {4}; //array with one item.
      try {
       int d = a[x];
       if (y == 0) {
        throw new Exception("Heeeeyyyy");
       }
       System.out.println("Hello Fonzie");
      }
      catch (IndexOutOfBoundsException e) {
       System.out.println("Hello Richie");
      }
     }
    
     public static void main(String[] args) {
      Exceptional e = new Exceptional();
      try {
       e.happyDays(0,1);
       e.happyDays(1,1);
       e.happyDays(0,0);
      } catch (Exception e1) {
       System.out.println("Hello Potsie");
      }
     }
    
    }
    
    Answer: There where three different tests, each with a different answer:
    public static void main(String[] args) {
     Exceptional e = new Exceptional();
     try {
      e.happyDays(0,1);
      e.happyDays(1,1);
      e.happyDays(0,0);
     } catch (Exception e1) {
      System.out.println("Hellow Potsie");
     }
     System.out.println("-------");
     try {
      e.happyDays(1,1);
      e.happyDays(0,1);
      e.happyDays(0,0);
     } catch (Exception e1) {
      System.out.println("Hellow Potsie");
     }
     System.out.println("--------");
     try {
      e.happyDays(1,1);
      e.happyDays(0,0);
      e.happyDays(1,0);
     } catch (Exception e1) {
      System.out.println("Hellow Potsie");
     }
    }
    Hello Fonzie
    Hello Richie
    Hellow Potsie
    -------
    Hello Richie
    Hello Fonzie
    Hellow Potsie
    --------
    Hello Richie
    Hellow Potsie
      
      
  3. (30%) Implement a recursive method that returns the mutant power of a Person. The mutant power of a Person depends on whether or not that person has the X-Gene, and how many of her ancestors have the X-Gene, with maternal lineage being doubly important.
    Specifically, you are given the class
    public class Person {
     public Person mother;
     public Person father;
     /** True if person had the X-Gene */
     public boolean xgene;
    } 
    
    where either mother or father could be null, signifying that no one up that lineage has the X-Gene (ignore them). The mutantPower of a Person Y is given by the formula:
    • mutant-power(Y) = (1 if Y has X-Gene, 0 otherwise) + 2 * mutant-power(Y's mom) + mutant-power(Y's dad).
    Implement int Person.calculateMutantPower(). For example, the code below prints out xavier's mutant power which is 3.
    public static void main(String[] args) {
     Person xavier = new Person();
     xavier.xgene = true;
     Person mom = new Person();
     mom.xgene = true;
     xavier.mother = mom;
     System.out.println(xavier.calculateMutantPower()); // 3
    }
    
    Answer:
    public int calculateMutantPower () {
     int power = (xgene) ? 1 : 0;
     int motherPower = 0;
     int fatherPower = 0;
     //The base case is when both mother and father are null, in which case we just return 1.
     if (mother != null) {
      motherPower = mother.calculateMutantPower();
     }
     if (father != null) {
      fatherPower = father.calculateMutantPower();
     }
     return power + 2*motherPower + fatherPower;
    }
      
  4. (30%) Implement a class called Set which implements a mathematical set, which we define as a bunch of elements of the same type where no element appears more than once (no repeats allowed). You will use an ArrayList to implement your Set.
    The Set will implement 3 methods:
    1. a no-argument constructor (Tip: see Listing 12.10 in your textbook)
    2. an add(...) method which adds a new element to the set, if its not already there,
    3. a toString() method which turns the whole set into a string, with a dash '-' between each element.
    The following is an example usage of the Set class you will write:
    public static void main(String[] args) {
     Set<String> s = new Set<String>();
     s.add("Hi");
     s.add("Hello");
     s.add("Hi");
     s.add("Hi");
     s.add("how are you?");
     System.out.println(s); //prints Hi-Hello-how are you?-
    }
         
    Answer:
    import java.util.ArrayList;
    
    public class Set<T> {
    
     private ArrayList<T> list;
     
     public Set() {
      list = new ArrayList<T>(10); 
     }
     
     public void add(T element) {
      if (!list.contains(element)) {
       list.add(element);
      }
     }
     
     public String toString() {
      String result = "";
      for (int i=0; i < list.size();i++) {
       result += list.get(i) + "-";
      }
      return result;
     }
    }
     

Thursday, November 18, 2010

HW7 Solution

Below is my solution to the homework:

import java.awt.Graphics;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class Fractal extends JPanel {

 private double length;

 public int numLevels;

 public void paintComponent(Graphics g) {
  g.setColor(Color.black);
  System.out.println("Drawing");
  Point from = new Point(150,200);
  Point to = new Point(450,200);
  length = 0;
//  drawFractalLineDragon(g,from,to,numLevels,Direction.Right);
  drawFractalLine(g,from,to,numLevels);
  
//  from = new Point(100,400);
//  Point top = new Point(300,100); 
//  to = new Point(500,400);
//  drawFractalLineSierpinsky(g,from,top,to,numLevels);
  System.out.println("Length of curve is " + length);
 }
 
 
 /**
  * Draw the Sierpinsky triangle http://en.wikipedia.org/wiki/Sierpinski_triangle
  * @param g
  * @param from bottom-left
  * @param top 
  * @param to bottom-right
  * @param level
  */
 public void drawFractalLineSierpinsky(Graphics g, Point from, Point top, Point to, int level) {
  if (level == 0) {
   g.drawLine(from.getX(), from.getY(), to.getX(), to.getY());
   length += from.getVectorTo(to).getMagnitude();
   g.drawLine(from.getX(), from.getY(), top.getX(), top.getY());
   length += from.getVectorTo(top).getMagnitude();
   g.drawLine(top.getX(), top.getY(), to.getX(), to.getY());
   length += top.getVectorTo(to).getMagnitude();
   return;
  }
  Point midFromTop = from.getMidPoint(top);
  Point midFromTo = from.getMidPoint(to);
  Point midTopTo = top.getMidPoint(to);
  
  drawFractalLineSierpinsky(g,from, midFromTop, midFromTo,level-1);
  drawFractalLineSierpinsky(g,midFromTop, top, midTopTo, level-1);
  drawFractalLineSierpinsky(g,midFromTo, midTopTo, to, level-1);
 }

 /**
  * Draws the Levy C Curve http://en.wikipedia.org/wiki/Levy_C_curve
  * @param g
  * @param from start point
  * @param to end point
  * @param level number of recursive levels.
  */
 public void drawFractalLine(Graphics g, Point from, Point to, int level) {
  if (level == 0) {
   g.drawLine(from.getX(), from.getY(), to.getX(), to.getY());
   length += from.getVectorTo(to).getMagnitude();
   //   System.out.println(from + "  " + to);
   return;
  }
  Point mid = from.getMidPoint(to);
  Vector delta = from.getVectorTo(to);
  delta = delta.getPerpendicularRight();
  delta = delta.multiplyBy(0.5); //half its magnitude
  mid = mid.addVector(delta);
  drawFractalLine(g,from,mid,level-1);
  drawFractalLine(g,mid,to,level-1);
 }

 public enum Direction {Right,Left};

 /**
  * Draws the Dragon curve http://en.wikipedia.org/wiki/Dragon_curve
  * @param g
  * @param from
  * @param to
  * @param level
  * @param d
  */
 public void drawFractalLineDragon(Graphics g, Point from, Point to, int level, Direction d) {
  if (level == 0) {
   g.drawLine(from.getX(), from.getY(), to.getX(), to.getY());
   length += from.getVectorTo(to).getMagnitude();
   //   System.out.println(from + "  " + to);
   return;
  }
  Point mid = from.getMidPoint(to);
  Vector delta = from.getVectorTo(to);
  if (d == Direction.Right) {
   delta = delta.getPerpendicularRight();
  } else {
   delta = delta.getPerpendicularLeft();
  }
  delta = delta.multiplyBy(0.5); //half its magnitude
  mid = mid.addVector(delta);
  drawFractalLineDragon(g,from,mid,level-1,Direction.Right);
  drawFractalLineDragon(g,mid,to,level-1,Direction.Left);
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  JFrame frame = new JFrame("Fractal Curve");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  Fractal panel = new Fractal();

  frame.add(panel);
  frame.setSize(600,600);
  frame.setVisible(true);
  try {
   do {
    String userInput = JOptionPane.showInputDialog("How Many Levels?");
    panel.numLevels = Integer.parseInt(userInput);
    frame.repaint(); //don't forget to re-paint it !
   } while (true);
  } catch (NumberFormatException e) {
   //ignore it, just exit program
   System.exit(0);
  }
 }

}

Wednesday, November 17, 2010

Lab Test 3 - Review Question

Problem 5 - Page 788

And also write a test program which will keep on asking the user for a string input and check if its a palindrome or not, by using the recursive method you have developed. The program should stop if the user enters "quit". The test program should also write all the input strings and the results (if its palindrome or not) to a text file.

Chapter 12 Video: Generics

Below is the screencast for Chapter 12 which talks about generics. The chapter also covers dynamic data structures but we will not be focusing on those, so you can skip those sections if you want, or you can read them and be ready for CSCE 146.

CSCE 145: Chapter 12 from Jose Vidal on Vimeo.

Here are the slides from the textbook:

Thursday, November 11, 2010

Lab 21 -- Section 5 & 6 -- Tuesday November 16 -- Sorting using MergeSort

Sort a list of numbers using MergeSort(with recursion). Please work on this from before hand and you must get it to work by your deadline lab timings on Tuesday

Please Refer to the MergeSort Program given in Chapter 11 of the book
Cheers

PS: I was unable to make it to class today due to TOEFL preparations.

Lab 20 - Section 5 and 6

Problem 4 - Page 788

More Lectures by Better Lecturers

If you think that listening to a better lecturer will help you learn the material better then, you are in luck! As you probably know, all major Universities have their CS101-type courses online. I highly recommend MIT's 6.00: Introduction to Computer Science lectures. Another good one is Harvard's CS50.

Below is their video for binary search (using recursion, of course), which I will be talking about today.

Tuesday, November 9, 2010

Lab 19 - section 5 and section 6

Problem 3 - page 787

HW 7: Fractals

In this homework you will practice recursion by drawing some well-known fractal curves. You have to use the Point and Vector classes I provide below to do your arithmetic. I will explain them in class today. The code below also creates a window and draws a line. You will use that as a starting point for your project.
The first curve you will implement is known as the Levy C Curve and its stages are shown on the first figure. A level 0 curve is just a line between two points:start and end. At level 1, instead of drawing a line between the two points, we
  1. find the midpoint between the two points,
  2. find the vector that is perpendicular to the line, scale it by .5
  3. add the perpendicular vector to the midpoint to get a new point, call it NP
  4. recursively draw a c-curve from the start to NP and another one from NP to the end point.
The above set of steps is pseudo-code for the Java recursive function you will write to draw the C Curve.
The second curve you will implement is the Dragon Curve which is nearly identical to the C curve expect that sometimes we use one perpendicular (right) and sometimes the other (left). You will implement another method which draws the Dragon curve.
The third fractal you will implement is the Sierpinsky triangle. This one is different in that, instead of drawing a line by breaking it up into two pieces, you will be drawing a triangle by breaking it up into three smaller triangles. The recursion will be similar but the drawing code will be different.
Finally, after you get these to run then go back and change them so that they calculate and printout the length of the fractal they have just drawn. That is, the sum of the length of all the little line segments.
This homework is due on Thursday, November 18 @9am. Below is the code for Point and Vector which you must use as well as a short program that draws a line, to get you started.
public class Point {
 
 public double x;
 public double y;
 
 /**
  * We return the nearest int to the current x value.
  * By keeping points as double we increase the precision of the final plot.
  * We only convert to int when absolutely necessary, that is, when plotting on screen.
  * @return
  */
 public int getX() {
  return (int) Math.round(x);
 }
 
 public int getY() {
  return (int) Math.round(y);
 }
 
 public Point(int x, int y) {
  this.x = x;
  this.y = y;
 }
 
 public Point(double x, double y) {
  this.x = x;
  this.y = y;
 }
 
 public String toString() {
  return x + "," + y;
 }
 
 /**
  * Make a vector from this point to other
  * @param other
  * @return a new Vector
  */
 public Vector getVectorTo(Point other) {
  return new Vector(other.x - x,other.y - y);
 }
 
 /**
  * Returns a Point that lies midway on the line between this point and other
  * @param other
  * @return a new Point
  */
 public Point getMidPoint(Point other) {
  return new Point((x + other.x)/ 2, (y +other.y)/ 2);
 }

 /**
  * Move this point by vector v.
  * @param v
  * @return a new Point
  */
 public Point addVector(Vector v) {
  return new Point(x + v.x, y + v.y);
 }
 
}


public class Vector extends Point {

 public Vector(double x, double y) {
  super(x,y);
 }

 /**
  * The magnitude
  * @return the magnitude.
  */
 public double getMagnitude() {
  return Math.sqrt(x*x+y*y);
 }

 /**
  * Creates a new vector that is perpendicular to this one, pointing to the right.
  * @return a new vector
  */
 public Vector getPerpendicularRight() {
  return new Vector(-y, x);
 }

 /**
  * Creates a new vector that is perpendicular to this one, pointing to the left.
  * @return a new vector
  */
 public Vector getPerpendicularLeft() {
  return new Vector(y, -x);
 }

 /**
  * Creates a new vector like this one but scaling both coordinates by d
  * @param d
  * @return a new vector
  */
 public Vector multiplyBy(double d) {
  return new Vector(x*d, y*d);
 }

}

/** Jose M Vidal 
 * If that's not me on the line above then I deserve 0 points on this homework. */

import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JOptionPane;

public class Fractal extends JPanel{

 public int numLevels;

 public void paintComponent(Graphics g) {
  g.setColor(Color.black);
  System.out.println("Drawing");
  g.drawLine(200, 200, 400, 200);
 }
 
 /**
  * @param args
  */
 public static void main(String[] args) {
  JFrame frame = new JFrame("Fractal Curve");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  Fractal panel = new Fractal();

  frame.add(panel);
  frame.setSize(600,600);
  frame.setVisible(true);
  try {
   do {
    String userInput = JOptionPane.showInputDialog("How Many Levels?");
    panel.numLevels = Integer.parseInt(userInput);
    frame.repaint(); //don't forget to re-paint it !
   } while (true);
  } catch (NumberFormatException e) {
   //ignore it, just exit program
   System.exit(0);
  }
 }
}

HW6 Solution

Below is my solution to HW6:
public class FileTooBigException extends Exception {
 public FileTooBigException(String msg) {
  super(msg);
 }
}

public class NotEnoughDataException extends Exception { 
 public NotEnoughDataException(String msg) {
  super(msg);
 }
}

import java.util.Scanner;
public class Day {
 private String date;
 private double open;
 private double high;
 private double low;
 private double close;
 private long volume;
 
 public double getClose() {
  return close;
 }
 
 public double getVolume() {
  return volume;
 }
 
 /**
  * Creates a new Day object by reading values from istream:
  *   date, open, high, log, close, volume: in that order.
  * We assume the delimiter has been correctly set on istream so values can be read
  *   by calling nextX()
  * @param istream
  */
 public Day (Scanner istream) {
  date = istream.next();
  open = istream.nextDouble();
  high = istream.nextDouble();
  low = istream.nextDouble();
  close = istream.nextDouble();
  volume = istream.nextLong();
 }

 public String toString() {
  return date + " " + close + " " + volume;
 }
}


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;

public class Security {

 private Day[] day;

 private int lastDay;

 private static final int DAY_ARRAY_SIZE = 1000;

 /**
  * Add day d to the history, but only if its volume > 0.
  * @param d
  * @throws FileTooBigException 
  */
 public void addDay(Day d) throws FileTooBigException {
  if (d.getVolume() > 0) {
   if (lastDay >= DAY_ARRAY_SIZE) {
    throw new FileTooBigException("You cannot have more than " + DAY_ARRAY_SIZE + " days.");
   }
   day[lastDay++] = d;
  }
 }

 public Security () {
  day = new Day[DAY_ARRAY_SIZE];
  lastDay = 0;
 }

 /** Read historical values for this security from a csv stream.
  * 
  * @param file
  * @throws FileTooBigException 
  */
 public void readFromStream(Scanner istream) throws FileTooBigException {
  istream.useDelimiter("[,\\s]"); //separate on , or on whitespace
  if (istream.hasNext()) {
   istream.nextLine(); //ignore first line
  }
  String w = null;
  while (istream.hasNext()) {
   //System.out.println("----" + istream.next());
   Day nextDay = new Day(istream);
   addDay(nextDay);
  }
 }

 public double getVolatility(int numDays) throws NotEnoughDataException {
  if (numDays > lastDay) {
   throw new NotEnoughDataException("Need more historical data");
  }
  double average = getAverageClose(numDays);
  double squareDifference = 0;
  for (int i=0; i < numDays; i++) {
   squareDifference += Math.pow(day[i].getClose() - average, 2);
  }
  double deviation = squareDifference / (double) numDays;
  return Math.sqrt(deviation);
 }

 public double getAverageClose(int numDays) {
  double sum = 0;
  for (int i=0; i< numDays;i++) {
   sum += day[i].getClose();
  }
  return sum / (double)numDays;
 }

 public String toString() {
  String result = "";
  for (int i= 0; i < lastDay; i++) {
   result += day[i] + "\n";
  }
  return result;
 }

 public double getMinClose(int numDays) {
  double min = Double.MAX_VALUE; //assume no stock price is ever this high
  for (int i = 0; i < numDays; i++) {
   if (day[i].getClose() < min)
    min = day[i].getClose();
  }
  return min;
 }

 public double getMaxClose(int numDays) {
  double max = -1;
  for (int i = 0; i < numDays; i++) {
   if (day[i].getClose() > max)
    max = day[i].getClose();
  }
  return max;
 }
 /**
  * Returns a price distribution array, where the index of the array is the price - getMinClose(numDays)
  * whose contents are the number of days we closed at that price within the last numDays.
  * @param numDays
  * @return array with getMaxClose(numDays) - getMinClose(numDays) + 1 values 
  */

 public int[] getPriceDistribution(int numDays) {
  int min = (int) getMinClose(numDays);
  int max = (int) getMaxClose(numDays);
  int[] result = new int[max-min + 1];
  for (int i =0; i < numDays; i++) {
   result[(int)day[i].getClose() - min]++;
  }
  return result;
 }

 public void savePriceDistribution(String outFile,int numDays) throws FileNotFoundException {
  PrintWriter out = new PrintWriter(new FileOutputStream(outFile, true));
  int min = (int) getMinClose(numDays);
  int[] distribution = getPriceDistribution(numDays);
  for (int i =0; i < distribution.length; i++) {
   int p = min + i;
   out.write(p + "," + distribution[i] + "\n");
  }
  out.close();
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  Scanner istream = null;
  String inputFile = "/Users/jmvidal/data.csv";
  try {
   istream = new Scanner(new File(inputFile));
  } catch (FileNotFoundException e) {
   System.out.println("Ooops, no such input file:" + inputFile);
   System.exit(1);
  }

  Security s = new Security(); //Security class will hold all the data
  try {
   s.readFromStream(istream); //read the contents from istream
  } catch (FileTooBigException e1) { //file is to big to read
   System.out.println(e1.getMessage());
   System.exit(1);
  }

  System.out.println(s); //print out all the contents. Note: no days with 0 volume.

  try {
   System.out.println("Volatility in the last 10 days = " + s.getVolatility(10));
   System.out.println("Volatility in the last 1000 days = " + s.getVolatility(1000));

  } catch (NotEnoughDataException e) {
   System.out.println("Sorry, not enough data." + e.getMessage());
  }

  System.out.println("Price Distribution for the last 10 days.");
  System.out.println("price\tnumber of days");
  int[] priceDistribution = s.getPriceDistribution(10); //get the distribution array
  int minClose = (int)s.getMinClose(10);
  for (int i=0; i < priceDistribution.length; i++) { //we need this loop to print it out
   int p = minClose + i;
   System.out.println(p + "\t" + priceDistribution[i]);
  }

  try {
   //now, save the distribtion for the last 20 days to a file.
   s.savePriceDistribution("/Users/jmvidal/distribution-20.csv",20); 
  } catch (FileNotFoundException e) {
   System.out.println("Ooops, bad output file name.");
   System.exit(1);
  }
 }
}

Monday, November 8, 2010

Chapter 11 Video: Recursion

Chapter 11 deals with the topic of recursion. Recursion is not a language feature, it is simply having a method call itself. All programming languages are capable of recursion. Recursion is a technique that makes certain algorithms much easier to write and understand.

CSCE 145: Chapter 11 from Jose Vidal on Vimeo.

Here are the slides from the textbook:

Thursday, November 4, 2010

Java 4-Ever!

Already nominated for a Developers' Choice award:

Chapter 10 Video

Below is the screencast for the chapter 10 which deals with reading and writing streams to files. I/O operations like these are slightly different on every programming language, but the basic ideas are the same.

CSCE 145: Chapter 10 from Jose Vidal on Vimeo.

The textbook slides are below.

Lab 18 -- File Handling -- File Read/Write

Assume you are the owner of Tower Records, which sells music CDs and albums, and you decide to hold a sale to try to reduce your inventory of old records. Write a Java program to read from your inventory text file (refer below for an example file "albums.txt"), which contains information about albums and CDs, including their cost. If an album is between one year and five years old, change the cost to show a discount of 5%. If an album is between 5 years old and 10 years old, give a discount of 10%. If it is more than 10 years old, give a discount of 50%. The album information with the new pricing should be written into a new text file newalbums.txt.

Each record is represented by four lines of text in the files. The first line is the title of the album, the next line is the artist/group name, the next is the year of release, and the next is the price of the album.

Hints: Once you read in each line as a String you can parse the year of release Integer.parseInt(String s) to an int and check how old it is and give a discount on the parsed price (double). Use the substring(int index) method of the String class to get rid of the $ sign in the front of price. Use a loop to do it for all albums.

Lab 18 -- FileHandling -- albums.txt

Rock Steady
No Doubt
2002
$18.98
Revolver
The Beatles
1966
$14.00
Dangerously in Love
Beyonce featuring Jean Paul
2003
$18.50
Blood on the Dance Floor: History in the Making
Michael Jackson
1997
$16.50

Wednesday, November 3, 2010