Category Archives: Resources

2 Stacks problems

Dynamic shrinking. With the array implementations of stack and queue, we doubled the size of the array when it wasn’t big enough to store the next element. If we perform a number of doubling operations, and then delete a lot of elements, we might end up with an array that is much bigger than necessary. Implement the following strategy: whenever the array is 1/4 full or less, shrink it to half the size. Explain why we don’t shrink it to half the size when it is 1/2 full or less.

Stack + max. Create a data structure that efficiently supports the stack operations (pop and push) and also return the maximum element. Assume the elements are integers or reals so that you can compare them.

LinkedList Implementation: iteration

Iteration.

To consider the task of implementing iteration, we start with a snippet of client code that prints all of the items in a collection of strings, one per line:

Stack collection = new Stack();
...
for (String s : collection)
   StdOut.println(s);
...

This foreach statement is shorthand for the following while statement:

Iterator i = collection.iterator();
while (i.hasNext()) { 
   String s = i.next();
   StdOut.println(s);
}

To implement iteration in a collection:

  • Include the following import statement so that our code can refer to Java’s java.util.Iterator interface:
    import java.util.Iterator;
    
  • Add the following to the class declaration, a promise to provide an iterator() method, as specified in the java.lang.Iterable interface:

implements Iterable
  • Implement a method iterator() that returns an object from a class that implements the Iterator interface:
    public Iterator iterator() {
        return new ListIterator();
    }
    
  • Implement a nested class that implements the Iterator interface by including the methods hasNext()next(), and remove(). We always use an empty method for the optional remove() method because interleaving iteration with operations that modify the data structure is best avoided.
    • The nested class ListIterator in Bag.java illustrates how to implement a class that implements the Iterator interface when the underlying data structure is a linked list.
    • The nested class ArrayIterator in ResizingArrayBag.java does the same when the underlying data structure is an array.

Assignments:

Implement the ADT Set, Set_YI.java with the methods below. The Set ADT uses a LinkedList structure. ‌ In mathematics, a Set is a well-defined collection of distinct objects, considered as an object in its own right. In this implementation of Set, the Set ADT behaves like a LinkedList but it doesn’t allow duplicates. Create a Node class.

    1. add(E e)
      Ensures that this collection contains the specified element.
    2. addAll(collection<?> c)
      Adds all of the elements in the specified collection to this set if they’re not already present. The alternate version is to add all elements from Set_YI.
    3. void clear()
      Removes all of the elements from this set (optional operation).
    4. boolean contains(Object o)
      Returns true if this set contains the specified element.
    5. boolean containsAll(collection<?> c)
      Returns true if this set contains all of the elements of the specified collection.
    6. boolean equals(Object o)
      Compares the specified object with this set for equality. The alternate version is to compare objects of Set_YI.
    7. boolean isEmpty()
      Returns true if this set contains no elements.
    8. Iterator<E> iterator()
      Returns an iterator over the elements in this set.
    9. boolean remove(Object o)
      Removes the specified element from this set if it is present (optional operation).
    10. boolean removeAll(collection<?> c) Removes from this set all of its elements that are contained in the specified collection (optional operation). The ? could be whatever you choose.
    11. int size()
      Returns the number of elements in this set (its cardinality).

Implementing a Maze Solver Using Stacks

Using what you learned about solving a maze with the previous tracing assignment, implement a maze solver using the Stack ADT you already implemented or the one supplied in the university resource site.

Stack.java

You can choose the name of your program but make sure you follow the guidelines discussed in the CS classes. The final solution should be a stack with the steps to take from start to end of any maze similar to the given below:

In your previous assignment, you should have a trace similar to the two samples from Leon and Kamola. Pay attention to the final product.

Maze Solver Tracing 2

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;>

Iterable Interface Example

java.lang.Iterable Interface Example




This article shows an example of Iterable interface. This is defined in java.lang package and was introduced with Java 5. The Iterable is defined as a generic type; Iterable<T>, where T type parameter represents the type of elements returned by the iterator.

An object that implements this interface allows it to be the target of the “foreach” statement. The for-each loop is used for iterating over arrays, collections etc. Collection classes and classes where iterations are useful implement this interface.

Before the iterable’s for-each loop was introduced, a way to iterate is to use the for(;;) loop or to use an Iterator; typically the Iterator could be acquired by invoking a collection object’s iterator() method. The iterator has been in Java since Java 1.2.

The Iterable interface provides a clean approach to coding the iteration functionality. An example shows iterating over a List collection with String object elements:

