Thursday, November 29, 2007

Declaring an Edge Adjacency List Graph

The 3 types of Graph representations are: 1. Edge List 2. Adjacency Edge List 3. Edge Matrix The heart of the simplest representation of Edge List is the following:

LinkedList [ ] AdjLists = new LinkedList [numberOfVertices];

This implies that we are declaring an Array called AdjLists. No matter what, the Graph at the end is just an Array!!! This Array called AdjLists will hold elements of the type LinkedList which are in turn containers of type 'Edge'. Whatever Edge means... So basically, we are implementing a 3 level structure, at the end the edge objects are elements that are stored in Linked Lists, which are themselves stored in an Array! How beautiful!!!!!!!!!!!!

Monday, November 26, 2007

MaximallyBalanced or Complete Binary Tree

// Queue version -- only version totally working so far!
    public boolean isMaximallyBalanced (TreeNode x){ 

            boolean scanningNulls = false;

            Deque q = new LinkedList ();
            q.addFirst(x);

            while (q.size() != 0) {
                TreeNode n = q.remove();

                if (scanningNulls) {
                    if (n != null) 
                        return false;
                }
                else {
                    if (n == null) {
                        scanningNulls = true;
                    }
                    else {
                        q.add(n.myLeft);
                        q.add(n.myRight);
                        
                    }
                    }
                }
            
            return true;
        }

// Adopted from: www.boyet.com/Articles/CheckingForHeap.html 

Wednesday, November 21, 2007

Calculating the Height of a Tree

//Increase the height only when the recursive call generates a new Iterator!!!
private static int height (T x) {
     if (x.myChildren.isEmpty ( )) {
         return 1;
     } else {
         int bestSoFar = 0;
         Iterator iter = x.myChildren.iterator ( );
         while (iter.hasNext ( )) {
             T child = iter.next ( );
             bestSoFar = Math.max (height(child) + 1, bestSoFar);
         }
         return bestSoFar;
     }
 }

Monday, November 19, 2007

Adding to a Circular Doubly Linked List


public void add (Object to_Add) {
    if (isEmpty ( )) {
      myHead = new DListNode (to_Add);
    } else {
      // Insert to_Add between myHead and myHead.myPrev.
      DListNode newNode = new DListNode (to_Add, myHead.myPrev, myHead);
      // Link the new node into the list.
      myHead.myPrev.myNext = newNode; // This is the circular link stuff.
      myHead.myPrev = newNode;
    }
    mySize++;
  }

Sunday, November 18, 2007

3 ways to REVERSE a list (singly linked)

There are 50 ways to leave your lover (P.Simon) but fundamentally 3 ways
 to reverse a list
1. Recursively Non-Destructive
2. Recursively Destructive
3. Iteratively

Recursively Non-Destructive:

public ListNode reverse (ListNode list) {
  ListNode sofar = new EmptyListNode();
        return reverseHelper (this, sofar);

 }


 private static ListNode reverseHelper (ListNode list1, ListNode sofar) {

        if (list1.isEmpty()) {

                return sofar;

        } else {

                return reverseHelper (list1.rest() ,  new NonemptyListNode (list1.first(), sofar) );

        }

 }
 


Recursively Destructive:




public void reverse2 () {
  myHead = reverse2Helper (myHead, null);
 }
 
 public static ListNode reverse2Helper (ListNode L, ListNode soFar){
  if (L == null){
   return soFar;
  } else {
   ListNode temp = L.myRest;
   L.myRest = soFar;
   return reverse2Helper (temp, L) ;
  }
 }




Iteratively:



public void reverse3 () {
  myHead = reverse3Helper (myHead);
 }

public static ListNode reverse3Helper (ListNode head){
  ListNode p, soFar;
  for (p = head, soFar = null; p != null;){
   ListNode temp = p.myRest;
   p.myRest = soFar;
   
   soFar = p;
   p = temp;
   
  }
  return soFar;
 
}




Reversing a List Iteratively!

public void reverse3 () {
  myHead = reverse3Helper (myHead);
 }

public static ListNode reverse3Helper (ListNode head){
  ListNode p, soFar;
  for (p = head, soFar = null; p != null;){
   ListNode temp = p.myRest;
   p.myRest = soFar;
   soFar = p;
   p = temp;
   
  }
  return soFar;
 
}

Saturday, November 17, 2007

Doubling a Linked List

