Presentation is loading. Please wait.

Presentation is loading. Please wait.

ITI 1221. Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.

Similar presentations


Presentation on theme: "ITI 1221. Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa."— Presentation transcript:

1 ITI 1221. Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa

2 2 Part I: Interface Objectives: –Understanding and implementing an interface –Creating an interface –Introduction and application of generic data structures

3 3 Interface - Comparable Implements the interface –java.lang.Comparable in Combination class Make all the necessary changes to the class Combination public interface Comparable { // Compares this object with the specified object for order. // Returns a negative integer, zero, or a positive integer // as this object is less than, equal to, or greater than the // specified object. public int compareTo (Object o); }

4 4 Combination (cont..) public class Combination implements Comparable { private int first; private int second; private int third; public Combination(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } public String toString() { return first + ":" + second + ":" + third; } }

5 5 Combination (cont..) public int compareTo(Object obj) { // pre-condition: (obj != null) && (obj instanceof Combination) Combination other = (Combination) obj; int result; if (first < other.first) { result = -1; } else if (first > other.first) { result = 1;} else if (second < other.second) { result = -1;} else if (second > other.second) {result = 1;} else if (third < other.third) {result = -1;} else if (third > other.third) {result = 1;} else { result = 0;} return result; }

6 6 Interface - OrderedStructure Create an interface, called OrderedStructure, that declares the following methods. –int size() –boolean add(Comparable obj) –Object get(int pos) –void remove(int pos) interface OrderedStructure { public abstract int size(); public abstract boolean add(Comparable obj); public abstract Object get(int pos); public abstract void remove(int pos); } Is it essential?

7 7 Class OrderedArray Provide an implementation for each method declared in the interface OrderedStructure: –Instance variables An OrderedArray makes use of an array to store elements. It must also keep track of the number of elements that are currently stored in the array.

8 8 Class OrderedArray public class OrderedArray implements OrderedStructure { private Comparable[ ] elems; private int numElems; public OrderedArray(int size) { elems = new Comparable[size]; numElems = 0; } public int size() {return numElems;} public Object get(int pos) { // pre-condition: 0 <= pos < numElements return elems[pos]; } public void remove(int pos) { // pre-condition: 0 <= pos < numElements for (int i=pos; i<(numElems-1); i++) { elems[i] = elems[i+1]; } numElems--; elems[numElems] = null; }

9 9 Class OrderedArray (cont..) public boolean add(Comparable elem) { if ( elem == null || numElems == elems.length ) return false; boolean inserted = false; for ( int i=0; i<numElems && ! inserted; i++) { if ( elems[i].compareTo( elem ) > 0 ) { for ( int j=numElems; j>i; j-- ) { elems[ j ] = elems[ j-1 ]; } elems[ i ] = elem; inserted = true; numElems++; } if ( ! inserted ) {elems[ numElems++ ] = elem;} return true; } 1.add() method adds an element in increasing order 2.returns true if the element can be successfully added 3.false if the data structure is full or the parameter argument is null

10 10 Let’s Run a Program What do you need? 1.Comparable.java 2.OrderedStructure.java 3.OrderedArray.java 4.Test.java

11 11 Part 2: Stack-based Algorithm Understanding of the stack-based algorithms Program –Validating expressions containing parentheses round, curly square parentheses

12 12 First Algorithm public class Balanced { public static boolean algo1( String s ) { int curly = 0; int square = 0; int round = 0; for ( int i=0; i<s.length(); i++ ) { char c = s.charAt( i ); switch ( c ) { case '{': curly++; break; case '}': curly--; break; case '[': square++; break; case ']': square--; break; case '(': round++; break; case ')': round--; } } return curly == 0 && square == 0 && round == 0; } public static void main( String[] args ) { for ( int i=0; i<args.length; i++ ) { System.out.println( "algo1( \"" + args[ i ] + "\" ) -> " + algo1( args[ i ] ) ); } public class Balanced { public static boolean algo1( String s ) { int curly = 0; int square = 0; int round = 0; for ( int i=0; i<s.length(); i++ ) { char c = s.charAt( i ); switch ( c ) { case '{': curly++; break; case '}': curly--; break; case '[': square++; break; case ']': square--; break; case '(': round++; break; case ')': round--; } } return curly == 0 && square == 0 && round == 0; } public static void main( String[] args ) { for ( int i=0; i<args.length; i++ ) { System.out.println( "algo1( \"" + args[ i ] + "\" ) -> " + algo1( args[ i ] ) ); } What’s happen if you miss to write break?

13 13 Exploit Stack Observation: –A well-balanced expression is an expression such that for each type of parentheses (round, curly and square), the number of opening and closing parentheses are same. –Parentheses rules. Implement a stack-based algorithm to validate an expression.

14 14 Second Algorithm public interface Stack { // Return true if this Stack is empty; and false otherwise. public abstract boolean isEmpty (); // Return The top element of this stack without removing it. public abstract Object peek (); // Removes and returns the element at the top of this stack. public abstract Object pop (); // Puts an element onto the top of this stack. public abstract void push (Object element); }

15 15 Second Algorithm (cont..) public class ArrayStack implements Stack { private Object[] elems; // used to store the elements of this ArrayStack private int top; // designates the first free cell public ArrayStack( int capacity ) { elems = new Object[ capacity ]; top = 0; } public boolean isEmpty() { return top == 0; } public Object peek() { // pre-conditions: ! isEmpty() return elems[ top-1 ]; }... }

16 16 Second Algorithm (cont..) public class ArrayStack implements Stack { … public Object pop() { // pre-conditions: ! isEmpty() // decrements top, then access the value Object saved = elems[ --top ]; elems[ top ] = null; // scrub the memory! return saved; } public void push( Object element ) { // pre-condition: the stack is not full // stores the element at position top, then increments top elems[ top++ ] = element; } }

17 17 Second Algorithm (cont..) public static boolean algo2( String s ) { Stack brackets = new ArrayStack( 100 ); for ( int i=0; i<s.length(); i++ ) { char current = s.charAt( i ); if ( current == '(' || current == '[' || current == '{' ) { brackets.push( new Character( current ) ); } else if ( current == ')' || current == ']' || current == '}' ) { if (brackets.isEmpty()) return false; char top = ( (Character) brackets.pop() ).charValue(); if ( (current == ')' && top != '(') || (current == ']' && top != '[') || (current == '}' && top != '{') ) return false; } } return brackets.isEmpty (); }

18 18 Clarification - Assignment 2 Modifying the interface Stack adding a method clear() public void clear() Purpose:  Clearing Stack, and it will be empty after this call public interface Stack { public abstract boolean isEmpty(); public abstract Object peek(); public abstract Object pop(); public abstract void push( Object element ); }

19 19 Clarification - Assignment 2 (cont..) Class: ArrayStack Implementing the method clear() in the Uses fixed sized array and implements the interface Stack Not Allowed??

20 20 6 Clarification - Assignment 2 (cont..) Calculator Using a stack Implement following operations in Calculator class: Add sub, Exch Dup pstack -top- INTEGER: 3 -bottom- -top- INTEGER: 3 INTEGER: 3 -bottom- -top- INTEGER: 6 -bottom- Example: 3 pstack dup pstack add pstack 3 3 Add

21 21 Clarification - Assignment 2 (cont..) Class DynamicArrayStack  Modify the implementation of the method push() so that the size of the array is increased when the array is full.  Allocate a new array which is bigger than the existing one  Copy all the elements from the old array into the new one  Set the instance variable to point at the new array  Proceed adding the element  The initial size of the stack is determined by the parameter of the constructor of the  class DynamicArrayStack( int capacity )  Every time the array will be full, the method push() will create an array that has 1.5 times its current capacity

22 22 Clarification - Assignment 2 (cont..) Creating a LinkedStack  Variable size (does not have a fixed capacity)  Always uses an amount of memory that is proportional to the number of elements stored in the stack (does not waste any memory)  Efficient (elements are never copied from one array to another)  LinkedStack must implement the instance method booleean equals( Object o )  Returns true other if designates a Stack (any implementation of the interface Stack) that contains the same number of elements as this stack, and each element of the other stack must be “equals” to the corresponding element in this stack  Returns false otherwise  Both stacks must not be changed by the method equals

23 23 The End


Download ppt "ITI 1221. Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa."

Similar presentations


Ads by Google