Category Archives: Class work

Symbol Tables Concepts

Definition

A symbol table is a data structure for key-value pairs that supports two operations:

  1. insert (put) a new pair into the table
  2. search for (get) the value associated with a given key

  1. Only one value is associated with each key (no duplicate keys in a table).
  2. When a client puts a key-value pair into a table already containing that key (and
    an associated value), the new value replaces the old one

The associative array abstraction, where you can think of a symbol table as being just like an array, where keys are indices and values are array entries.

In a conventional array, keys are integer indices that we use to quickly access array values; in an associative array (symbol table), keys are of arbitrary type, but we can still use them to quickly access values.

Keys must not be null. As with many mechanisms in Java, use of a null key results in an exception at runtime

In java, no key can be associated with the value null.

Searching cost model
When studying symbol-table implementations, we count compares (equality tests or key comparisons). In (rare) cases where compares are not in the inner loop, we count array accesses.

Priority Queues – Comparable and Comparator

Screen Shot 2016-01-02 at 2.43.31 AM

Implementing Comparable amounts to defining a compareTo() method that implements a natural ordering for the type.

There are many applications where we want to use different orders for the objects that we are sorting, depending on the situation. The Java Comparator interface allows us to build multiple orders within a single class.

Insertion sorting with a Comparator

public static void sort(Object[] a, Comparator c)
  {
     int N = a.length;
     for (int i = 1; i <; N; i++) for (int j = i; j >; 0 && less(c, a[j], a[j-1]); j--)
           exch(a, j, j-1);
}
  private static boolean less(Comparator c, Object v, Object w)
  {  return c.compare(v, w) <; 0;  }
  private static void exch(Object[] a, int i, int j)
  {  Object t = a[i]; a[i] = a[j]; a[j] = t; }


In typical applications, items have multiple instance variables that might need to serve as sort keys.

The sort does each compare through a callback to the compare() method in Transaction that is specified by the client code. To avoid the cost of making a new Comparator object for each sort, we could use public final instance variables to define the comparators (as Java does for CASE_INSENSITIVE_ORDER).

 import java.util.Comparator;
  public class Transaction
  {
     ...
     private final String who;
     private final Date when;
     private final double amount;
     ...
     public static class WhoOrder implements Comparator
     {
        public int compare(Transaction v, Transaction w)
        {  return v.who.compareTo(w.when);  }
     }
     public static class WhenOrder implements Comparator
     {
        public int compare(Transaction v, Transaction w)
        {  return v.when.compareTo(w.when);  }
     }
     public static class HowMuchOrder implements Comparator
     {
        public int compare(Transaction v, Transaction w)
        {
           if (v.amount < w.amount) return -1; if (v.amount > w.amount) return +1;
           return 0;
} }
}

Priority queues with comparators. The same flexibility to use comparators is also useful for priority queues. Extending our standard implementation in Algorithm 2.6 to support comparators involves the following steps:
. Import java.util.Comparator.
. Add to MaxPQ an instance variable comparator and a constructor that takes a 
comparator as argument and initializes comparator to that value.
. Add code to less() that checks whether comparator is null (and uses it if it is 
not null).
For example, with these changes, you could build different priority queues with Transaction keys, using the time, place, or account number for the ordering. If you remove the Key extends Comparable phrase from MinPQ, you even can support keys with no natural order.

ALGORITHM 2.6 Heap priority queue
  public class MaxPQ >
  {
     private Key[] pq;             // heap-ordered complete binary tree
     private int N = 0;            //    in pq[1..N] with pq[0] unused
     public MaxPQ(int maxN)
     {  pq = (Key[]) new Comparable[maxN+1];  }
public boolean isEmpty()
{  return N == 0;  }
public int size()
{  return N;  }
public void insert(Key v)
{
pq[++N] = v;
swim(N); }
public Key delMax()
{
   Key max = pq[1];
   exch(1, N--);
   pq[N+1] = null;
   sink(1);
return max; }
// Retrieve max key from top.
// Exchange with last item.
// Avoid loitering.
// Restore heap property.
     // Missing the implementations of these helper methods.
     private boolean less(int i, int j)
     private void exch(int i, int j)
     private void swim(int k)
     private void sink(int k)
}

MaxPQ

Assignments:
1. Write a telephone lookup program, YI_Telephone.java. Read a data set of 1,000 names and telephone numbers from a file that contains the numbers in random order. Handle lookups by name and also reverse lookups by phone number. Use Comparator and a binary search for both lookups.

2. Write a program, YI_StringLength.java to sort an array list of strings by increasing length. Supply a Comparator.

NOTE:
Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.
http://stackoverflow.com/questions/8736378/what-is-a-callback-in-java

Recursive N-queen Problem – An implementation

Know a bit about the Queen piece in a game of Chess

A solution for the “8 queens” problem

Numberphile video:

You can have access to all the Lynda.com resources with your own Princeton Public Library card.

The problem: Design and implement a recursive program that solves the Non- Attacking Queens problem. That is, write a program to determine how eight queens can be positioned on an eight-by-eight chessboard so that none of them are in the same row, column, or diagonal as any other queen. There are no other chess pieces on the board.

Assignment:
If you already implemented the solution to the problem, answer the following questions:

  1. How does your implementation compare to the one below?
  2. Is your implementation better than this one?
  3. What is the time complexity (for now we can say the big-O notation)?