//couldn't find a better way to do this...

public void double2 ( ) {
  /* Invariant is L with 2 first ones and rest*/
  ListNode q, w;
  w = q = new ListNode (null);
  
  for (ListNode p = myHead; p != null; p = p.myRest) {
       
       q.myRest = new ListNode(p.myFirst, p);
       q = q.myRest.myRest;
       
               
     }
  myHead = w.myRest;
   /*ListNode p = myHead;
  ListNode p1 = myHead.myRest;
  ListNode p2 = myHead.myRest.myRest;
  
  myHead = new ListNode (p.myFirst, p);
  myHead.myRest.myRest = new ListNode (p1.myFirst, p1);
  myHead.myRest.myRest.myRest.myRest = new ListNode (p2.myFirst, p2);
   */
 }
 
 public void double3 ( ) {
  ListNode w;
  w = new ListNode (myHead.myFirst);
  for (ListNode p = myHead; p != null; p = p.myRest) {
   w.myRest= new ListNode(p.myFirst, p);
   w = w.myRest.myRest;
   System.out.println(this.toString());
  }
  myHead = new ListNode (myHead.myFirst, myHead);
 }


Friday, November 9, 2007

Access Modifiers: public, private, proctecd, package protected(default)

Public : declarations represent specifications – what clients of a package are supposed to rely on. Package Private (default): declarations are part of the implementation of a class that must be known to other classes that assist in the implementation. Protected: declarations are part of the implementation that subtypes may need, but that clients of the subtypes generally won’t. Private: declarations are part of the implementation of a class that only that class needs. *********************************************************************** Import: Does not grant any special access; it only allows abbreviation.

Thursday, November 8, 2007

End of HFJ

Announcing the end of going through HFJ. Admittedly, only a first pass... But finally finished back back to back...well maybe except for code kitchens on the beat program and some of the appendices...But did finish all the chapters, didn't I? It's a great book and one that really make stuff look easy. As they say, the best always make it look easy! And this is kind of, one of the best example of that saying! Took me 5 weeks to go through it all. But it was a great experience. I'll miss, reading that book, it seems to me! In any case, on to more stuff then....

Wednesday, November 7, 2007

Format Specifiers

Format Specifiers:

% [argument number] [flags] [width] [.precision] type

%: says, ‘insert arument here’ and format it using these instructions.

flags: these are for special formatting options like inserting commas, or
Putting negative numbers in parentheses, or to make the numbers
Left justified

width: This defines the Minimum number of characters that will be sued.
That’s minimum not TOTAL. If the number is longer than the width,it’ll still be used in
full, but if it’s less than the width, it’ll be padded with zeroes. Most of the time
this does not need to be specified.


.precision:  It defines the precision. In other words, it sets the number of decimal places.

type: Type is mandatory and will usually be ‘d’ for a decimal integer or ‘f’ for a floating
point number.

E.g. :
format(“%,3.1f”, 91.0000000); -> 91.0

complete example code:

public class FormatTest {

static String x = "";
static double y = 91.000000;

public static void main(String[] args) {

 x = String.format("%,3.1f", y);
 System.out.println(x);

}

} // produces: 42.0

// Adopted from HFJ

Tuesday, November 6, 2007

Collection class tidbits...

I had to say I do > in a picture...

Generic class definitions and one implementation

Generic class definitions and one implementation

Type parameterization goes in the horizontal direction while abstraction takes care of the 
vertical direction. The idea is the same, reusability and other OOP goodness. 

“The Class, the central notion in Object Technology, can be viewed as the product of the 
corporate merger between the module and type concepts.”

A generic class declared as C[G] is, rather than a type, a type pattern covering an infinite 
set of possible types; you can obtain any one of these by providing an actual generic 
parameter – itself a type - corresponding to G.

Java allows the use of wildcards to specify bounds on what type of parameters a given
 generic object may have. E.g. List indicates a list which has an unknown object 
type.  
List  is pronounced as List of Unknowns.

Void printCollection (Collection  c) {
 For (Object e : c)
     System.out.println(e);
} // will work for any collection of objects. 
   //But if the formal argument is Collection   then, it will not!

This is because, in general, if Parrot is a subtype (subclasss or subinterface) of 
Bar, and G is some Generic type declaration, it is not the case that G is a
subtype of G.