List stringList = new ArrayList<String>();
stringList.add("a");
stringList.add("b");
stringList.add("c");

for (String s : stringList) {
    System.out.println(s);
}

for (int i = 0; i < stringList.size(); i++) {

    System.out.println(stringList [i]);
}

Iterator iter = stringList.iterator();

while (iter.hasNext()) {

    System.out.println(iter.next());

}

Note that there is also a possibility of introducing a bug in the above two code snippets, because of the details.

1. Example

The following example class implements the Iterable interface. The class takes an input array of any type and iterates it in a for-each loop and in reverse order.

Oracle doc

The Iterable interface has one method to override: Iterator<T> iterator().

The example has the iterable implementation MyIterable.java and a tester class MyIterableTester.java.

1.1. The code

MyIterable.java

import java.util.List;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Collections;

public class MyIterable implements Iterable {

    private List list;
    public MyIterable(T [] t) {
        list = Arrays.asList(t);
        Collections.reverse(list);
    }
    @Override
    public Iterator iterator() {
        return list.iterator();
    }

}

MyIterableTester.java

public class MyIterableTester {

    public static void main(String [] args) {

        Integer [] ints = {1, 2, 3};

        MyIterable myList = new MyIterable<>(ints);

        for (Integer i : myList) {
            System.out.println(i);
        }

    }

}

1.2. The output

3
2
1

2. Download Java Source Code

This was an example of java.lang.Iterable Interface Example.

Download
You can download the full source code of this example here: IterableExample.zip

Stack ADT

September 15th, 2015

Classwork
A Stack Collection
Let’s look at a different example of a collection. A stack is a linear collection whose elements are added and removed from the same end. We say that a stack is processed in a last in, first out (LIFO) manner. That is, the last element to be put on a stack will be the first one that gets removed. Said another way, the elements of a stack are removed in the reverse order of their placement on it. In fact, one of the principal uses of a stack in computing is to reverse the order of something (e.g., an undo operation). The processing of a stack is shown in Figure 3.3. Usually a stack is depicted vertically, and we refer to the end to which elements are added and from which they are removed as the top of the stack.

Recall from our earlier discussions that we define an abstract data type (ADT) by identifying a specific set of operations that establishes the valid ways in which we can manage the elements stored in the data structure. We always want to use this concept to formally define the operations for a collection and work within the functionality it provides. That way, we can cleanly separate the interface to the collection from any particular implementation technique used to create it.

conceptual view of a stack

The operations for a stack ADT are listed in Figure 3.4. In stack terminology, we push an element onto a stack and we pop an element off a stack. We can also peek at the top element of a stack, examining it or using it as needed, without ac- tually removing it from the collection. There are also the general operations that allow us to determine if the stack is empty and, if not empty, how many elements it contains.

Sometimes there are variations on the naming conventions for the operations on a collection. For a stack, the use of the terms push and pop is relatively standard. The peek operation is sometimes referred to as top.

push – Adds an element to the top of the stack.
pop – Removes an element from the top of the stack.
peek – Examines the element at the top of the stack.
isEmpty – Determines if the stack is empty.
size – Determines the number of elements on the stack.

A Stack ADT

/**
 *  @author Lewis and Chase
 *
 *  Defines the interface to a stack data structure.
 */
package jss2;
public interface StackADT
{
   /** Adds one element to the top of this stack.
    *  @param element element to be pushed onto stack
    */
   public void push (T element);
   /** Removes and returns the top element from this stack.
    *  @return T element removed from the top of the stack
    */
   public T pop();
   /** Returns without removing the top element of this stack.
    *  @return T element on top of the stack
    */
   public T peek();
   /** Returns true if this stack contains no elements.
    *  @return boolean whether or not this stack is empty
    */
   public boolean isEmpty();
   /** Returns the number of elements in this stack.
    *  @return int number of elements in this stack
    */
   public int size();
   /** Returns a string representation of this stack.
    *  @return String representation of this stack
    */
   public String toString();
}

stackADT UML

Using Stacks: Evaluating Postfix Expressions

Let’s look at a slightly more complicated example. Consider the following infix expression:
(3 * 4 – (2 + 5)) * 4 / 2
The equivalent postfix expression is
3 4 * 2 5 + – 4 * 2 /
Applying our evaluation rule results in:
12 2 5 + – 4 * 2 /
then 12 7 – 4 * 2 /
then 5 4 * 2 /
then 20 2 /
then 10