If you have not implemented yet, do the following:

  1. Trace the code for 4 queens. It only has 2 solutions but 1 unique.
  2. Explain how the implementation works
  3. What is the time complexity (for now we can say the big-O notation)?

//********************************************************************
//
//  A recursive program that solves the Non-attacking Queens problem.
//********************************************************************

public class NonAttackingQueens {

    int[] queens;   // Queen i is always placed in row i.  The
                    // column is variable.
                    // queens[i] represents the column of the ith row 
                    // where the ith queen is
    
    final int NUM_QUEENS = 8;
 
    public NonAttackingQueens()
    {
        queens = new int[NUM_QUEENS];
    }

    //-----------------------------------------------------------------
    //  Returns true if a queen queenNumber can be placed in column 
    //----------------------------------------------------------------- 
    boolean canPlace(int queenNumber, int column)
    {
        for (int row = 0; row < queenNumber; row++) // check all rows above queenNumber row
        {

            if (queens[row] == column) // in the same column
                return false;
            if (Math.abs(queens[row] - column) == Math.abs(row - queenNumber)) // same diagonal
                return false;
        }
        return true;
    }
    
    //-----------------------------------------------------------------
    //  Starting with the row represented by queenNumber, find all correct 
    //  placements in the row and below the row.
    //-----------------------------------------------------------------
    public void solve(int queenNumber)
    {
        for (int column = 0; column < NUM_QUEENS; column++)  // iterate through all columns
        {
            if (canPlace(queenNumber, column)) // queen can be placed in current column
            {
                queens[queenNumber] = column;  // place queen in current column

                if (queenNumber + 1 >= NUM_QUEENS) // solved
                    printSolution();
                else    // keep looking
                    solve(queenNumber + 1);
            }
        }
    }

    //-----------------------------------------------------------------
    //  Computes and displays all solutions to the problem
    //-----------------------------------------------------------------    
    public void showSolutions()
    {
        solve(0);  // start with the first row
    }
    
    //-----------------------------------------------------------------
    //  Prints a grid showing the position of the queens on the chessboard.  
    //  Queen = X
    //  Empty space = O
    //-----------------------------------------------------------------    
    private void printSolution()
    {
        int column;
        for (int row=0; row<num_queens; row++)="" {="" for="" (column="0;" column<num_queens;="" column++)="" if="" (queens[row]="=" column)="" system.out.print("="" x");="" else="" 0");="" system.out.print("\n");="" }="" system.out.println("\n-----------------------");="" public="" static="" void="" main="" (string="" args[])="" new="" nonattackingqueens().showsolutions();="" <="" pre=""></num_queens;>

BSTs – Proposition

Screen Shot 2015-02-27 at 7.44.59 AM

2-3 search trees
Screen Shot 2015-02-27 at 7.46.26 AM

We introduce in this section a type of binary search tree where costs are guaranteed to be logarithmic. Our trees have near-perfect balance, where the height is guaranteed to be no larger than 2 lg N.

Proposition.

Search and insert operations in a 2-3 tree with N keys are guaranteed to visit at most lg N nodes.

Typical 2-3 tree built from random keys
However, we are only part of the way to an implementation. Although it would be possible to write code that performs transformations on distinct data types representing 2- and 3-nodes, most of the tasks that we have described are inconvenient to implement in this direct representation.

Implementing Binary Search Trees

Binary Trees

Homework:
Implementing Binary Search Trees: With Links

1. How are the constructors implemented?
2. Write the pseudocode for public void addElement (T element). Draw an example of adding an element to a BST.
3. Write the pseudocode for public T removeElement (T targetElement). Draw an example of removing an element to a BST.
4. Write the pseudocode for public void removeAllOccurrences (T targetElement).

LispList interface

November 13th, 2014
Screen Shot 2014-11-13 at 7.29.51 AM
Linked lists. A linked list is a recursive data structure that is either empty (null) or a reference to a node having a generic item and a reference to a linked list. To implement a linked list, we start with a nested class that defines the node abstraction

private class Node {
   Item item;
   Node next;
}

Homework:
LispList interface and the EmptyList and NonEmptyList classes implementations.
Write a test program that constructs a list and prints it.
From Wikipedia:
Lisp (historically, LISP) is a family of computer programming languages with a long history and a distinctive, fully parenthesized Polish prefix notation. Originally specified in 1958, Lisp is the second-oldest high-level programming language in widespread use today; only Fortran is older (by one year).
The name LISP derives from “LISt Processing”. Linked lists are one of Lisp language’s major data structures, and Lisp source code is itself made up of lists. As a result, Lisp programs can manipulate source code as a data structure, giving rise to the macro systems that allow programmers to create new syntax or new domain-specific languages embedded in Lisp.

Bag Class

Classwork:
Go to Classroom Salon to discuss the Bag Class and watch only the visual representation of stacks and queues video.

Screen Shot 2014-09-23 at 8.24.26 AM

Homework: Use the API discussed in class to develop your own implementation of the Bag Class. Make sure you use generics.

Trees

September 24th, 2015

Classwork: Work on assignments.
Homework: Read 9.1 Trees and 9.2 Strategies for Implementing Trees

Not this kind of trees:
trees

or this kind!
example_flowchart_vacationDecisionTree

More like this kind:
maxrestree
BTW This picture is worth a 1,000 words!

It comes from this video I found.