To specify the upper bound of a generic element, the extends keyword is used, which
 indicates that the generic type is a subclass (either extends the class, or 
implements the interface) of the bounding class.

So List means that the given list contains objects which extend the 
Shape class; for example, the list could be List or List.

To specify the lower bound of a generic element, the super keyword is used, which 
indicates that the generic type is a superclass of the bounding class.

So, List could be List or List or List.

Example Implementation: The  fictitious “formal generic parameter” here is E.

public class OopList {
 
 protected class Node{
  E element;
  Node next;
  Node (E e, Node n){ element = e; next = n; }
 }
 
 protected Node _head;
 
 
 /** Construct the empty List. */
 public OopList() { _head = null; }
 
 /** Add item to the beginning of the List. */
 
 public void add (E element) {
  _head = new Node (element, _head);
 }
 
 /** Return true iff this List is empty. */
 
 public boolean isEmpty() { return _head == null; }
 
 public String toString() {
  String x = "( ";
  while (!isEmpty()){
   x = x + this._head.element + " ";
   _head = _head.next;
  }
  return x + ")";
 }
 
 /** Allow iteration. */
 
 public java.util.Iterator elements() {
  return new OopListIterator (this);
 }
 
 public static void main (String [] args) {
  OopList OopLT = new OopList ();
  OopLT.add("Hello");
  OopLT.add("Not");
  OopLT.add("Done");
  
  System.out.println(OopLT.toString());
  
 }
} // End of class 



//********************************************************


// beginning of Iterator class. OopListIterator.

import java.util.*;

public class OopListIterator implements Iterator {
 
 private OopList _list;
 private OopList.Node _current;
 
 public OopListIterator (OopList list){
  _list = list;
  _current = _list._head;
 }
 
 public boolean hasNext () { return (_current != null); }
 
 public E next() throws NoSuchElementException {
  if (_current == null)
   throw new NoSuchElementException();
  E result = _current.element;
  _current = _current.next;
  return (result);
 }
 
 public void remove() throws UnsupportedOperationException {
  throw new UnsupportedOperationException();
 } 
  
 
}

//************************************************ Test Classes


public class Animal {

 protected String x;
 protected int age;
 protected boolean pet;
 
 public Animal (String y, int v, boolean i){
  x = y;
  age = v;
  pet = i;
 }
 
 public String toString (){
  String voila = "";
  voila = "Name: " + x + "  " +  "Age: " + age + " "+ " Pet: " + pet;
  return voila;
 }
 
 
 
 public static void main (String [] args){

  Animal me = new Animal ("Tiger", 33, true);
  System.out.println("Tiger is: ");
  System.out.println(me.toString());
 
  Animal Parrot1 = new Parrot ("P", 3, true);
  System.out.println("Parrot is: ");
  System.out.println(Parrot1.toString());
 }
}

//*****************************************

public class Parrot extends Animal {
  
  public Parrot (String x, int v, boolean z){
   super(x, v, z);
   this.x = "Parrot";
  }
  
 }


// JUNIT Testing:
//********************************************************

import junit.framework.TestCase;


public class OopListTest extends TestCase {

 public void OopListConstructorTest() {
  OopList OopLT = new OopList ();
  assertTrue (OopLT.isEmpty());
  
 }
 
 public void testOopList() {
  OopList OopLT = new OopList ();
  assertTrue (OopLT.isEmpty());
 }

 public void testAdd() {
  OopList OopLT = new OopList ();
  OopLT.add("Hello");
  OopLT.add("Not");
  OopLT.add("Done");
  assertEquals ("( Done Not Hello )", OopLT.toString());
  
 }

 public void testIsEmpty() {
  OopList OopLT = new OopList ();
  assertTrue (OopLT.isEmpty());
 }

 public void testElements() {
  OopList OopLT = new OopList ();
  OopListIterator iter1 = new OopListIterator (OopLT);
  assertFalse (iter1.hasNext());
  OopLT.add("Hello");
  OopLT.add("Not");
  OopLT.add("Done");
  OopListIterator iter = new OopListIterator (OopLT);
  
  assertFalse (OopLT.isEmpty());
  assertTrue (iter.hasNext());
  assertTrue (iter.hasNext());
  assertEquals("Done", iter.next().toString());
  assertEquals("Not", iter.next().toString());
  assertEquals("Hello", iter.next().toString());
  assertFalse (iter.hasNext());
 
 }
 