The algorithm for evaluating a postfix expression using a stack can be expressed as follows: Scan the expression from left to right, identifying each token (operator or operand) in turn. If it is an operand, push it onto the stack. If it is an operator, pop the top two elements off of the stack, apply the operation to them, and push the result onto the stack. When we reach the end of the expression, the element remaining on the stack is the result of the expression. If at any point we attempt to pop two elements off of the stack but there are not two elements on the stack, then our postfix expression was not properly formed. Similarly, if we reach the end of the expression and more than one element remains on the stack, then our expression was not well formed.

postfix op with stack

/**
 * @author Lewis and Chase
 *
 * Demonstrates the use of a stack to evaluate postfix expressions.
 */
import java.util.Scanner;
public class Postfix
{
 /**
  * Reads and evaluates multiple postfix expressions.
  */
 public static void main (String[] args)
 {
   String expression, again;
   int result;
try
{
   Scanner in = new Scanner(System.in);
   do
   {
     PostfixEvaluator evaluator = new PostfixEvaluator();
     System.out.println ("Enter a valid postfix expression: ");
     expression = in.nextLine();
     result = evaluator.evaluate (expression);
     System.out.println();
     System.out.println ("That expression equals " + result);
     System.out.print ("Evaluate another expression [Y/N]? ");
     again = in.nextLine();
     System.out.println();
   }
      while (again.equalsIgnoreCase("y"));
    }
    catch (Exception IOException)
  {
    System.out.println(“Input exception reported");
  } 
 }
}


/**
 * PostfixEvaluator.java
 *
 * Represents an integer evaluator of postfix expressions. Assumes
 * the operands are constants.
 */
import jss2.ArrayStack;
import java.util.StringTokenizer;
public class PostfixEvaluator
{
  /** constant for addition symbol */
  private final char ADD = '+';
  /** constant for subtraction symbol */
  private final char SUBTRACT = '-';
  /** constant for multiplication symbol */
  private final char MULTIPLY = '*';
  /** constant for division symbol */
  private final char DIVIDE = '/';
  /** the stack */
  private ArrayStack stack;

  /**
   * Sets up this evaluator by creating a new stack.
   */
  public PostfixEvaluator()
  {
   stack = new ArrayStack();
  }

  /**
   * Evaluates the specified postfix expression. If an operand is
   * encountered, it is pushed onto the stack. If an operator is
   * encountered, two operands are popped, the operation is
   * evaluated, and the result is pushed onto the stack.
   * @param expr String representation of a postfix expression
   * @return int value of the given expression
   */
  public int evaluate (String expr)
  {
    int op1, op2, result = 0;
    String token;
    StringTokenizer tokenizer = new StringTokenizer (expr);
    while (tokenizer.hasMoreTokens())
    {
      token = tokenizer.nextToken();
    if (isOperator(token))
      {
        op2 = (stack.pop()).intValue();
        op1 = (stack.pop()).intValue();
        result = evalSingleOp (token.charAt(0), op1, op2);
        stack.push (new Integer(result));
       } else
        stack.push (new Integer(Integer.parseInt(token)));
    }
    return result;
  }

  /**
   * Determines if the specified token is an operator.
   * @param token String representing a single token
   * @return boolean true if token is operator
   */
  private boolean isOperator (String token)
  {
    return ( token.equals("+") || token.equals("-") ||
             token.equals("*") || token.equals("/") );
}
  /**
   * Performs integer evaluation on a single expression consisting of
   * the specified operator and operands.
   * @param operation operation to be performed
   * @param op1 the first operand
   * @param op2 the second operand
   * @return int value of the expression
   */
   private int evalSingleOp (char operation, int op1, int op2)
  {
    int result = 0;
    switch (operation)
    {
    case ADD:
      result = op1 + op2;
      break;
    case SUBTRACT:
      result = op1 - op2;
      break;
    case MULTIPLY:
      result = op1 * op2;
      break;
    case DIVIDE:
      result = op1 / op2;
    }
    return result;
   }
 }


postfix UML class diag

Homework:

Implement the ArrayStack Class
Visit edmodo.com to work on a hand trace assignment.

Collections

September 9th, 2015

Collections

  1. Define the concepts and terminology related to collections
  2. Explore the basic structure of the Java Collections API
  3. Discuss the abstract design of collections
  4. Define a set collection
  5. Use a set collection to solve a problem
  6. Examine an array implementation of a set

Homework:
INTRODUCTION TO COLLECTIONS
Abstract Data Types
The Java Collections API

A SET COLLECTION
Interfaces
Iterators
Exceptions

Answer questions on edmodo.com