 /* Now let's try with another set of Objects 
  * Actual Generic Parameters in this case are Animal objects.
  * Type erasure and Generically derived type is Animal here.
  * */
 
 
 public void testElements3() {
  OopList OopLT = new OopList ();
  assertTrue (OopLT.isEmpty());
  OopListIterator iter1 = new OopListIterator (OopLT);
  assertFalse (iter1.hasNext());
  
  Animal me = new Animal("Tiger", 33, true);
  
  Animal horse = new Animal("Horse", 10, true);
  
  Animal Parrot1 = new Parrot ("P", 3, true);
  OopLT.add(Parrot1);
  OopLT.add(horse);
  OopLT.add(me);
  OopListIterator iter = new OopListIterator (OopLT);
  assertFalse (OopLT.isEmpty());
  assertTrue (iter.hasNext());
  assertTrue (iter.hasNext());
  assertEquals("Name: Tiger  Age: 33  Pet: true", iter.next().toString());
  assertEquals("Name: Horse  Age: 10  Pet: true", iter.next().toString());
  assertEquals("Name: Parrot  Age: 3  Pet: true", iter.next().toString());
  assertFalse (iter.hasNext());
  OopListIterator iter2 = new OopListIterator (OopLT);
  assertTrue (iter2.hasNext());
  assertTrue (iter2.hasNext());
  assertEquals("Name: Tiger  Age: 33  Pet: true", iter2.next().toString());
  assertEquals("Name: Horse  Age: 10  Pet: true", iter2.next().toString());
  assertEquals("Name: Parrot  Age: 3  Pet: true", iter2.next().toString());
}
}

// Adopted from: http://www.cs.huji.ac.il/course/2005/oop/lecture-slides.html


Thursday, November 1, 2007

doubling a List

//couldn't find a better way to do this...

public void double2 ( ) {
  /* Invariant is L with 2 first ones and rest*/
  ListNode q, w;
  w = q = new ListNode (null);
  
  for (ListNode p = myHead; p != null; p = p.myRest) {
       
       q.myRest = new ListNode(p.myFirst, p);
       q = q.myRest.myRest;
       
               
     }
  myHead = w.myRest;
   /*ListNode p = myHead;
  ListNode p1 = myHead.myRest;
  ListNode p2 = myHead.myRest.myRest;
  
  myHead = new ListNode (p.myFirst, p);
  myHead.myRest.myRest = new ListNode (p1.myFirst, p1);
  myHead.myRest.myRest.myRest.myRest = new ListNode (p2.myFirst, p2);
   */
 }
 
 public void double3 ( ) {
  ListNode w;
  w = new ListNode (myHead.myFirst);
  for (ListNode p = myHead; p != null; p = p.myRest) {
   w.myRest= new ListNode(p.myFirst, p);
   w = w.myRest.myRest;
   System.out.println(this.toString());
  }
  myHead = new ListNode (myHead.myFirst, myHead);
 }


Don't Forget Your Scheme!


Well, wasted half a day yesterday by forgetting my Scheme. Finally,
A&S came to the rescue, somehow remembered after wasting a lot of time,
that 'append!' was one of the examples in that book and the same stuff
basically can be done in Java too..

Here is the Scheme version:


 (define (append! x y)
   (set-cdr! (last-pair x) y)
 x)
Here last-pair is a procedure that returns the last pair in its argument:

 (define (last-pair x)
   (if (null? (cdr x))
       x
   (last-pair (cdr x))))

From there the Java version for append! or what we call, descructively
appending a list to another one while not instantiating another one is easy.
Though we have to instantiate a new ListNode...

         ListNode LastP = lastPair(list1);
  LastP.setNext(list2);   //setNext is set-cdr!
  return list1;

Here's the helper for Java...

      public static LNode lastPair(ListNode y){
 if (y.next().isEmpty()){
    return y;
 } else 
  return lastPair(y.next());
      }


Another instersting one is the Reverse method: 

Scheme Version:

       (define (reverse L)
 (reverse-helper L '( )) )
 
       (define (reverse-helper L so-far)
      (if (null? L) so-far
   (reverse-helper (cdr L) (cons (car L) so-far)) ) )

Java version works the sameway if we are writing the recursive one:

return reverseHelper (list1.next() ,  new LNode (list1.data(), sofar) );


Just some daily notes ...

Powered By Blogger